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>RangelReale/chordlive<file_sep>/src/climport.h
#ifndef H__CLIMPORT__H
#define H__CLIMPORT__H
#include <wx/wx.h>
#include "clpanel.h"
class CLImport : public wxDialog {
DECLARE_CLASS(CLImport)
DECLARE_EVENT_TABLE()
private:
CLPanel *clpanel_;
void OnTextChanged(wxCommandEvent &event);
void OnLyricsChanged(wxCommandEvent &event);
public:
enum {
ID_TITLE,
ID_ARTIST,
ID_TEXT,
ID_PREVIEW,
};
CLImport(wxWindow* parent);
};
#endif // H__CLIMPORT__H
<file_sep>/src/clmain.cpp
#include "clmain.h"
#include "climport.h"
IMPLEMENT_CLASS(CLMain, wxFrame)
BEGIN_EVENT_TABLE(CLMain, wxFrame)
EVT_MENU(IDM_FILE_EXIT, CLMain::onFileExit)
EVT_MENU(IDM_FILE_IMPORT, CLMain::onFileImport)
EVT_MENU(IDM_HELP_ABOUT, CLMain::onHelpAbout)
END_EVENT_TABLE()
CLMain::CLMain() {
// Create the CLMain
Create(NULL, ID_FRAME, wxT("ChordLive"), wxDefaultPosition,
wxDefaultSize, wxDEFAULT_FRAME_STYLE);
// create the main menubar
wxMenuBar *mb = new wxMenuBar;
// create the file menu
wxMenu *fileMenu = new wxMenu;
fileMenu->Append(IDM_FILE_IMPORT, wxT("&Import"));
fileMenu->AppendSeparator();
fileMenu->Append(IDM_FILE_EXIT, wxT("E&xit"));
// add the file menu to the menu bar
mb->Append(fileMenu, wxT("&File"));
// create the help menu
wxMenu *helpMenu = new wxMenu;
helpMenu->Append(IDM_HELP_ABOUT, wxT("About"));
// add the help menu to the menu bar
mb->Append(helpMenu, wxT("&Help"));
// add the menu bar to the CLMain
SetMenuBar(mb);
song_ = new CLPanel(this);
song_->GetSong().LoadFromFile(wxT("M:\\prog\\personal\\chordlive\\songs\\Beatles - I Want to Hold Your Hand.cls"));
}
void CLMain::onHelpAbout(wxCommandEvent &) {
wxMessageBox(wxT("wx-sdl tutorial\nCopyright (C) 2005 <NAME>"),
wxT("about wx-sdl tutorial"), wxOK | wxICON_INFORMATION);
}
void CLMain::onFileImport(wxCommandEvent &event)
{
CLImport d(this);
d.ShowModal();
}
void CLMain::onFileExit(wxCommandEvent &) {
Close();
}
<file_sep>/src/clpanel.cpp
#include "clpanel.h"
#include "clmain.h"
inline void CLPanel::onEraseBackground(wxEraseEvent &) {}
IMPLEMENT_CLASS(CLPanel, wxPanel)
BEGIN_EVENT_TABLE(CLPanel, wxPanel)
EVT_PAINT(CLPanel::onPaint)
EVT_ERASE_BACKGROUND(CLPanel::onEraseBackground)
EVT_KEY_DOWN(CLPanel::onKeyDown)
END_EVENT_TABLE()
CLPanel::CLPanel(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size,
long style, const wxString& name) : wxPanel(parent, id, pos, size, style|wxWANTS_CHARS, name), startpos_(0) {
song_ = new CLSong;
//song_->LoadFromFile(wxT("M:\\prog\\personal\\chordlive\\songs\\Beatles - I Want to Hold Your Hand.cls"));
}
CLPanel::~CLPanel()
{
delete song_;
}
void CLPanel::onPaint(wxPaintEvent &) {
wxBufferedPaintDC dc(this);
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(*wxWHITE_BRUSH);
dc.DrawRectangle(GetClientRect());
CLSongDraw sd(song_);
sd.SetStartPos(startpos_);
sd.Draw(dc, GetClientRect());
}
void CLPanel::onKeyDown(wxKeyEvent &event)
{
if (event.GetKeyCode()==WXK_DOWN)
{
startpos_+=5;
Refresh();
} else if (event.GetKeyCode()==WXK_UP) {
startpos_-=5;
Refresh();
} else if (event.GetKeyCode()==WXK_PAGEDOWN) {
startpos_+=40;
Refresh();
} else if (event.GetKeyCode()==WXK_PAGEUP) {
startpos_-=40;
Refresh();
} else if (event.GetKeyCode()==WXK_HOME) {
startpos_=0;
Refresh();
}
event.Skip();
}
<file_sep>/src/clsong.cpp
#include "clsong.h"
#include <wx/wfstream.h>
#include <wx/tokenzr.h>
/****
*
* CLSongLine
*
***/
CLSongLine::CLSongLine()
{
}
CLSongLine::CLSongLine(linekind_t linekind, const wxString &line, const wxString &chords) :
linekind_(linekind), line_(line), chords_(chords)
{
}
CLSongLine::~CLSongLine()
{
}
bool CLSongLine::IsChord(const wxString &chars)
{
if (chars.Left(1)!=wxT("C") &&
chars.Left(1)!=wxT("D") &&
chars.Left(1)!=wxT("E") &&
chars.Left(1)!=wxT("F") &&
chars.Left(1)!=wxT("G") &&
chars.Left(1)!=wxT("A") &&
chars.Left(1)!=wxT("B"))
return false;
return true;
}
bool CLSongLine::IsChordLine(const wxString &line)
{
bool ret=true;
// detect chord line
wxStringTokenizer chstr(line, wxT(" "), wxTOKEN_DEFAULT);
while ( chstr.HasMoreTokens() ) {
wxString chtoken = chstr.GetNextToken();
if (!CLSongLine::IsChord(chtoken)) {
ret=false;
break;
}
}
return ret;
}
/****
*
* CLSong
*
***/
CLSong::CLSong()
{
/*
lines_.push_back(songlistitem_t(new CLSongLine(CLSongLine::LK_LINE, wxT(""), wxT("C D C D C D"))));
lines_.push_back(boost::shared_ptr<CLSongLine>(new CLSongLine(CLSongLine::LK_SPACE)));
lines_.push_back(songlistitem_t(new CLSongLine(CLSongLine::LK_LINE, wxT("Oh yeah I'll tell you somenthing"), wxT("G D"))));
lines_.push_back(songlistitem_t(new CLSongLine(CLSongLine::LK_LINE, wxT("I think you'll understand"), wxT("Em B"))));
lines_.push_back(songlistitem_t(new CLSongLine(CLSongLine::LK_LINE, wxT("When I say that something"), wxT("G D"))));
lines_.push_back(songlistitem_t(new CLSongLine(CLSongLine::LK_LINE, wxT("I want to hold your hand"), wxT("Em B"))));
lines_.push_back(boost::shared_ptr<CLSongLine>(new CLSongLine(CLSongLine::LK_SPACE)));
lines_.push_back(songlistitem_t(new CLSongLine(CLSongLine::LK_LINE, wxT("I want to hold your hand"), wxT("C D G Em"))));
lines_.push_back(songlistitem_t(new CLSongLine(CLSongLine::LK_LINE, wxT("I want to hold your hand"), wxT("C D G"))));
lines_.push_back(boost::shared_ptr<CLSongLine>(new CLSongLine(CLSongLine::LK_SPACE)));
*/
}
CLSong::~CLSong()
{
}
void CLSong::Clear()
{
title_=wxT("");
artist_=wxT("");
lines_.clear();
}
void CLSong::Parse(const wxString &text)
{
wxString mtext(text);
mtext.Replace(wxT("\t"), wxT(" "));
CLSongLine::linekind_t n_linekind = CLSongLine::LK_NONE;
wxString n_lyrics(wxT("")), n_chords(wxT(""));
lines_.clear();
wxStringTokenizer str(mtext, wxT("\n"), wxTOKEN_RET_EMPTY);
while ( str.HasMoreTokens() )
{
wxString token = str.GetNextToken();
n_linekind=CLSongLine::LK_NONE;
// white line
if (token.IsEmpty())
{
if (!n_chords.IsEmpty())
lines_.push_back(songlistitem_t(new CLSongLine(CLSongLine::LK_LINE, wxT(""), n_chords)));
n_linekind=CLSongLine::LK_SPACE;
n_lyrics=wxT("");
n_chords=wxT("");
lines_.push_back(songlistitem_t(new CLSongLine(n_linekind, n_lyrics, n_chords)));
} else {
if (CLSongLine::IsChordLine(token)) {
n_chords=token.Trim(false);
} else {
n_linekind=CLSongLine::LK_LINE;
n_lyrics=token.Trim(false);
lines_.push_back(songlistitem_t(new CLSongLine(n_linekind, n_lyrics, n_chords)));
n_lyrics=n_chords=wxT("");
}
}
}
}
void CLSong::LoadFromStream(wxInputStream &stream)
{
wxXmlDocument doc;
if (!doc.Load(stream))
throw new CLSongException(_("Invalid ChordLive song data"));
if (doc.GetRoot()->GetName() != wxT("chordlivesong"))
throw new CLSongException(_("Invalid ChordLive song data"));
Clear();
wxXmlNode *child = doc.GetRoot()->GetChildren();
while (child) {
if (child->GetName() == wxT("title")) {
title_=child->GetNodeContent();
} else if (child->GetName() == wxT("artist")) {
artist_=child->GetNodeContent();
} else if (child->GetName() == wxT("keywords")) {
// TODO
} else if (child->GetName() == wxT("lines")) {
// load lines
LoadLines(child);
}
child = child->GetNext();
}
}
void CLSong::LoadLines(wxXmlNode *lines)
{
wxXmlNode *child = lines->GetChildren();
while (child) {
if (child->GetName() == wxT("line")) {
LoadLine(child);
}
child = child->GetNext();
}
}
void CLSong::LoadLine(wxXmlNode *line)
{
CLSongLine::linekind_t n_linekind = CLSongLine::LK_LINE;
wxString n_lyrics(wxT("")), n_chords(wxT(""));
n_linekind=line->GetPropVal(wxT("kind"), wxT("line"))==wxT("space")?CLSongLine::LK_SPACE:CLSongLine::LK_LINE;
wxXmlNode *child = line->GetChildren();
while (child) {
if (child->GetName() == wxT("lyrics")) {
n_lyrics=child->GetNodeContent();
} else if (child->GetName() == wxT("chords")) {
n_chords=child->GetNodeContent();
}
child = child->GetNext();
}
if (n_linekind == CLSongLine::LK_SPACE || !n_lyrics.IsEmpty() || !n_chords.IsEmpty())
lines_.push_back(songlistitem_t(new CLSongLine(n_linekind, n_lyrics, n_chords)));
}
void CLSong::SaveToStream(wxOutputStream &stream)
{
}
void CLSong::LoadFromFile(const wxString &filename)
{
wxFileInputStream f(filename);
LoadFromStream(f);
}
void CLSong::SaveToFile(const wxString &filename)
{
wxFileOutputStream f(filename);
SaveToStream(f);
}
/****
*
* CLSongDraw
*
***/
CLSongDraw::CLSongDraw(CLSong *song) : song_(song)
{
}
CLSongDraw::~CLSongDraw()
{
}
void CLSongDraw::Draw(wxDC &dc, const wxRect &rect)
{
wxFont titlefont(13, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD);
wxFont linefont(11, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);
wxFont chordfont(11, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD);
int spos=-1*startpos_;
dc.SetFont(titlefont);
dc.DrawText(song_->title_, 10, spos);
spos+=dc.GetTextExtent(song_->title_).GetHeight();
dc.DrawText(song_->artist_, 10, spos);
spos+=dc.GetTextExtent(song_->artist_).GetHeight();
spos+=dc.GetTextExtent(wxT("M")).GetHeight();
for (CLSong::songlist_t::const_iterator i=song_->lines_.begin(); i!=song_->lines_.end(); i++)
{
switch ((*i)->GetLineKind()) {
case CLSongLine::LK_LINE:
dc.SetFont(chordfont);
dc.DrawText((*i)->GetChords(), 10, spos);
spos+=dc.GetTextExtent((*i)->GetChords()).GetHeight();
dc.SetFont(linefont);
dc.DrawText((*i)->GetLine(), 10, spos);
spos+=dc.GetTextExtent((*i)->GetLine()).GetHeight();
break;
case CLSongLine::LK_SPACE:
dc.SetFont(linefont);
spos+=dc.GetTextExtent(wxT("M")).GetHeight();
break;
}
}
}
<file_sep>/src/clapp.h
#ifndef H__CLAPP__H
#define H__CLAPP__H
#include <iostream>
#include <wx/wx.h>
#include "clmain.h"
class CLApp : public wxApp {
DECLARE_CLASS(CLApp)
private:
CLMain *frame;
public:
virtual bool OnInit();
};
#endif // H__CLAPP__H<file_sep>/src/clsong.h
#ifndef H__CLSONG__H
#define H__CLSONG__H
#include <wx/wx.h>
#include <deque>
#include <stdexcept>
#include <boost/shared_ptr.hpp>
#include <wx/xml/xml.h>
// forward
class CLSongDraw;
/****
*
* CLSongException
*
***/
class CLSongException : public std::exception {
public:
CLSongException(const wxString &what) throw() : exception()
{ what_=what; }
virtual ~CLSongException() throw () {}
const wxString &what() { return what_; }
private:
wxString what_;
};
/****
*
* CLSongLine
*
***/
class CLSongLine
{
public:
enum linekind_t {
LK_NONE,
LK_LINE,
LK_SPACE,
};
CLSongLine();
CLSongLine(linekind_t linekind, const wxString &line = wxEmptyString, const wxString &chords = wxEmptyString);
virtual ~CLSongLine();
static bool IsChord(const wxString &chars);
static bool IsChordLine(const wxString &line);
linekind_t GetLineKind() { return linekind_; }
const wxString &GetLine() { return line_; }
const wxString &GetChords() { return chords_; }
private:
linekind_t linekind_;
wxString chords_, line_;
};
/****
*
* CLSong
*
***/
class CLSong
{
public:
CLSong();
virtual ~CLSong();
const wxString &GetTitle() { return title_; }
void SetTitle(const wxString &title) { title_=title; }
const wxString &GetArtist() { return artist_; }
void SetArtist(const wxString &artist) { artist_=artist; }
void Clear();
void Parse(const wxString &text);
void LoadFromFile(const wxString &filename);
void SaveToFile(const wxString &filename);
void LoadFromStream(wxInputStream &stream);
void SaveToStream(wxOutputStream &stream);
protected:
void LoadLines(wxXmlNode *lines);
void LoadLine(wxXmlNode *line);
private:
friend class CLSongDraw;
typedef boost::shared_ptr<CLSongLine> songlistitem_t;
typedef std::deque< songlistitem_t > songlist_t;
wxString title_, artist_;
songlist_t lines_;
};
/****
*
* CLSongDraw
*
***/
class CLSongDraw
{
public:
CLSongDraw(CLSong *song);
virtual ~CLSongDraw();
int GetStartPos() { return startpos_; }
void SetStartPos(int startpos) { startpos_=startpos; }
void Draw(wxDC &dc, const wxRect &rect);
private:
CLSong *song_;
int startpos_;
};
#endif // H__CLSONG__H
<file_sep>/src/clapp.cpp
#include "clapp.h"
bool CLApp::OnInit() {
// create the CLMain
frame = new CLMain;
frame->SetClientSize(640, 480);
frame->Centre();
frame->Show();
// Our CLMain is the Top Window
SetTopWindow(frame);
// initialization should always succeed
return true;
}
IMPLEMENT_CLASS(CLApp, wxApp)
IMPLEMENT_APP(CLApp)
<file_sep>/src/climport.cpp
#include "climport.h"
#include <wx/statline.h>
IMPLEMENT_CLASS(CLImport, wxFrame)
BEGIN_EVENT_TABLE(CLImport, wxDialog)
EVT_TEXT(ID_TITLE, CLImport::OnTextChanged)
EVT_TEXT(ID_ARTIST, CLImport::OnTextChanged)
EVT_TEXT(ID_TEXT, CLImport::OnLyricsChanged)
END_EVENT_TABLE()
CLImport::CLImport(wxWindow* parent) {
Create(parent, wxID_ANY, wxT("ChordLive Import"), wxDefaultPosition,
wxDefaultSize, wxDEFAULT_FRAME_STYLE);
wxBoxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
// TITLE
topsizer->Add(new wxStaticText(this, wxID_ANY, _("Title")), 0, wxALIGN_CENTER_HORIZONTAL|wxALL|wxGROW, 3);
wxTextCtrl *title = new wxTextCtrl(this, ID_TITLE, wxEmptyString, wxDefaultPosition, wxSize(200, -1));
topsizer->Add(title, 0, wxALL|wxGROW, 3);
// ARTIST
topsizer->Add(new wxStaticText(this, wxID_ANY, _("Artist")), 0, wxALIGN_CENTER_HORIZONTAL|wxALL|wxGROW, 3);
wxTextCtrl *artist = new wxTextCtrl(this, ID_ARTIST, wxEmptyString, wxDefaultPosition, wxSize(200, -1));
topsizer->Add(artist, 0, wxALL|wxGROW, 3);
// TEXT SIZER
wxFlexGridSizer *textsizer = new wxFlexGridSizer(2, 2);
textsizer->AddGrowableRow(1, 1);
textsizer->AddGrowableCol(0, 1);
textsizer->AddGrowableCol(1, 1);
textsizer->SetFlexibleDirection(wxBOTH);
topsizer->Add(textsizer, 1, wxALL|wxGROW, 3);
// TEXT
textsizer->Add(new wxStaticText(this, wxID_ANY, _("Lyrics Text")), 0, wxALIGN_CENTER_HORIZONTAL|wxALL|wxGROW, 3);
// PREVIEW
textsizer->Add(new wxStaticText(this, wxID_ANY, _("Preview")), 0, wxALIGN_CENTER_HORIZONTAL|wxALL|wxGROW, 3);
// TEXT
wxTextCtrl *text = new wxTextCtrl(this, ID_TEXT, wxEmptyString, wxDefaultPosition, wxSize(400, 300), wxTE_MULTILINE);
wxFont linefont(9, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);
text->SetFont(linefont);
textsizer->Add(text, 1, wxALL|wxGROW, 3);
// PREVIEW
clpanel_ = new CLPanel(this, ID_PREVIEW, wxDefaultPosition, wxSize(400, 300));
textsizer->Add(clpanel_, 1, wxALL|wxGROW, 3);
// divider line
wxStaticLine *line = new wxStaticLine(this, wxID_STATIC, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL);
topsizer->Add(line, 0, wxGROW|wxALL, 3);
// BUTTONS
wxBoxSizer *buttonsizer = new wxBoxSizer(wxHORIZONTAL);
topsizer->Add(buttonsizer, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 3);
// ok button
wxButton* ok = new wxButton ( this, wxID_OK, _("&OK"), wxDefaultPosition, wxDefaultSize, 0 );
buttonsizer->Add(ok, 0, wxALIGN_CENTER_VERTICAL|wxALL, 3);
// cancel button
wxButton* cancel = new wxButton ( this, wxID_CANCEL, _("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
buttonsizer->Add(cancel, 0, wxALIGN_CENTER_VERTICAL|wxALL, 3);
SetSizer(topsizer);
topsizer->SetSizeHints(this);
CentreOnScreen();
}
void CLImport::OnTextChanged(wxCommandEvent &event)
{
clpanel_->GetSong().SetTitle( ((wxTextCtrl*)FindWindow(ID_TITLE))->GetValue() );
clpanel_->GetSong().SetArtist( ((wxTextCtrl*)FindWindow(ID_ARTIST))->GetValue() );
clpanel_->Refresh();
}
void CLImport::OnLyricsChanged(wxCommandEvent &event)
{
clpanel_->GetSong().Parse( ((wxTextCtrl*)FindWindow(ID_TEXT))->GetValue() );
clpanel_->Refresh();
}
<file_sep>/src/clmain.h
#ifndef H__CLMAIN__H
#define H__CLMAIN__H
#include <wx/wx.h>
#include "clpanel.h"
class CLMain : public wxFrame {
DECLARE_CLASS(CLMain)
DECLARE_EVENT_TABLE()
private:
void onFileImport(wxCommandEvent &event);
void onFileExit(wxCommandEvent &event);
void onHelpAbout(wxCommandEvent &event);
CLPanel *song_;
public:
enum {
ID_FRAME = 10000,
ID_PANEL,
IDM_FILE_IMPORT,
IDM_FILE_EXIT,
IDM_HELP_ABOUT
};
CLMain();
};
#endif // H__CLMAIN__H
<file_sep>/src/clpanel.h
#ifndef H__CLPANEL__H
#define H__CLPANEL__H
#include <wx/wx.h>
#include <wx/dcbuffer.h>
#include <wx/image.h>
#include "clsong.h"
class CLPanel : public wxPanel {
DECLARE_CLASS(CLPanel)
DECLARE_EVENT_TABLE()
private:
CLSong *song_;
int startpos_;
void onPaint(wxPaintEvent &event);
void onEraseBackground(wxEraseEvent &event);
void onKeyDown(wxKeyEvent &event);
public:
CLPanel(wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL, const wxString& name = wxT("panel"));
~CLPanel();
CLSong &GetSong() { return *song_; }
};
#endif // H__CLPANEL__H
| a96faf238d7d30a64b3cff7d8c7532074123f3be | [
"C++"
] | 10 | C++ | RangelReale/chordlive | 5529f61bdd10deed1cd5c8070f9bd9557f318719 | 0c93a8bd0a29c44ba0c7c206e353c2c77bbe8164 |
refs/heads/master | <file_sep>[tool.poetry]
name = "websocket-camera-controll-server"
version = "0.1.0"
description = ""
authors = ["Takahiro55555 <<EMAIL>>"]
license = "MIT"
[tool.poetry.dependencies]
python = "^3.7"
tornado = "^6.0.4"
bcrypt = "^3.1.7"
sqlalchemy = "^1.3.15"
[tool.poetry.dev-dependencies]
autopep8 = "^1.5"
pylint = "^2.4.4"
pytest = "^5.4.1"
websocket-client = "^0.57.0"
requests = "^2.23.0"
[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
<file_sep># 標準ライブラリ
import os
import logging
import secrets
import ssl
# 外部ライブラリ
import bcrypt
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.escape
import tornado.options
from tornado.options import define, options
# 自作モジュール
from module.password_hash import hash_password, check_password
# 最初に以下のモジュールを読みこまないとその他のモジュールでオプションが見つからずにエラーが発生する
from tornado_options import *
from module.tables import create_tables
from module.root_handler import RootHandler
from module.controller_handler import ControllerHandler
from module.account_handler import AccountHandler
from module.token_handler import TokenHandler
from module.relay_handler import RelayHandler
from module.ws_relay_handler import WsRelayHandler
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", RootHandler),
(r"/controller", ControllerHandler),
(r"/api/v1/accounts", AccountHandler),
(r"/api/v1/tokens", TokenHandler),
(r"/api/v1/relays", RelayHandler),
(r"/ws/v1/relays/([0-9a-zA-Z]+\-[0-9a-zA-Z]+)", WsRelayHandler),
]
settings = dict(
static_path=os.path.join(os.path.dirname(__file__), "static"),
template_path=os.path.join(os.path.dirname(__file__), "templates"),
autoescape="xhtml_escape",
debug=options.debug
)
tornado.web.Application.__init__(self, handlers, **settings)
if __name__ == "__main__":
# 設定ファイルや、コマンドラインからハッシュ化されたパスワードが渡されていない場合
if options.hashed_admin_password == None:
options.hashed_admin_password = <PASSWORD>password(options.admin_password)
options.admin_password = None
# テーブルを作成する
create_tables()
app = Application()
# NOTE: HTTPServerではAutoreloadモードが使えない
# Ref: https://www.tornadoweb.org/en/stable/guide/running.html
# > Autoreload mode is not compatible with the multi-process mode of HTTPServer.
if options.debug:
app.listen(options.port)
else:
if options.use_ssl:
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain(options.ssl_crt_file_path, options.ssl_key_file_path)
server = tornado.httpserver.HTTPServer(app, ssl_options=ssl_ctx)
else:
server = tornado.httpserver.HTTPServer(app)
server.bind(options.port)
# NOTE: マルチプロセスにすると、同一のリレー(WebSocket)が別々のプロセスで生成されてしまい、
# 上手く転送をすることができなくなってしまう。
server.start(1) # プロセス数を設定する
tornado.ioloop.IOLoop.instance().start()
<file_sep>import bcrypt
def hash_password(password, rounds=12):
return bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds)).decode()
def check_password(user_password, hashed_password):
return bcrypt.checkpw(user_password.encode(), hashed_password.encode())
def main():
from getpass import getpass
raw_password = getpass()
if len(raw_password) < 8:
print("Too short pasword. We required more than 8 charactors.")
return
hashed_password = hash_password(raw_password)
print(hashed_password)
if __name__ == "__main__":
main()<file_sep># WebSocketRelayServer
※)電気通信事業法の適用がある「他人の通信を媒介」するサービスとなってしまうため、本システムは一般公開しておりません。
## これは何?
WebSocketのデータを中継するためのWebサーバです。
PythonのWebフレームワークである
[Tornado](https://www.tornadoweb.org/en/stable/)
を使用しています。
また、トークンや認証情報(メールアドレス、ハッシュ化したパスワード)を保存するためのDBにはSQLiteを、ORMには
[SQLAlchemy](https://www.sqlalchemy.org/)
を使用しています。
バーチャルホストとHTTPSに対応させるために、
[jwilder/nginx-proxy](https://hub.docker.com/r/jwilder/nginx-proxy)
というDockerイメージと
[jrcs/letsencrypt-nginx-proxy-companion](https://hub.docker.com/r/jrcs/letsencrypt-nginx-proxy-companion)
というDockerイメージを使用し、公開しました。
## なぜ作った!?
スマートフォンのブラウザから、ジャイロセンサーの値をRaspberry Piへ送信し、スマートフォンの傾きとRaspberryPiのカメラの傾きを連動させようと考えたのがきっかけです。
[AWS IoT](https://docs.aws.amazon.com/ja_jp/iot/latest/developerguide/what-is-aws-iot.html)
や
[Pusher](https://pusher.com/)
を使用しなかったのは、ただ単にこのようなシステムを作って見たかったからです。
## 構成
- 端末:iPhone7
- 制御ボード:Raspberry Pi 4
- Google Compute Engine f1-micro(vCPU x 1、メモリ 0.6 GB)
- サーバゾーン:us-east
- 端末地域:日本
- 動画配信:[WebRTC Native Client Momo](https://github.com/shiguredo/momo)
## 動作の様子
以下の動画は、実際に使用した際の動画です。クリックすることで見ることができます(Twitter)。
[](https://twitter.com/i/status/1254174635333058560)
<file_sep># 標準ライブラリ
import logging
import secrets
# 外部ライブラリ
import tornado.web
from tornado.options import define, options
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import sqlalchemy.exc
# 自作モジュール
from module.tables import User, Token
from module.password_hash import hash_password, check_password
# HACK: エラーメッセージの作成をスマートにする
# 現在のままではタイプミスによる間違ったキーによるデータを送信してしまう可能性がある
# データの受信もJSONで行うようにする
#
# NOTE: トークンは一意なID部とパスワード部から成り、ハイフンで区切る
# パスワード部はハッシュ化した後にDBへ登録する
class TokenHandler(tornado.web.RequestHandler):
engine = create_engine(
options.db_uri_type + options.db_path, echo=options.sql_echo)
token_nbytes = 32
token_passwd_nbytes = 36
token_registration_try_time = 10 # トークンに重複が起きた際、トークンを再生成する回数
def get(self):
self.set_status(501, reason="Not Implemented")
def post(self):
errors = []
# 未入力フィールドの確認
try:
user_email = self.get_argument("userEmail")
except tornado.web.MissingArgumentError as e:
errors.append(
dict(
field="userEmail",
code="missing_argument",
message=e.log_message
)
)
try:
raw_user_password = self.get_argument("userPassword")
except tornado.web.MissingArgumentError as e:
errors.append(
dict(
field="userPassword",
code="missing_argument",
message=e.log_message
)
)
if len(errors) != 0:
del raw_user_password
self.write(dict(
message="Missing argument",
errors=errors
))
return
# DBからユーザ情報を照会、取得
session = sessionmaker(bind=self.engine)()
try:
result = session.query(User.hashed_user_password, User.user_id).filter(
User.email == user_email).one_or_none()
except sqlalchemy.exc.IntegrityError as e:
del raw_user_password
msg = dict(
message="Database error occured",
errors=[(
dict(
field="userEmail",
code="db_error",
message=str(e)
)
)]
)
self.write(msg)
return
# ユーザが存在しなかった場合
if result == None:
del raw_user_password
msg = dict(
message="%s is not exist" % user_email,
errors=[
dict(
field="userEmail",
code="invalid_user",
message="user email is not correct or have no enough authorization"
)
]
)
self.write(msg)
return
hashed_user_password = result[0]
user_id = result[1]
# 入力されたユーザの有効性パスワードの有効性を確認
if not check_password(raw_user_password, hashed_user_password):
del raw_user_password
msg = dict(
message="User passward is not correct",
errors=[
dict(
field="userPassword",
code="invalid_password",
message="password is not correct"
)
]
)
self.write(msg)
return
del raw_user_password
# トークンのパスワード部を生成
raw_token_passwd = secrets.token_hex(nbytes=self.token_passwd_nbytes)
hashed_token_passwd = hash_password(raw_token_passwd)
# トークンを生成
# 重複が生じる可能性を考慮し、複数回トークンの生成を試みる
db_token = Token()
is_registration_succeed = False
for _ in range(self.token_registration_try_time):
token_id = secrets.token_hex(nbytes=self.token_nbytes)
db_token.token_id = token_id
db_token.hashed_token_password = <PASSWORD>
db_token.user_id = user_id
try:
session.add(instance=db_token)
session.commit()
except sqlalchemy.exc.IntegrityError as e:
continue
except Exception as e:
errors.append(dict(
code="db_error",
message=str(e)
))
break
is_registration_succeed = True
break
if len(errors) != 0:
del token_id, raw_token_passwd
msg = dict(
message="Database error occurred",
errors=errors
)
self.write(msg)
return
# ユニークなトークンを生成できなかった場合のエラー(必ずしもそうとは限らない)
if not is_registration_succeed:
del token_id, raw_token_passwd
msg = dict(
message="Token generator failed, please try again",
errors=[
dict(
code="token_generator_error",
message="Could not generate unique token, please try again"
)
]
)
self.write(msg)
return
# ユーザが扱いやすいようにID部とパスワード部を結合し、送信
combined_token = "%s-%s" % (token_id, raw_token_passwd)
msg = dict(
message="Success",
token=combined_token
)
self.write(msg)
del token_id, raw_token_passwd, combined_token
session.close()
<file_sep># 標準ライブラリ
import re
# 外部ライブラリ
import tornado.web
from tornado.options import define, options
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import sqlalchemy.exc
# 自作モジュール
from module.tables import User
from module.password_hash import hash_password, check_password
# HACK: エラーメッセージの作成をスマートにする
# 現在のままではタイプミスによる間違ったキーによるデータを送信してしまう可能性がある
# データの受信もJSONで行うようにする
class AccountHandler(tornado.web.RequestHandler):
engine = create_engine(options.db_uri_type +
options.db_path, echo=options.sql_echo)
def get(self):
self.set_status(501, reason="Not Implemented")
def post(self):
errors = []
# 未入力フィールドの確認
try:
admin_email = self.get_argument("adminEmail")
except tornado.web.MissingArgumentError as e:
errors.append(
dict(
field="adminEmail",
code="missing_argument",
message=e.log_message
)
)
try:
raw_admin_password = self.get_argument("adminPassword")
except tornado.web.MissingArgumentError as e:
errors.append(
dict(
field="adminPassword",
code="missing_argument",
message=e.log_message
)
)
try:
user_email = self.get_argument("userEmail")
except tornado.web.MissingArgumentError as e:
errors.append(
dict(
field="userEmail",
code="missing_argument",
message=e.log_message
)
)
try:
raw_user_password = self.get_argument("userPassword")
except tornado.web.MissingArgumentError as e:
errors.append(
dict(
field="userPassword",
code="missing_argument",
message=e.log_message
)
)
if len(errors) != 0:
self.write(dict(
message="Missing argument",
errors=errors
))
return
# メールアドレスの確認(正規表現)
reg = r"^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$"
if re.fullmatch(reg, user_email) == None:
msg = dict(
message="Email addres is not valid.",
errors=[
dict(
field="userEmail",
code="invalid_email",
message="user email addres does not match the regular expression(`%s`). " % reg
)
]
)
self.write(msg)
return
# 管理者名の有効性を確認
if admin_email != options.admin_email:
msg = dict(
message="%s is not admin or not exists",
errors=[
dict(
field="adminEmail",
code="invalid_user",
message="admin email is not correct or have no enough authorization"
)
]
)
self.write(msg)
return
# 管理者パスワードの有効性を確認
if not check_password(raw_admin_password, options.hashed_admin_password):
msg = dict(
message="Admin passward is not correct",
errors=[
dict(
field="adminPassword",
code="invalid_password",
message="password is not correct"
)
]
)
self.write(msg)
return
# パスワードのハッシュ化
hashed_user_password = hash_password(raw_user_password)
del raw_user_password
# DBへの登録
session = sessionmaker(bind=self.engine)()
user = User()
user.hashed_user_password = <PASSWORD>
user.email = user_email
try:
session.add(instance=user)
session.commit()
except sqlalchemy.exc.IntegrityError as e:
errors.append(
dict(
field="userEmail",
code="db_error",
message=str(e)
)
)
if len(errors) != 0:
msg = dict(
message="Database error occurred",
errors=errors
)
self.write(msg)
return
msg = dict(
message="Success"
)
self.write(msg)
<file_sep># TODO: クラス名とファイル名を一致させる
# コネクション切断時のステータスコードをきちんと考える
import datetime
import secrets
# 外部ライブラリ
from tornado.options import define, options
# TODO: XSSを防ぐために、送信する文字列のエスケープを行うようにする
# HACK: client_id ではなく、 session_id のほうが適切
class RelayPaire:
"""中継のために必要なデータ及びオブジェクト、関数を持つ
Returns
-------
None
"""
def __init__(self, connection_limit=2, client_id_nbytes=32, log_func=print):
self.__connection_limit = connection_limit
self.__client_id_nbytes = client_id_nbytes
self.__ws_clients = dict()
self.__log_func = log_func
self.__log_func("New realay paire created")
def relay(self, ws_con, public_msg={}, echo=False):
for key in self.__ws_clients:
ws_con_tmp = self.__ws_clients[key]["ws_con"]
if (not echo) and (ws_con == ws_con_tmp):
continue
if ws_con_tmp == None:
continue
ws_con_tmp.write_message(public_msg)
def connect_client(self, ws_con, msg={}):
# 接続上限数の確認
valid_clients_num = 0
is_duplicate = False
for _,v in self.__ws_clients.items():
if not v["is_exited"]:
if v['ws_con'] == ws_con:
is_duplicate = True
break
valid_clients_num += 1
if is_duplicate:
response = dict()
response["header"] = dict(
client_id = None
)
response["errors"] = [dict(
field="header.cmd",
code="duplicate_connection",
message="Already connected"
)]
ws_con.write_message(response)
return
if valid_clients_num >= self.__connection_limit:
ws_con.close(code=5000, reason="This relay has already reached its connection limit")
return
# クライアントIDを生成し、クライアントIDをキーにしてWebSocket接続オブジェクトを格納する
# NOTE: RelayPairオブジェクト内でのクライアントIDの重複の可能性を排除するためにプレフィックスを付加
client_id = "%d-%s" % (len(self.__ws_clients), secrets.token_urlsafe(nbytes=self.__client_id_nbytes))
self.__ws_clients[client_id] = dict(ws_con=ws_con, is_exited=False)
ws_con.client_id = client_id # WebSocketオブジェクトにクライアントIDを設定
# レスポンスの作成
response_header = dict(
client_id = client_id
)
response = dict(
header = response_header,
contents = None
)
ws_con.write_message(response)
def reconnect_client(self, ws_con, client_id):
"""
何らかの原因によりWebSocketが切断された際に再接続するための関数
"""
# 送られてきたクライアントIDが有効なものかどうかを確認
if not self.__is_valid_client_id(client_id):
ws_con.close(code=5000, reason="This client id is not valid")
return
if self.is_autholized_connecton(ws_con):
response = dict()
response["header"] = dict(
client_id = None
)
response["errors"] = [dict(
field="header.cmd",
code="duplicate_connection",
message="Already connected by this connection"
)]
ws_con.write_message(response)
return
if self.__is_connectiong_client_id(client_id):
ws_con.close(code=5000, reason='Connection already exists by this client_id')
return
self.__ws_clients[client_id]["ws_con"] = ws_con
ws_con.client_id = client_id
response = dict(
header = dict(
status = 'ok'
),
contents = None
)
ws_con.write_message(response)
def ws_con_close(self, ws_con):
"""
当該WebSocketを閉じる際に実行するべき関数。
割り当てられたクライアントIDで認証することによって再接続することはできる。
"""
for key in self.__ws_clients:
ws_con_tmp = self.__ws_clients[key]["ws_con"]
if ws_con_tmp == ws_con:
self.__ws_clients[key]["ws_con"] = None
return
# そもそも登録されていなかった場合
ws_con.close(code=5000, reason="Not registered to this relay")
def exit(self, ws_con):
"""
当該WebSocketを閉じ、退出フラグを立てる
割り当てられたクライアントIDを使用しての再接続も不可能
"""
for key in self.__ws_clients:
ws_con_tmp = self.__ws_clients[key]["ws_con"]
if ws_con_tmp == ws_con:
ws_con_tmp.close(code=5000, reason="Closed by client")
self.__ws_clients[key]["ws_con"] = None
self.__ws_clients[key]["is_exited"] = True
break
def is_autholized_connecton(self, ws_con):
for _,v in self.__ws_clients.items():
if v['ws_con'] is ws_con:
return True
return False
def is_host_connection(self, ws_con):
"""
将来的にホストを識別するようになった時のための関数
"""
return self.is_autholized_connecton(ws_con)
def __is_valid_client_id(self, client_id):
"""
クライアントIDがリレー中に存在し、退出フラグが立っていないことを確認
"""
if not client_id in self.__ws_clients:
return False
if self.__ws_clients[client_id]["is_exited"]:
return False
return True
def __is_connectiong_client_id(self, client_id):
"""
当該クライアントIDのクライアントが接続中であることを確認
"""
if not self.__is_valid_client_id(client_id):
return False
if self.__ws_clients[client_id]["ws_con"] == None:
return False
return True
def __del__(self):
print('deleting')
for key in self.__ws_clients:
ws_con_tmp = self.__ws_clients[key]["ws_con"]
if ws_con_tmp == None:
continue
ws_con_tmp.close(code=5000, reason="This relay is deleted")
<file_sep># 標準ライブラリ
# 外部ライブラリ
import tornado.web
from tornado.options import define, options
# 自作ライブラリ
# TODO: このクラスと、HTMLテンプレートは削除
# 今後このサーバでは、Webページの提供は行わない予定のため
class RootHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
<file_sep>"""
Tornadoのオプション設定をまとめておくファイル
NOTE: このファイルは 'main.py' と同じ階層のディレクトリに置くこと
"""
import os
import secrets
import tornado.options
from tornado.options import define, options
define("port", default=80, type=int, help="port to listen on")
define("debug", default=False, type=bool, help="enable debug mode")
define("admin_email", secrets.token_urlsafe()+"<EMAIL>", type=str,
help="Default email is random string, so you must set 'admin_email' by hand when you use admin functions.")
define("admin_password", secrets.token_urlsafe(), type=str,
help="Default password is random string, so you must set 'admin_password' by hand when you use admin functions.")
define("hashed_admin_password", None, type=str,
help="hashed admin passowrd")
# SSL の設定
define("use_ssl", default=False, type=bool, help="Enable SSL")
define("ssl_crt_file_path", default="", type=str, help="SSL cert file`s absolute path")
define("ssl_key_file_path", default="", type=str, help="SSL key file`s absolute path")
# DBファイル名とパスの設定
define("db_name", "RelayServer.sqlite3", help="sqlite file name")
define("db_path", os.path.join(
os.path.dirname(__file__), options.db_name), help="sqlite file path")
# 設定ファイル名とパスの設定
define("config_file_name", "server.conf", help="config file name")
define("config_file_path", os.path.join(
os.path.dirname(__file__), options.config_file_name), help="config file path")
define("sql_echo", default=False,
help="If True, the SQLAlchemy Engine will log all statements")
define("tokens_lifespan_sec", default=7776000,
help="default lifespan: 7776000sec (90days)")
define("db_uri_type", default="sqlite:///",
help="DB name, such as 'sqlite:///' and 'mysql:///'. This option using as 'sqlite:///<file_path>'")
define("relays_lifespan_sec", default=7776000,
help="default lifespan: 7776000sec (90days)")
# NOTE: 設定ファイル名やパスをコマンドラインから受け取ることがあるため、はじめにコマンドラインのオプションを読み込む
tornado.options.parse_command_line(final=False)
options.config_file_path = os.path.join(
os.path.dirname(__file__), options.config_file_name)
# NOTE: 設定ファイルのオプションを読み込む
tornado.options.parse_config_file(options.config_file_path, final=False)
# NOTE: コマンドラインの設定を優先するため再度コマンドラインのオプションを読み込む
tornado.options.parse_command_line()
options.db_path = os.path.join(os.path.dirname(__file__), options.db_name)
<file_sep># 標準ライブラリ
import datetime
import logging
import secrets
# 外部ライブラリ
import tornado.web
from tornado.options import define, options
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import sqlalchemy.exc
# 自作モジュール
from module.tables import User, Token, Relay
from module.password_hash import hash_password, check_password
# HACK: エラーメッセージの作成をスマートにする
# 現在のままではタイプミスによる間違ったキーによるデータを送信してしまう可能性がある
class RelayHandler(tornado.web.RequestHandler):
engine = create_engine(
options.db_uri_type + options.db_path, echo=options.sql_echo)
relay_id_nbytes = 32
relay_passwd_nbytes = 36
relay_registration_try_time = 10 # トークンに重複が起きた際、トークンを再生成する回数
def get(self):
self.set_status(501, reason="Not Implemented")
def post(self):
errors = []
# 未入力フィールドの確認
combined_token = ""
try:
combined_token = self.get_argument("token")
except tornado.web.MissingArgumentError as e:
errors.append(
dict(
field="token",
code="missing_argument",
message=e.log_message
)
)
if len(errors) != 0:
del combined_token
self.write(dict(
message="Argument error",
errors=errors
))
return
try:
token_id, raw_token_passwd = combined_token.split('-')
except ValueError as e:
del combined_token
msg = dict(
message="Toekn error",
errors=[
dict(
field="token",
code="invalid_token",
message="Invalid token format"
)]
)
self.write(msg)
return
del combined_token
# DBからトークン情報を照会、取得
session = sessionmaker(bind=self.engine)()
try:
result = session.query(Token.expire_time, Token.hashed_token_password).filter(
Token.token_id == token_id, Token.is_valid).one_or_none()
except sqlalchemy.exc.IntegrityError as e:
del raw_token_passwd, token_id
msg = dict(
message="Database error occured",
errors=[
dict(
field="token",
code="db_error",
message=str(e)
)
]
)
self.write(msg)
return
# トークンが存在しなかった場合
if result == None:
msg = dict(
message="%s is not exist" % token_id,
errors=[
dict(
field="token",
code="invalid_token",
message="invalid token id"
)
]
)
del raw_token_passwd, token_id
self.write(msg)
return
token_expire_time = result[0]
hashed_token_password = result[1]
print(token_expire_time)
# トークンの有効期限を確認
if token_expire_time < datetime.datetime.now():
del raw_token_passwd
msg = dict(
message="Token is expired",
errors=[
dict(
field="token",
code="expired_token",
message="This token was expired at %s" % token_expire_time
)
]
)
self.write(msg)
return
# 入力されたトークンパスワードの有効性を確認
if not check_password(raw_token_passwd, hashed_token_password):
del raw_token_passwd
msg = dict(
message="Token passward is not correct",
errors=[
dict(
field="token",
code="invalid_password",
message="password is not correct"
)
]
)
self.write(msg)
return
del raw_token_passwd
# リレーのパスワード部を生成
raw_relay_passwd = secrets.token_hex(nbytes=self.relay_passwd_nbytes)
hashed_relay_passwd = hash_password(raw_relay_passwd)
# トークンを生成
# 重複が生じる可能性を考慮し、複数回トークンの生成を試みる
db_relay = Relay()
is_registration_succeed = False
for _ in range(self.relay_registration_try_time):
relay_id = secrets.token_hex(nbytes=self.relay_passwd_nbytes)
db_relay.relay_id = relay_id
db_relay.hashed_relay_password = <PASSWORD>
db_relay.token_id = token_id
try:
session.add(instance=db_relay)
session.commit()
except sqlalchemy.exc.IntegrityError as e:
continue
except Exception as e:
errors.append(dict(
code="db_error",
message=str(e)
))
break
is_registration_succeed = True
break
if len(errors) != 0:
del relay_id, raw_relay_passwd
msg = dict(
message="Database error occurred",
errors=errors
)
self.write(msg)
return
# ユニークなトークンを生成できなかった場合のエラー(必ずしもそうとは限らない)
if not is_registration_succeed:
del relay_id, raw_relay_passwd
msg = dict(
message="Relay generator failed, please try again",
errors=[
dict(
code="relay_generator_error",
message="Could not generate unique relay id, please try again"
)
]
)
self.write(msg)
return
# ユーザが扱いやすいようにID部とパスワード部を結合し、送信
combined_relay = "%s-%s" % (relay_id, raw_relay_passwd)
msg = dict(
message="Success",
relay=combined_relay
)
self.write(msg)
del relay_id, raw_relay_passwd, combined_relay
session.close()
<file_sep># 標準ライブラリ
# 外部ライブラリ
import tornado.web
from tornado.options import define, options
# TODO: このクラスと、HTMLテンプレートは削除
# 今後このサーバでは、Webページの提供は行わない予定のため
class ControllerHandler(tornado.web.RequestHandler):
def get(self):
self.render('controller.html')
<file_sep># 標準ライブラリ
import json
from datetime import datetime, timedelta
# 外部ライブラリ
import tornado.websocket
from tornado.options import define, options
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import sqlalchemy.orm.exc
# 自作モジュール
from module.tables import Relay
from module.relay_pair import RelayPaire
from module.password_hash import hash_password, check_password
# TODO: コネクション切断時のエラーコードをきちんと考える
# 現状、すべて5000を返す
# XSSを防ぐために、送信する文字列のエスケープを行うようにする
class WsRelayHandler(tornado.websocket.WebSocketHandler):
relay_paires = dict()
engine = create_engine(
options.db_uri_type + options.db_path, echo=options.sql_echo)
def check_origin(self, origin):
"""
デバッグ用に同一生成元ポリシーを無くす
"""
return True
def open(self, relay):
relay_id, raw_relay_password = relay.split('-')
self.__relay_id = None
try:
is_valid_relay = self.__is_valid(relay_id, raw_relay_password)
except sqlalchemy.orm.exc.NoResultFound:
self.close(code=5000, reason="Database error occurred")
del raw_relay_password
return
del raw_relay_password
if not is_valid_relay:
self.close(code=5000, reason="Invalid relay")
return
if self.__is_expired(relay_id):
self.close(code=5000, reason="This relay is already expired")
return
self.__relay_id = relay_id
if not relay_id in self.relay_paires:
self.relay_paires[relay_id] = RelayPaire()
def on_message(self, message):
if self.__relay_id == None:
return
try:
msg = json.loads(message)
except json.JSONDecodeError:
self.close(code=5000, reason='Invalid format message')
return
if not 'header' in msg:
# TODO: ここにエラー処理を入れる
return
msg_header = msg['header']
response_contents = None
if 'contents' in msg:
# NOTE: 中継するべきデータ
response_contents = msg['contents']
if not 'cmd' in msg_header:
# TODO: ここにエラー処理を入れる
print('Invalid message header')
return
command = msg_header['cmd']
if command == 'connect':
self.relay_paires[self.__relay_id].connect_client(self)
return
if command == 'reconnect':
if self.relay_paires[self.__relay_id].is_autholized_connecton(self):
response = dict()
response["header"] = None
response["errors"] = [dict(
field="header.cmd",
code="duplicate_connection",
message="Already connected"
)]
self.write_message(response)
return
if not 'client_id' in msg_header:
self.close(code=5000, reason="Too few key")
return
self.relay_paires[self.__relay_id].reconnect_client(self, msg_header['client_id'])
return
#### 以下の処理は、認証済みのコネクションでないと実行できない ####
if not self.relay_paires[self.__relay_id].is_autholized_connecton(self):
self.close(code=5000, reason="This connection is not authorized, please authorize by using [connect] or [reconnect] command")
return
if command == 'relay':
response = dict(
header = dict(),
contents = response_contents
)
self.relay_paires[self.__relay_id].relay(self, response)
return
if command == 'close':
self.relay_paires[self.__relay_id].ws_con_close(self)
return
if command == 'exit':
self.relay_paires[self.__relay_id].exit(self)
return
if command == 'delete':
if not self.relay_paires[self.__relay_id].is_host_connection(self):
response = dict()
response["header"] = None
response["errors"] = [dict(
field="header.cmd",
code="permission_denied",
message="This operation is not permitted"
)]
self.write_message(response)
return
print(self.__relay_id)
del self.relay_paires[self.__relay_id]
try:
session = sessionmaker(bind=self.engine)()
relay = session.query(Relay).filter(Relay.relay_id == self.__relay_id).one()
relay.is_valid = False
session.commit()
session.close()
except sqlalchemy.orm.exc.NoResultFound:
self.close(code=5000, reason="Database error occurred")
print("Database error occurred")
return
print('deleted')
return
def on_close(self):
if self.__relay_id in self.relay_paires:
self.relay_paires[self.__relay_id].ws_con_close(self)
print('WebSocket closed')
def __is_valid(self, relay_id, raw_relay_password):
# DBからリレー情報を照会、取得
session = sessionmaker(bind=self.engine)()
result = session.query(Relay.hashed_relay_password, Relay.relay_id).filter(
Relay.relay_id == relay_id, Relay.is_valid).one_or_none()
# リレーが存在しなかった場合
if result == None:
del raw_relay_password
return False
hashed_relay_password = result[0]
relay_id = result[1]
# 入力されたリレーの有効性パスワードの有効性を確認
if not check_password(raw_relay_password, hashed_relay_password):
del raw_relay_password
return False
del raw_relay_password
return True
def __is_expired(self, relay_id):
# DBからリレー情報を照会、取得
session = sessionmaker(bind=self.engine)()
result = session.query(Relay.created_at).filter(
Relay.relay_id == relay_id, Relay.is_valid).one_or_none()
# リレーが存在しなかった場合
if result == None:
return False
created_at = result[0]
return not (created_at + timedelta(seconds=options.relays_lifespan_sec)) > datetime.now()
<file_sep>FROM python:3.7
# nginxのインストール
RUN wget https://nginx.org/keys/nginx_signing.key && \
apt-key add nginx_signing.key && \
rm nginx_signing.key && \
echo "deb http://nginx.org/packages/debian/ buster nginx" >> /etc/apt/sources.list && \
echo "deb-src http://nginx.org/packages/debian/ buster nginx" >> /etc/apt/sources.list && \
apt update && \
apt -y install nginx
WORKDIR /usr/src/app
# poetryのインストール
RUN curl -sSL https://raw.githubusercontent.com/sdispater/poetry/master/get-poetry.py | python
# Pythonパッケージのインストール
COPY pyproject.toml poetry.lock ./
RUN export PATH="$HOME/.poetry/bin:$PATH" && \
poetry export -f requirements.txt > requirements.txt && \
pip install --no-cache-dir -r requirements.txt
RUN echo "#!/usr/bin/env bash" >> /startup.sh && \
echo "service nginx start" >> /startup.sh && \
echo "python ./main.py" >> /startup.sh && \
chmod +x /startup.sh
CMD ["/startup.sh"]<file_sep>from datetime import datetime, timedelta
from tornado.options import define, options
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, Text, DateTime, Boolean
from sqlalchemy import ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class User(Base):
__tablename__ = "users"
user_id = Column(Integer, primary_key=True, autoincrement=True)
email = Column(Text, unique=True, nullable=False)
hashed_user_password = Column(Text, nullable=False)
created_at = Column(DateTime, default=datetime.now)
# NOTE: SQLAlchemyのリレーションについての解説
# https://poyo.hatenablog.jp/entry/2017/01/08/212227
token = relationship("Token")
class Token(Base):
__tablename__ = "tokens"
token_id = Column(Text, primary_key=True)
hashed_token_password = Column(Text, nullable=False)
user_id = Column(Integer, ForeignKey(
"users.user_id", onupdate="CASCADE", ondelete="CASCADE"), nullable=False)
expire_time = Column(DateTime, default=lambda: datetime.now(
) + timedelta(seconds=options.tokens_lifespan_sec))
is_valid = Column(Boolean, default=True)
created_at = Column(DateTime, default=datetime.now)
class Relay(Base):
__tablename__ = "relays"
relay_id = Column(Text, primary_key=True)
hashed_relay_password = Column(Text, nullable=False)
token_id = Column(Text, ForeignKey("tokens.token_id",
onupdate="CASCADE", ondelete="CASCADE"), nullable=False)
last_access = Column(DateTime, default=datetime.now)
is_valid = Column(Boolean, default=True)
created_at = Column(DateTime, default=datetime.now)
def create_tables():
"""
テーブルが作成されていない場合、新たにテーブルが作成される。
既にテーブルが存在する場合は、何も起きない
"""
engine = create_engine(options.db_uri_type +
options.db_path, echo=options.sql_echo)
Base.metadata.create_all(bind=engine)
| 8728c09445eda153060754e1c9a5a11946a40d45 | [
"TOML",
"Python",
"Dockerfile",
"Markdown"
] | 14 | TOML | Takahiro55555/WsCameraController | fdbf1e29ee61836f494160a29453bc66b5240a3c | 2b6339a4e681ec018391255974e33862be4e47cb |
refs/heads/main | <file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,i,j,k,len;
int m=0;
bool flag;
cin>>n;
for(i=0;i<n;i++)
{
cin>>len>>k;
cin>>word;
flag=false;
for(j=0;j<=len-k;j++)
{
str=word.substr(j,k);
ones=0;
zeroes=0;
q=0
for(m=0;m<str.length();m++)
{
if(str[m]=='1')
ones++;
else if(str[m]=='0')
zeroes++;
else if(str[m]=='?')
q++
}
if(ones==zeroes)
{
flag=true;
}
else if (abs(ones-zeroes)==q)
{
flag=true;
}
else
{
flag=false;
break;
}
}
if(flag==false)
{
cout<<"NO"<<endl;
}
else
{
cout<<"YES"<<endl;
}
}
return 0;
}
| 117a4664a099c96361bd41bbbd68af34772c051a | [
"C++"
] | 1 | C++ | Angana1/Coding- | 91e43964c04e09d87ff1564ed53f1aefc29370d6 | e9294413611ed91b8a664c1404f2aa3efd92e513 |
refs/heads/master | <repo_name>arinakt/sunnyDay<file_sep>/sunnyDay/View Controllers/ViewController.swift
//
// ViewController.swift
// sunnyDay
//
// Created by Арина on 28.05.2020.
// Copyright © 2020 Арина. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController {
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var tempLabel: UILabel!
@IBOutlet weak var detailLabel: UILabel!
@IBOutlet weak var maxLabel: UILabel!
@IBOutlet weak var minLabel: UILabel!
@IBOutlet weak var himidityLabel: UILabel!
@IBOutlet weak var speedLabel: UILabel!
@IBOutlet weak var pressureLabel: UILabel!
var networkWeatherManager = NetworkWeatherManager()
lazy var locationManager: CLLocationManager = {
let lm = CLLocationManager()
lm.delegate = self
lm.desiredAccuracy = kCLLocationAccuracyKilometer
lm.requestWhenInUseAuthorization()
return lm
}()
@IBAction func searchButton(_ sender: UIButton) {
self.presentSearchAlertController(withTitle: "Enter city name", message: nil, style: .alert) { [unowned self] city in
self.networkWeatherManager.fetchCurrentWeather(forRequestType: .cityName(city: city)) }
}
override func viewDidLoad() {
super.viewDidLoad()
networkWeatherManager.onCompletion = { [weak self] currentWeather in
guard let self = self else { return }
self.updateInterfaceWith(weather: currentWeather)
}
if CLLocationManager.locationServicesEnabled() {
locationManager.requestLocation()
}
}
func updateInterfaceWith(weather: CurrentWeather) {
DispatchQueue.main.async {
self.cityLabel.text = weather.cityName
self.tempLabel.text = "\(weather.temperatureString)º"
self.detailLabel.text = weather.main
self.maxLabel.text = "↑ \(weather.tempMaxString)º"
self.minLabel.text = "↓ \(weather.tempMinString)º"
self.himidityLabel.text = "\(weather.humidityString)%"
self.speedLabel.text = "\(weather.speedString)m/s"
self.pressureLabel.text = weather.pressureString
}
}
}
// MARK = CLLocationManager
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
networkWeatherManager.fetchCurrentWeather(forRequestType: .coordinate(latitude: latitude, longitude: longitude)
) }
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}
}
<file_sep>/sunnyDay/Models/CurrentWeatherData.swift
//
// CurrentWeatherData.swift
// sunnyDay
//
// Created by Арина on 28.05.2020.
// Copyright © 2020 Арина. All rights reserved.
//
import Foundation
struct CurrentWeatherData: Codable {
let name: String
let main: Main
let weather: [Weather]
let wind: Wind
}
struct Main: Codable {
let temp: Double
let pressure: Int
let humidity: Int
let tempMin: Double
let tempMax: Double
enum CodingKeys: String, CodingKey {
case temp
case pressure
case humidity
case tempMin = "temp_min"
case tempMax = "temp_max"
}
}
struct Wind: Codable {
let speed: Double
}
struct Weather: Codable {
let id: Int
let main: String
}
<file_sep>/sunnyDay/Models/CurrentWeather.swift
//
// CurrentWeather.swift
// sunnyDay
//
// Created by Арина on 28.05.2020.
// Copyright © 2020 Арина. All rights reserved.
//
import Foundation
struct CurrentWeather {
let cityName: String
let temperature: Double
var temperatureString: String {
return String(format: "%.0f", temperature)
}
let pressure: Int
var pressureString: String {
return "\(pressure)"
}
let humidity: Int
var humidityString: String {
return "\(humidity)"
}
let tempMin: Double
var tempMinString: String {
return String(format: "%.0f", tempMin)
}
let tempMax: Double
var tempMaxString: String {
return String(format: "%.0f", tempMax)
}
let speed: Double
var speedString: String {
return String(format: "%.0f", speed)
}
let main: String
/*let conditionCode: Int
var systemIconString: String {
switch conditionCode {
case 200...232: return "cloud.rain.fill"
case 300...321: return "cloud.drizzle"
case 500...531: return "cloud.rain"
case 600...622: return "cloud.snow"
case 701...781: return "smoke"
case 800: return "sun"
case 801...804: return "cloud"
default:
return "nosign"
}
}*/
init?(currentWeatherData: CurrentWeatherData) {
cityName = currentWeatherData.name
temperature = currentWeatherData.main.temp
pressure = currentWeatherData.main.pressure
humidity = currentWeatherData.main.humidity
tempMin = currentWeatherData.main.tempMin
tempMax = currentWeatherData.main.tempMax
speed = currentWeatherData.wind.speed
main = currentWeatherData.weather.first!.main
}
}
<file_sep>/sunnyDay/Supporting files/Constants.swift
//
// Constants.swift
// sunnyDay
//
// Created by Арина on 28.05.2020.
// Copyright © 2020 Арина. All rights reserved.
//
import Foundation
let apiKey = "<KEY>"
| 6e6b61573fb56081bb9c8fea7da367ebe9085a4e | [
"Swift"
] | 4 | Swift | arinakt/sunnyDay | e8b3aec53ea38c4429de6212a80008038421b4da | 97cdb9c3d057c18d2f719531f1e1c24de123a7fa |
refs/heads/main | <file_sep>const baseUrl = 'https://60f18ece38ecdf0017b0fd03.mockapi.io/api/v1/events';
export const getFetchData = () =>
fetch(baseUrl).then(response => {
if (response.ok) {
return response.json();
}
return null;
});
export const postFetchData = event =>
fetch(baseUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(event),
}).then(response => {
if (!response.ok) {
throw new Error();
}
});
export const deleteFetchData = taskId =>
fetch(`${baseUrl}/${taskId}`, {
method: 'DELETE',
}).then(response => {
if (!response.ok) {
throw new Error();
}
});
<file_sep>const events = [
{
id: 1,
title: "Go to the gym",
description: "some text here",
dateFrom: new Date(2021, 6, 14, 10, 15),
dateTo: new Date(2021, 6, 14, 15, 0),
},
{
id: 2,
title: "Go to the school",
description: "hello, 2 am",
dateFrom: new Date(2021, 6, 15, 11, 0),
dateTo: new Date(2021, 6, 15, 12, 0),
},
{
id: 3,
title: "Lunch",
description: "",
dateFrom: new Date(2020, 8, 17, 10, 30),
dateTo: new Date(2020, 8, 17, 11, 30),
},
{
id: 4,
title: "Meet friend",
description: "at the cafe",
dateFrom: new Date(2020, 8, 25, 10, 30),
dateTo: new Date(2020, 8, 25, 11, 0),
},
];
export default events;<file_sep>import React from 'react';
import PropTypes from 'prop-types';
const EventDelete = ({ isShowDelete, deleteEvent }) =>
isShowDelete && (
<button className="delete-event-btn" onClick={deleteEvent}>
<i className="fas fa-trash"></i>
Delete
</button>
);
EventDelete.propTypes = {
isShowDelete: PropTypes.bool.isRequired,
deleteEvent: PropTypes.func.isRequired,
};
export default EventDelete;
<file_sep>import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import Navigation from '../navigation/Navigation.jsx';
import Week from '../week/Week.jsx';
import Sidebar from '../sidebar/Sidebar.jsx';
import Modal from '../modal/Modal.jsx';
import { deleteFetchData, getFetchData, postFetchData } from '../../gateway/gateway.js';
import './calendar.scss';
const Calendar = ({ weekDates, isOpenModal, onCloseModal }) => {
const [eventsData, setEventsData] = useState([]);
const upgradeDate = data =>
data.map(event => ({
...event,
dateFrom: new Date(event.dateFrom),
dateTo: new Date(event.dateTo),
}));
const fetchData = () => {
getFetchData()
.then(events => {
setEventsData(upgradeDate(events));
})
.catch(() => alert("Internal Server Error. Can't display events"));
};
useEffect(() => {
fetchData();
}, []);
const saveEvent = event => {
postFetchData(event).then(() => fetchData());
};
const removeEvent = eventId => {
deleteFetchData(eventId).then(() => fetchData());
};
return (
<section className="calendar">
<Navigation weekDates={weekDates} />
<div className="calendar__body">
<div className="calendar__week-container">
<Sidebar />
<Week weekDates={weekDates} events={eventsData} removeEvent={removeEvent} />
</div>
</div>
<Modal isOpenModal={isOpenModal} onCloseModal={onCloseModal} saveEvent={saveEvent} />
</section>
);
};
Calendar.propTypes = {
isOpenModal: PropTypes.bool.isRequired,
onCloseModal: PropTypes.func.isRequired,
weekDates: PropTypes.array.isRequired,
};
export default Calendar;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Hour from '../hour/Hour.jsx';
const Day = ({ dataDay, dayEvents, removeEvent, isCurrentTime }) => {
const hours = Array(24)
.fill()
.map((val, index) => index);
return (
<div className="calendar__day" data-day={dataDay}>
{hours.map(hour => {
const hourEvents = dayEvents.filter(event => event.dateFrom.getHours() === hour);
const currentTimeSlot = isCurrentTime ? new Date().getHours() === hour : false;
return (
<Hour
key={dataDay + hour}
dataHour={hour}
hourEvents={hourEvents}
removeEvent={removeEvent}
currentTimeSlot={currentTimeSlot}
/>
);
})}
</div>
);
};
Day.propTypes = {
dataDay: PropTypes.number.isRequired,
dayEvents: PropTypes.array.isRequired,
removeEvent: PropTypes.func.isRequired,
isCurrentTime: PropTypes.bool.isRequired,
};
export default Day;
<file_sep>import React, { useState } from 'react';
import PropTypes from 'prop-types';
import EventDelete from './EventDelete.jsx';
import './event.scss';
const Event = ({ height, marginTop, title, time, id, removeEvent }) => {
const [isShowDelete, setIsShowDelete] = useState(false);
const eventStyle = {
height,
marginTop,
};
const showDelete = () => {
setIsShowDelete(!isShowDelete);
};
const deleteEvent = () => {
setIsShowDelete(false);
removeEvent(id);
};
return (
<>
<div style={eventStyle} className="event" onClick={showDelete}>
<div className="event__title">{title}</div>
<div className="event__time">{time}</div>
</div>
<EventDelete isShowDelete={isShowDelete} deleteEvent={deleteEvent} />
</>
);
};
Event.propTypes = {
height: PropTypes.number.isRequired,
marginTop: PropTypes.number.isRequired,
removeEvent: PropTypes.func.isRequired,
id: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
time: PropTypes.string.isRequired,
};
export default Event;
<file_sep>import React, { useState, useEffect } from 'react';
import './time.scss';
const Time = () => {
const [topStyles, setTopStyles] = useState(new Date().getMinutes());
const style = {
top: topStyles,
};
useEffect(() => {
const intervalId = setInterval(() => {
setTopStyles(new Date().getMinutes());
}, 1000);
return () => {
clearInterval(intervalId);
};
}, [topStyles]);
return (
<div style={style} className="red-block">
<div className="red-block__line"></div>
<div className="red-block__circle"></div>
</div>
);
};
export default Time;
| 5a01059289e0d4b5a359d93d9b686bcae1b5a69a | [
"JavaScript"
] | 7 | JavaScript | JuliyaSavelyeva/calendar-react | 67d60b0d3c3c222f3e5d7c5e6abe78dea92ebb66 | 1b0b8fd3c161bf6c89154d3b88c78b59c0edff27 |
refs/heads/main | <file_sep>package com.tom.jspServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @descriptions: test
* @author: Tom
* @date: 2021/1/13 上午 12:10
* @version: 1.0
*/
public class MyServelet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
req.getRequestDispatcher("/hello.jsp").forward(req,resp);
}
}
<file_sep>"# SSHStudy"
| b1171129e0c4176d9b0744b649e20cb68fcde429 | [
"Markdown",
"Java"
] | 2 | Java | loustrong/SSHStudy | d9454793c8e8c5d060a77fc29b7ea597653b46e1 | 57ed807b6d182fef8765277a2c136918e16d3fc0 |
refs/heads/master | <file_sep># mCloudStorage
Cloud storage using the Mega.nz API
You can upload, download and share files with the program.
<file_sep>/*
*/
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using MetroFramework.Forms;
using CG.Web.MegaApiClient;
using System.Linq;
using System.Threading.Tasks;
namespace mCloudStorage
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class CloudDrive : MetroForm
{
public static MegaApiClient mclient = new MegaApiClient();
INode mcNode;
Dictionary<string,INode> nodeDict = new Dictionary<string, INode>();
public static bool loggedIn = false;
public CloudDrive()
{
Form.CheckForIllegalCrossThreadCalls = false;
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//this.Opacity = 0;
WaitForLogin();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
async void WaitForLogin()
{
while (!loggedIn)
{
System.Threading.Thread.Sleep(100);
}
//await Task.Run(()=>new LoginForm().ShowDialog());
}
async void CloudDriveLoad(object sender, EventArgs e)
{
//this.Opacity = 1.0;
this.Show();
this.WindowState = FormWindowState.Minimized;
this.WindowState = FormWindowState.Normal;
label1.Text = "Loading Nodes...";
await Task.Run(()=>LoadData());
label1.Text = "Ready.";
}
void LoadData()
{
try
{
label1.Text = "Fetching Nodes...";
var nodes = mclient.GetNodes().ToList();
INode root = nodes.Single(n => n.Type == NodeType.Root);
bool hasmCloudFolder = false;
label1.Text = "Scanning Nodes...";
foreach (var node in nodes)
{
if (node.Name=="mCloud")
hasmCloudFolder = true;
}
if (!hasmCloudFolder)
{
label1.Text = "Adding Nodes...";
mclient.CreateFolder("mCloud",root);
nodes = mclient.GetNodes().ToList();
}
label1.Text = "Processing Nodes...";
mcNode = nodes.Single(n => n.Name=="mCloud");
List<INode> fileNodes = new List<INode>();
foreach (var node in nodes)
{
if (node.ParentId==mcNode.Id)
{
fileNodes.Add(node);
}
}
foreach (var node in fileNodes)
{
string fileName = node.Name;
if (!nodeDict.ContainsKey(fileName))
nodeDict.Add(fileName,node);
}
RefreshView();
}
catch (Exception ex)
{
MessageBox.Show("A fatal error occurred loading the Cloud Drive. mCloudStorage will now exit.");
this.Close();
}
}
void RefreshView()
{
listView1.Items.Clear();
foreach (string filename in nodeDict.Keys)
{
listView1.Items.Add(filename);
}
}
void RefreshNodes()
{
try
{
nodeDict = new Dictionary<string, INode>();
var nodes = mclient.GetNodes().ToList();
label1.Text = "Refreshing Nodes...";
mcNode = nodes.Single(n => n.Name=="mCloud");
foreach (var node in nodes)
{
if (node.ParentId==mcNode.Id)
{
if (!nodeDict.ContainsKey(node.Name))
nodeDict.Add(node.Name,node);
}
}
RefreshView();
label1.Text = "Ready.";
}
catch (Exception ex)
{
MessageBox.Show("An error occurred refreshing nodes.");
label1.Text = "Node Refresh Error.";
}
}
bool forceClose = false;
void Button1Click(object sender, EventArgs e)
{
try
{
mclient.Logout();
Properties.Settings.Default.email="";
Properties.Settings.Default.password="";
Properties.Settings.Default.Save();
this.Close();
forceClose = true;
}
catch (Exception ex)
{
MessageBox.Show("An error occurred while logging out.");
}
}
async void Button2Click(object sender, EventArgs e)
{
try
{
label1.Text = "Uploading...";
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
foreach (string fileName in ofd.FileNames)
{
await Task.Run(()=>mclient.Upload(fileName, mcNode));
}
}
label1.Text = "Uploaded Successfully.";
RefreshNodes();
}
catch (Exception ex)
{
label1.Text = "Upload Error.";
MessageBox.Show("An error occurred uploading the file.");
}
}
async void Button3Click(object sender, EventArgs e)
{
ListViewItem lvitem = null;
try
{
lvitem = listView1.Items[listView1.SelectedIndices[0]];
}
catch
{
return;
}
if (lvitem==null)
return;
try
{
label1.Text = "Downloading...";
SaveFileDialog sfd = new SaveFileDialog();
DialogResult dr = sfd.ShowDialog();
if (dr == DialogResult.OK)
{
string fp = sfd.FileName;
await Task.Run(()=> mclient.DownloadFile(nodeDict[lvitem.Text],fp));
}
label1.Text = "Downloaded Successfully.";
}
catch (Exception ex)
{
label1.Text = "Download Error.";
MessageBox.Show("An error occurred downloading the file.");
}
}
private async void button4_Click(object sender, EventArgs e)
{
await Task.Run(()=> RefreshNodes());
}
private async void button5_Click(object sender, EventArgs e)
{
ListViewItem lvitem = null;
try
{
lvitem = listView1.Items[listView1.SelectedIndices[0]];
}
catch
{
return;
}
if (lvitem == null)
return;
try
{
label1.Text = "Deleting...";
DialogResult dr = MessageBox.Show("Are you sure you want to delete this item?","Warning",MessageBoxButtons.OKCancel);
DialogResult tr = MessageBox.Show("Do you want to move this item to the trash?","Alert",MessageBoxButtons.YesNoCancel);
if (dr == DialogResult.OK && tr != DialogResult.Cancel)
{
await Task.Run(() => { mclient.Delete(nodeDict[lvitem.Text], tr == DialogResult.Yes); RefreshNodes(); });
}
label1.Text = "Deleted Successfully.";
}
catch
{
label1.Text = "Delete Error.";
MessageBox.Show("An error occurred deleting the file.");
}
}
private void CloudDrive_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = !forceClose;
this.Hide();
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Minimized;
this.WindowState = FormWindowState.Normal;
}
void CloudDriveShown(object sender, EventArgs e)
{
//this.Hide();
}
}
}
<file_sep>/*
*/
using System;
using System.Drawing;
using System.Windows.Forms;
using MetroFramework.Forms;
using CG.Web.MegaApiClient;
using System.Threading;
using System.Threading.Tasks;
namespace mCloudStorage
{
/// <summary>
/// Description of LoginForm.
/// </summary>
public partial class LoginForm : MetroForm
{
public LoginForm()
{
Form.CheckForIllegalCrossThreadCalls = false;
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
async void AttemptLogin(object sender, EventArgs e)
{
bool canExit = false;
bool runCDrive = false;
label3.Text = "Logging in...";
button1.Enabled = false;
await Task.Run(()=>{
string un = textBox1.Text;
string pw = textBox2.Text;
try
{
CloudDrive.mclient.Login(un,pw);
Properties.Settings.Default.email = un;
Properties.Settings.Default.password = pw;
Properties.Settings.Default.Save();
label3.Text = "Login success.";
CloudDrive.loggedIn = true;
this.Close();
}
catch (ApiException apie)
{
MessageBox.Show("Server rejected the credentials.");
label3.Text = "Login failure.";
}
button1.Enabled = true;
});
}
async void AttemptRegister(object sender, EventArgs e)
{
/*
bool canExit = false;
label3.Text = "Registering...";
button1.Enabled = false;
await Task.Run(()=>{
string un = textBox1.Text;
string pw = textBox2.Text;
try
{
msvc.Register(un, pw, ()=>{
//Success
Properties.Settings.Default.email = un;
Properties.Settings.Default.password = pw;
Properties.Settings.Default.Save();
label3.Text = "Register success.";
MessageBox.Show("Your account has been registered! Please log in now.");
}, e=>{
});
this.Hide();
new CloudDrive().ShowDialog();
canExit = true;
}
catch (ApiException apie)
{
MessageBox.Show("Server rejected the credentials.");
label3.Text = "Login failure.";
}
button1.Enabled = true;
});
if (canExit)
{
this.Close();
}
*/
}
void LoginFormLoad(object sender, EventArgs e)
{
bool emptyPass = string.IsNullOrWhiteSpace(Properties.Settings.Default.password);
bool emptyUn = string.IsNullOrWhiteSpace(Properties.Settings.Default.email);
if (!emptyPass&&!emptyUn)
{
this.Opacity = 0;
textBox1.Text = Properties.Settings.Default.email;
textBox2.Text = Properties.Settings.Default.password;
AttemptLogin(null,null);
}
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("https://mega.nz/#register");
}
private void LoginForm_Shown(object sender, EventArgs e)
{
if (this.Opacity == 0)
this.Hide();
}
void LoginFormFormClosing(object sender, FormClosingEventArgs e)
{
/*
if (!CloudDrive.loggedIn)
Application.Exit();
*/
}
}
}
| c8204b269e9e59ab2a1e4d7ea6f521ca6bb03ce2 | [
"Markdown",
"C#"
] | 3 | Markdown | todokku/mCloudStorage | 9a46456069e879464296ad0d0c87b740c072d80a | 1bbf776b00907c2cade65eb4f32501575298e584 |
refs/heads/master | <repo_name>MuflikhunovRR/ISBNProject<file_sep>/src/main/java/ru/gotoqa/Constants/Constants.java
package ru.gotoqa.Constants;
/**
* @author <NAME>
*/
public class Constants {
public static final String URLSITE = "https://shop.harvard.com/search/site/java";
public static final String FILEPATH = "D:\\JAVA\\Java_SRC\\ISBNProject\\src\\main\\resources\\report.txt";
public static final String FILEPATHHTML = "D:\\JAVA\\Java_SRC\\ISBNProject\\src\\main\\resources\\harvard.html";
public static final String MONEYCODE = "$";
public static final String STATUSMESSAGE = "OK";
public static final String ADDTOCART = "Add to Cart";
public static final String ADDTOWISHLIST = "Add to Wish List";
public static final int COUNTELEMENT = 10;
public static final int STATUSCODE200 = 200;
//userAgent
public static final String USERAGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7";
private Constants() {
//this prevents even the native class from
//calling this ctor as well :
throw new AssertionError();
}
}<file_sep>/src/main/resources/db.sql
-- Create TABLE
CREATE TABLE ISBN_CATALOG (
id INT(11) NOT NULL AUTO_INCREMENT,
StatusCode VARCHAR(30) NOT NULL,
StatusMessage VARCHAR(150) NOT NULL,
ISBN VARCHAR(18) NOT NULL,
BookName VARCHAR(150) NOT NULL,
BookPrice VARCHAR(30) NOT NULL,
BookAuthor VARCHAR(150) NOT NULL,
Availability VARCHAR(150) NOT NULL,
Published VARCHAR(150) NOT NULL,
PRIMARY KEY (id)
);
DROP TABLE ISBN_CATALOG;
SELECT * FROM ISBN_CATALOG;
-- Insert data
INSERT INTO WorldAirports VALUES
(1, 'LAX', 'LOS ANGELES INTL', 'United States', 'US', 91, 8, 12091, 126, 33, 56, 0, 'N', 118, 24, 0, 'W'),
(2, 'FCO', 'ROME DA VINCI', 'Italy', 'IT', 450, -1, 12795, 14, 41, 47,59, 'N', 12, 14, 3, 'E'),
(3, 'SFO', 'SAN FRANCISCO INTL', 'United States', 'US', 91, 8, 11870, 12, 37, 37, 0, 'N', 122, 23, 0, 'W');
DROP TABLE autocode_test2;
//for Oracle
CREATE TABLE autocode_test2;
( id NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1),
Title varchar2(150) NOT NULL,
Author varchar2(150) NOT NULL,
Price varchar2(150) NOT NULL,
ISBN varchar2(150) NOT NULL,
AvailabilityData varchar2(150) NOT NULL,
Published varchar2(150) NOT NULL
);
//for MsSql
CREATE TABLE ISBN_CATALOG (
id INT(11) NOT NULL AUTO_INCREMENT,
Title VARCHAR(150) NOT NULL,
Author VARCHAR(150) NOT NULL,
Price VARCHAR(150) NOT NULL,
ISBN VARCHAR(150) NOT NULL,
AvailabilityData VARCHAR(150) NOT NULL,
Published VARCHAR(150) NOT NULL,
ISBN_Check BOOLEAN NOT NULL,
PRIMARY KEY (id)
);
SELECT * FROM autocode_test2 order by id;
DELETE FROM autocode_test2;
INSERT INTO autocode_test2 (Title, Author, Price, ISBN, AvailabilityData, Published) VALUES ();
commit;
<file_sep>/src/main/java/ru/gotoqa/ParsingHtmlBook.java
package ru.gotoqa;
import org.junit.jupiter.api.Test;
import ru.gotoqa.models.ISBNService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
/**
* @author <NAME>
*/
public class ParsingHtmlBook {
@Test
void test1() throws IOException {
String url = "https://shop.harvard.com/search/site/java";
Document document = null;
if (!Jsoup.connect(url).get().equals(null)){
document = Jsoup.connect(url).get();
}
/* //Parsing all info from page
String bookPage = document.select("div.abaproduct-details").text();
System.out.println("ISBN: " + bookPage);*/
//String bookIsbn = document.select("li.search-result:nth-child(1) > div:nth-child(3) > span:nth-child(4)").text();
//get ISBN num first book
String firstBookIsbn = document.select("#block-system-main > div > ol > li:nth-child(1) > div.abaproduct-details > span:nth-child(4)").text().replace("ISBN-13: ", "");
System.out.println(firstBookIsbn);
//Soap request
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"application-config.xml"});
ISBNService bean = context.getBean(ISBNService.class);
boolean validISBN13 = bean.getISBNServiceSoap().isValidISBN13(firstBookIsbn);
System.out.println("Проверка книги показала: " +validISBN13);
}
}
<file_sep>/src/main/java/ru/gotoqa/ParsingHtmlSoupRqSetUserAgent.java
package ru.gotoqa;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import ru.gotoqa.models.ISBNService;
import javax.sql.DataSource;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import static ru.gotoqa.Constants.Constants.*;
/**
* @author <NAME>
*/
public class ParsingHtmlSoupRqSetUserAgent {
private static final Logger LOGGER = LoggerFactory.getLogger(ParsingHtmlSoupRqSetUserAgent.class);
public static Document doc;
public static Connection.Response response;
public static ISBNService bean;
private static ClassPathXmlApplicationContext contextdb = new ClassPathXmlApplicationContext("db.xml");
NamedParameterJdbcTemplate nqu = new NamedParameterJdbcTemplate(contextdb.getBean(DataSource.class));
@BeforeAll
public static void AccessSetup() throws IOException {
//Set User Agent + get connect to page
doc = Jsoup.connect(URLSITE)
.userAgent(USERAGENT)
.timeout(5000)
.cookie("cookiename", "roman")
.cookie("anothercookie", "gotoqa")
.referrer("http://google.com")
.header("headersecurity", "xyz123")
.get();
//get response
response = Jsoup.connect(URLSITE).followRedirects(false).execute();
//Soap request
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"application-config.xml"});
bean = context.getBean(ISBNService.class);
}
@Test
@DisplayName("Test ID = 1. Check the Status Code.")
public void statusCodeTest() {
int sc = response.statusCode();
Assertions.assertEquals(STATUSCODE200, sc);
LOGGER.trace("Status Code: {}", sc);
}
@Test
@DisplayName("Test ID = 2. Check the Status Message.")
public void statusMessageTest() {
String sm = response.statusMessage();
Assertions.assertEquals(STATUSMESSAGE, sm);
LOGGER.trace("Status Message: {}", sm);
}
@Test
@DisplayName("Test ID = 3. Check the ISBN use webservice & create report TXT file.")
public void checkIsbnWebServiceTest() {
Elements links = doc.select("div.abaproduct-details > span:matches(\\d{13})");
Assertions.assertEquals(COUNTELEMENT, links.size());
try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILEPATH))){
for (Element link : links) {
String replace = link.text().replace("ISBN-13: ", "");
boolean validISBN13 = bean.getISBNServiceSoap().isValidISBN13(replace);
Assertions.assertTrue(validISBN13);
LOGGER.trace("Checking book ISBN = " + replace + ". Web service return: " + validISBN13);
bw.write("Checking book ISBN = " + replace + ". Web service return: " + validISBN13);
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
@DisplayName("Test ID = 4. Check the Title Page.")
public void checkTitlePageTest() {
String title = doc.title();
Assertions.assertEquals("Search | Harvard Book Store", title);
LOGGER.trace("Title: {}", title);
}
@Test
@DisplayName("Test ID = 5. Check the Book name.")
public void checkBookNameTest() {
Elements bookName = doc.select("#block-system-main > div > ol > li > h3");
Assertions.assertEquals(COUNTELEMENT, bookName.size());
for (Element link2 : bookName) {
String replace2 = link2.text();
LOGGER.trace("Book name: {}", replace2);
Assertions.assertNotNull(replace2, "No book title.");
Assertions.assertTrue(replace2.contains("Java"));
//Assertions.assertTrue(replace2.contains("Paperback"));
}
}
@Test
@DisplayName("Test ID = 6. Check the Book price.")
public void checkBookPriceTest() {
Elements bookPrice = doc.select("div.abaproduct-details > h3");
Assertions.assertEquals(COUNTELEMENT, bookPrice.size());
for (Element link3 : bookPrice) {
String replace3 = link3.text();
LOGGER.trace("Book price: {}", replace3);
Assertions.assertNotNull(replace3);
Assertions.assertTrue(replace3.contains(MONEYCODE));
}
}
@Test
@DisplayName("Test ID = 7. Check the Book Author.")
public void ckeckBookAuthorTest() {
//get the bookAuthor. all authors css (div.abaproduct-details > p > a)
Elements bookAuthor = doc.select("div.abaproduct-details > p");
Assertions.assertEquals(COUNTELEMENT, bookAuthor.size());
for (Element link4 : bookAuthor) {
String replace4 = link4.text();
LOGGER.trace("Book Author: {}", replace4);
Assertions.assertNotNull(replace4);
}
}
@Test
@DisplayName("Test ID = 8. Check the Enter Terms.")
public void checkEnterTermsTest() {
Elements enterTermsInput = doc.select("#edit-keys");
Assertions.assertNotNull(enterTermsInput, "Element enterTermsInput is empty");
LOGGER.trace("Enter Terms: {}", enterTermsInput);
}
@Test
@DisplayName("Test ID = 9. Check the Sort Results element.")
public void checkSortResultElementTest() {
Elements sortResults = doc.select("#edit-fsort");
Assertions.assertNotNull(sortResults, "Element Sort Results is empty");
}
@Test
@DisplayName("Test ID = 10. Check the Search Results element.")
public void checkSearchResultElementTest() {
Elements searchResults = doc.select("#block-system-main > div > h2");
Assertions.assertNotNull(searchResults, "Element Search Results is empty");
}
@Test
@DisplayName("Test ID = 11. Check the Add Cart button.")
public void checktAddCartButtonTest() {
Elements addCart = doc.select("[id^=edit-add-to-cart]");
Assertions.assertNotNull(addCart, "Nu such Element: Add to Cart");
Assertions.assertEquals(COUNTELEMENT, addCart.size());
for (Element link5 : addCart) {
String replace5 = link5.text();
System.out.println(replace5);
Assertions.assertNotNull(replace5);
Assertions.assertEquals(ADDTOCART, replace5);
}
}
@Test
@DisplayName("Test ID = 12. Check the Wish List button.")
public void checktWishListButtonTest() {
Elements addWishList = doc.select("[id^=edit-add-to-w]");
Assertions.assertNotNull(addWishList, "Nu such Element: Add to Wish List");
Assertions.assertEquals(COUNTELEMENT, addWishList.size());
for (Element link : addWishList) {
String replace = link.text();
System.out.println(replace);
Assertions.assertNotNull(replace);
Assertions.assertEquals(ADDTOWISHLIST, replace);
}
}
@Test
@DisplayName("Test ID = 13. Check the Availability element.")
public void checktAvailabilityElementTest() {
Elements availability = doc.select("div.abaproduct-details > span:nth-child(6)");
Assertions.assertNotNull(availability, "Nu such Element: Availability");
Assertions.assertEquals(COUNTELEMENT, availability.size());
for (Element link : availability) {
String replace = link.text();
System.out.println(replace);
Assertions.assertNotNull(replace);
Assertions.assertTrue(replace.contains("Availability"));
}
}
@Test
@DisplayName("Test ID = 14. Check the Published element.")
public void checktPublishedTest() {
Elements published = doc.select("div.abaproduct-details > span:nth-child(8)");
Assertions.assertNotNull(published, "Nu such Element: Published");
Assertions.assertEquals(COUNTELEMENT, published.size());
for (Element link : published) {
String replace = link.text();
System.out.println(replace);
Assertions.assertNotNull(replace);
Assertions.assertTrue(replace.contains("Published"));
}
}
@Test
@DisplayName("Test ID = 15. Check the img element.")
public void checkImgElementTest() {
Elements published = doc.select("div.abaproduct-image > a > img");
Assertions.assertNotNull(published, "Nu such Element: img");
Assertions.assertEquals(COUNTELEMENT, published.size());
for (Element link : published) {
System.out.println(link);
Assertions.assertNotNull(link);
}
}
@Test
@DisplayName("Test ID = 16. Check the all element.")
public void checkAllElementTest() {
Elements published = doc.select("#block-system-main > div > ol > li");
Assertions.assertNotNull(published, "Nu such Element");
Assertions.assertEquals(COUNTELEMENT, published.size());
for (Element link : published) {
String replace = link.text();
System.out.println(replace);
Assertions.assertNotNull(replace);
}
}
}<file_sep>/src/main/java/ru/gotoqa/TempParsing.java
package ru.gotoqa;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
/**
* @author <NAME>
*/
public class TempParsing {
@Test
void test1() throws IOException {
Document doc = Jsoup.connect("https://shop.harvard.com/search/site/java")
.userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7")
.timeout(5000)
.cookie("cookiename", "val234")
.cookie("anothercookie", "ilovejsoup")
.referrer("http://google.com")
.header("headersecurity", "xyz123")
.get();
/* // get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}*/
//ISBN
Elements links = doc.select("div.abaproduct-details > span:matches(\\d{13})");
for (Element link : links) {
// get the value
String replace = link.text().replace("ISBN-13: ", "");
System.out.println(replace);
}
ArrayList<String> elements = new ArrayList<String>();
for (int i = 0; i < links.size(); i++) {
elements.add(links.get(i).html());
}
System.out.println(elements);
//div.abaproduct-image > a > img
//
/*
//All data loop
Elements bookPage = document.select("div.abaproduct-details");
for (Element element : bookPage) {
System.out.println(element.text());
}*/
}
} | 89fa6883284f0e8601ad53c7efb3d62363678ba2 | [
"Java",
"SQL"
] | 5 | Java | MuflikhunovRR/ISBNProject | 3a502bfc95798ed87f76848fdc4d4ac6f2d45b7e | 0bf196cda34e7dd6c620b237cfdb564d82153146 |
refs/heads/master | <file_sep>package br.com.stand.artilharia.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Ambiente implements Modelo, Serializable {
private static final long serialVersionUID = -3231050480459880668L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@NotEmpty(message = "Precisa preencher a descrição")
private String descricao;
@NotNull(message = "Precisa preencher a área")
private Integer area;
@NotNull(message = "Precisa preencher alvo")
private Boolean alvo;
public String getResumo() {
return descricao + " - área: " + area + " - alvo: " + (alvo ? "SIM" : "NÃO");
}
}<file_sep>export class Reserva {
}
<file_sep>
# DKL-System
Projeto Final Desenvolvimento Web IV - Profª MarcielI- Entrega 1 - Proposta Inicial
GRUPO: <NAME>, <NAME> e <NAME>
Requisitos mínimos do projeto:
Desenvolver pelo menos 2 Cruds básicos e um Caso de Uso complexo.
Exemplo de Crud Básico: Cadastro de Cliente
Exemplo de Caso de uso complexo: Empréstimo/Devolução de livros.
Artefatos de engenharia:
Diagrama de classes de entidades
Lista de requisitos macro (tarefas do usuário)
Protótipos de tela (linkados com os requisitos macro)
Apresentação da proposta:
Deverão ser apresentados os artefatos de engenharia (armazenados no Github).
Colocar o link do repositório do projeto no github na issue.
Os artefatos deverão ser apresentados pelos membros da equipe para o professor e demais colegas.
Haverá espaço para perguntas e respostas.
NÃO é necessária a preparação de slides, a apresentação se dará diretamente dos artefatos no github.
As apresentações iniciarão as 19:15 por sorteio, a equipe sorteada que não tiver algum de seus membros presentes decidirá por apresentar sem o membro ausente ou por não apresentar, perdendo em conceito.
NOME DO PROJETO = DKL-System Fire
Uma solução simples para entidades de Tiro prático, Tiro Esportivo e Paintball, constituindo uma plataforma que oferece produtos e serviços que ajudam sua entidade a otimizar processos para aumentar sua produtividade, sem complicaçōes:
Controle de Cadastro de clientes
O sistema permite um controle completo do cadastro dos filiados por meio de filtros que permitem um busca direcionada dos dados cadastrais.
Controle de Cadastro de Armas .Controle completo do cadastro das armas oferecida com busca pro filtros
Controle de Cadastro de Ambiente (pistas ou stands de tiro). Controle completo do cadastro das áreas de prática desportiva oferecida.
Controle do agendamento das locações dos Ambientes, das armas e equipamentos com relatorios e consultas rápidas.
LINK DA PAGINA GIT-HUB PAGES:
https://lvkill.github.io/DKL-System/
Data de entrega sexta, 6 set 2019, 23:59
<file_sep>TRUNCATE arma
CASCADE;
TRUNCATE ambiente CASCADE;
TRUNCATE arma_locada CASCADE;
TRUNCATE cliente CASCADE;
TRUNCATE credenciais CASCADE;
TRUNCATE reserva CASCADE;
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ReservaService {
constructor(
private http: HttpClient
) { }
/**
* salva reserva
*/
public salvaReserva(id = null, clienteSelecionado, ambienteSelecionado, inicioDaLocacao, fimDaLocacao, armasLocadas, ativo = "true") {
/**
* {
* "cliente":{"id":"128"},
* "ambiente":{"id":"1002"},
* "inicioDaLocacao":"2019-12-12T12:12",
* "fimDaLocacao":"2019-12-12T12:13",
* "ativa":true,
* "armaLocadas":[
* {"arma":{"id":1003},"quantidade":1}
* ]
* }
*
* {
* "cliente": {"id":"1001"},
* "ambiente":{"id":"1002"},
* "inicioDaLocacao":"1212-12-12T12:12",
* "fimDaLocacao":"1212-12-12T12:12",
* "ativa":true,
* "armasLocadas": [
* {"id":1001,"quantidade":1}
* ]}
*/
let obj = {
"cliente": {"id" : clienteSelecionado},
"ambiente": {"id" : ambienteSelecionado},
"inicioDaLocacao" : inicioDaLocacao,
"fimDaLocacao" : fimDaLocacao,
"ativa" : true,
"armaLocadas" : []
}
for (let i = 0; i< armasLocadas.length; i++){
obj.armaLocadas.push({"arma" : armasLocadas[i]});
}
console.log(obj);
if(id === null){
return this.http.post<any>('http://127.0.0.1:9090/api/reservas', obj , {});
}else {
return this.http.put<any>('http://127.0.0.1:9090/api/reservas/' + id, obj, {});
}
}
/**
* listar reservas
*/
public listarReserva() {
return this.http.get<any>('http://127.0.0.1:9090/api/reservas?busca=&pagina=0&tamanho=20');
};
/**
* pega reserva pelo id
* http://127.0.0.1:9090/api/reservas/109
*/
public listaReservaPorId(id){
return this.http.get<any>('http://127.0.0.1:9090/api/reservas/' + id);
}
}
<file_sep>package br.com.stand.artilharia.configuration;
import br.com.stand.artilharia.security.JWTAuthenticationFilter;
import br.com.stand.artilharia.security.JWTLoginFilter;
import br.com.stand.artilharia.service.CustomUserDetailsService;
import lombok.AllArgsConstructor;
import java.util.Arrays;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private CustomUserDetailsService service;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().and().csrf().disable().authorizeRequests().antMatchers(HttpMethod.POST, "/api/logar")
.permitAll().antMatchers(HttpMethod.POST, "/api/registrar").permitAll().anyRequest().permitAll().and()
// filtra requisições de login
.addFilterBefore(new JWTLoginFilter("/api/logar", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
// filtra outras requisições para verificar a presença do
// JWT(token/autencicacao) no header
.addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(service).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// Configuração para devolver a autorização(token) do header
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
configuration
.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
// This allow us to expose the headers
configuration.setExposedHeaders(Arrays.asList("Access-Control-Allow-Headers",
"Authorization, x-xsrf-token, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, "
+ "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
<file_sep>INSERT INTO reserva(
id, fim_da_locacao, cliente_id, ativa, inicio_da_locacao, ambiente_id)
VALUES (1001,'2019-11-06 14:50:00',1001,true, '2019-11-06 14:10:00', 1001);
INSERT INTO arma_locada(id, quantidade, reserva_id, arma_id)
VALUES (1001, 1, 1001, 1001);<file_sep>server.port=9090
spring.jpa.database=POSTGRESQL
spring.datasource.platform=postgres
spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5432/namosca_db}
spring.datasource.username=postgres
spring.datasource.password=<PASSWORD>
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
spring.flyway.locations=classpath:db/migration/
spring.flyway.baseline-on-migrate=false
spring.flyway.url= ${DB_URL:jdbc:postgresql://localhost:5432/namosca_db}
spring.flyway.user= postgres
spring.flyway.password= <PASSWORD><file_sep>package br.com.stand.artilharia.repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import br.com.stand.artilharia.model.Arma;
@Repository
public interface ArmaRepository extends JpaRepository<Arma, Long> {
@Query("SELECT a FROM Arma a WHERE ?1 = NULL OR (a.descricao LIKE %?1%)")
Page<Arma> getAll(String busca, PageRequest pageRequest);
}<file_sep>package br.com.stand.artilharia.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import br.com.stand.artilharia.enums.Marca;
import br.com.stand.artilharia.enums.Calibre;
import br.com.stand.artilharia.enums.SituacaoDaArma;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import lombok.*;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(of = { "id" })
public class Arma implements Serializable, Modelo {
private static final long serialVersionUID = -4560616246394961016L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@NotEmpty(message = "Precisa preencher a descrição")
private String descricao;
@NotNull(message = "Precisa preencher a marca")
@Enumerated(EnumType.STRING)
private Marca marca;
@NotNull(message = "Precisa preencher o calibre")
@Enumerated(EnumType.STRING)
private Calibre calibre;
@NotNull(message = "Precisa preencher a situação")
@Enumerated(EnumType.STRING)
private SituacaoDaArma situacao;
public String getResumo(){
return descricao + " - " + marca + " - " + calibre + " | " + situacao;
}
}<file_sep>package br.com.stand.artilharia.repository;
import br.com.stand.artilharia.model.Reserva;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface ReservaRepository extends JpaRepository<Reserva, Long> {
@Query(value = "SELECT r FROM Reserva r " + "JOIN r.cliente c " + "WHERE ?1 = NULL")
Page<Reserva> buscarTodos(String busca, PageRequest pageRequest);
@Modifying
@Query("UPDATE Reserva SET ativa = false WHERE id =?1 ")
void inativar(Long id);
}<file_sep>package br.com.stand.artilharia;
import javax.annotation.PostConstruct;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
@SpringBootApplication
public class ArtilhariaApplication {
@Autowired
private ObjectMapper objectMapper;
public static void main(String[] args) {
SpringApplication.run(ArtilhariaApplication.class, args);
}
@PostConstruct
public void setUp() {
objectMapper.registerModule(new JavaTimeModule());
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Bean
public LocalValidatorFactoryBean getValidator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}
}
<file_sep>INSERT INTO credenciais (id,email,password,enabled) VALUES (1001,'<EMAIL>','<PASSWORD>',true);<file_sep>package br.com.stand.artilharia.exception;
import org.springframework.core.annotation.Order;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomExceptionInterceptor extends ResponseEntityExceptionHandler {
@ResponseBody
@ExceptionHandler(value = { BadCredentialsException.class })
@ResponseStatus(HttpStatus.FORBIDDEN)
public CustomExceptionSchema handleBadCredentials(BadCredentialsException ex) {
CustomExceptionSchema error = new CustomExceptionSchema(ex.getMessage());
return error;
}
@ResponseBody
@ExceptionHandler(value = { CustomException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public CustomExceptionSchema handleConflict(CustomException ex) {
CustomExceptionSchema error = new CustomExceptionSchema(ex.getMessage(), ex.getHint(), ex.getError());
return error;
}
@ResponseBody
@ExceptionHandler(value = { NotFoundException.class })
@ResponseStatus(HttpStatus.NOT_FOUND)
public CustomExceptionSchema handleNotFound(CustomException ex) {
CustomExceptionSchema error = new CustomExceptionSchema(ex.getMessage(), ex.getHint(), ex.getError());
return error;
}
}<file_sep>INSERT INTO arma
(id,descricao,marca,calibre,situacao)
VALUES
(1001, 'arma 1', 'GLOCK', 'CAL_22', 'DISPONIVEL'),
(1002, 'arma 2', 'TAURUS', 'CAL_388', 'DISPONIVEL'),
(1003, 'arma 3', 'ROSSI', 'CAL_4_5', 'DISPONIVEL');<file_sep>package br.com.stand.artilharia.controller;
import br.com.stand.artilharia.model.Reserva;
import br.com.stand.artilharia.service.ReservaService;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/reservas")
@AllArgsConstructor
public class ReservaController {
private ReservaService service;
@PostMapping
public ResponseEntity<Reserva> post(@RequestBody Reserva reserva) {
return ResponseEntity.ok().body(service.salvar(reserva, null));
}
@PutMapping("/{id}")
public ResponseEntity<Reserva> post(@RequestBody Reserva reserva, @PathVariable Long id) {
return ResponseEntity.ok().body(service.salvar(reserva, id));
}
@GetMapping("/inativar")
public ResponseEntity<Reserva> inativar(@RequestParam Long id) {
service.inativar(id);
return ResponseEntity.ok().build();
}
@GetMapping
public ResponseEntity<Page<Reserva>> getAll(@RequestParam("pagina") int pagina,
@RequestParam("tamanho") int tamanho, String busca) {
return ResponseEntity.ok()
.body(service.buscarTodos(busca, (PageRequest.of(pagina, tamanho, Sort.by("id").descending()))));
}
@GetMapping("{id}")
public ResponseEntity<Reserva> get(@PathVariable("id") Long id) {
return ResponseEntity.ok().body(service.buscarReservaPorId(id));
}
}
<file_sep>package br.com.stand.artilharia.service;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.jdbc.Sql;
import br.com.stand.artilharia.AbstractIntegrationTestsNamosca;
import br.com.stand.artilharia.model.Ambiente;
public class AmbienteTest extends AbstractIntegrationTestsNamosca {
@Autowired
AmbienteService ambienteService;
@Test
@Sql({ "/dataset/truncate.sql", "/dataset/ambientes.sql" })
public void deveBuscarTodosAmbientes() {
Page<Ambiente> ambientes = ambienteService.getAll("", PageRequest.of(0, 100));
assertThat(ambientes.getContent(), hasSize(2));
}
@Test
@Sql({ "/dataset/truncate.sql", "/dataset/ambientes.sql" })
public void deveSalvarAmbiente() {
Ambiente ambiente = Ambiente.builder().descricao("area 3").area(12).alvo(true).build();
ambienteService.save(ambiente);
assertNotNull(ambiente);
assertNotNull(ambiente.getId());
}
@Test
@Sql({ "/dataset/truncate.sql", "/dataset/ambientes.sql" })
public void deveBuscarUmAmbiente() {
Ambiente ambiente = ambienteService.findOne(1001L);
assertNotNull(ambiente);
assertNotNull(ambiente.getId());
}
@Test
@Sql({ "/dataset/truncate.sql", "/dataset/ambientes.sql" })
public void deveAtualizarAmbiente() {
Ambiente ambiente = Ambiente.builder().descricao("area 51").area(12).alvo(true).build();
ambienteService.update(1001L, ambiente);
assertThat(ambiente.getId(), equalTo(1001L));
assertEquals("area 51", ambiente.getDescricao());
}
}
<file_sep>version=0.0.1-SNAPSHOT
groupId=br.com.stand
artifactId=artilharia
<file_sep>package br.com.stand.artilharia.service;
import br.com.stand.artilharia.AbstractIntegrationTestsNamosca;
import br.com.stand.artilharia.model.Credenciais;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.jdbc.Sql;
import static org.junit.Assert.assertNotNull;
public class CredenciasTest extends AbstractIntegrationTestsNamosca {
@Autowired
CredenciaisService credenciaisService;
@Test
@Sql({"/dataset/truncate.sql"})
public void deveRegistrarCredencial() {
Credenciais credenciais = credenciaisService.register(Credenciais.builder().email("<EMAIL>").password("123").build());
assertNotNull(credenciais);
}
}
<file_sep>package br.com.stand.artilharia.service;
import br.com.stand.artilharia.repository.CredenciaisRepository;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@AllArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {
private CredenciaisRepository repository;
@Override
@Transactional
public UserDetails loadUserByUsername(String username) {
return repository.findCredentialByEmail(username)
.orElseThrow(() -> new UsernameNotFoundException("Usuário não encontrado:" + username));
}
@Transactional
public UserDetails loadUserById(Long id) {
return repository.findById(id).orElseThrow(
() -> new UsernameNotFoundException("Usuário com id: : " + id + " não encontrado"));
}
}
<file_sep>package br.com.stand.artilharia.security;
import br.com.stand.artilharia.exception.TokenExpiredException;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import java.util.Collections;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.util.Strings;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@Log4j2
class TokenAuthenticationService {
// EXPIRATION_TIME = 60 min
static final long EXPIRATION_TIME = 3600000;
static final String SECRET = "MySecret";
static final String HEADER_STRING = "Authorization";
static void addAuthentication(HttpServletResponse response, String username) {
String JWT = Jwts.builder().setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET).compact();
response.addHeader(HEADER_STRING, JWT);
}
static Authentication getAuthentication(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
try {
if (!Strings.isEmpty(token)) {
String user = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody()
.getSubject();
if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
}
}
} catch (SignatureException ex) {
log.info("Invalid JWT Signature");
} catch (MalformedJwtException ex) {
log.info("Invalid JWT token");
} catch (ExpiredJwtException ex) {
log.info("Expired JWT token");
new TokenExpiredException("expired");
} catch (UnsupportedJwtException ex) {
log.info("Unsupported JWT exception");
} catch (IllegalArgumentException ex) {
log.info("Jwt claims string is empty");
}
return null;
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ReservaFormComponent } from './view/reserva/reserva-form/reserva-form.component';
import { ReservaListComponent } from './view/reserva/reserva-list/reserva-list.component';
import { HomeComponent } from './view/home/home.component';
const routes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'reserva',
children: [
{path: ':reserva_id', component: ReservaFormComponent },
{path: '', component: ReservaFormComponent }
]
},
{
path: 'reserva-list',
component: ReservaListComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class AmbienteService {
constructor(
private http : HttpClient
) { }
/**
* Retorna ambientes
*/
public getAmbientes () {
return this.http.get<any>('http://127.0.0.1:9090/api/ambientes?busca=&pagina=0&tamanho=20');
};
}
<file_sep>package br.com.stand.artilharia.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import br.com.stand.artilharia.model.Arma;
import br.com.stand.artilharia.repository.ArmaRepository;
@Service
public class ArmaService extends DefaultService<ArmaRepository, Arma> {
@Override
public Page<Arma> getAll(String busca, PageRequest pageRequest) {
return repo.getAll(busca, pageRequest);
}
}<file_sep>import { Component, OnInit } from '@angular/core';
import { ReservaService } from 'src/app/service/reserva.service';
@Component({
selector: 'app-reserva-list',
templateUrl: './reserva-list.component.html',
styleUrls: ['./reserva-list.component.css']
})
export class ReservaListComponent implements OnInit {
constructor(
private reservaService: ReservaService,
) { }
reservas: any[];
ngOnInit(
) {
this.bindReserva();
}
bindReserva(): void {
this.reservaService.listarReserva().subscribe(data => {
console.log(data);
this.reservas = data.content;
});
}
}
<file_sep>INSERT INTO ambiente (id,descricao,area,alvo)
VALUES (1001,'ambiente 1',15,true),
(1002,'ambiente 2',17,true);<file_sep>import { Component, OnInit } from '@angular/core';
import { ClienteService } from 'src/app/service/cliente.service';
import { AmbienteService } from 'src/app/service/ambiente.service';
import { ArmaService } from 'src/app/service/arma.service';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { ReservaService } from 'src/app/service/reserva.service';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-reserva-form',
templateUrl: './reserva-form.component.html',
styleUrls: ['./reserva-form.component.css']
})
export class ReservaFormComponent implements OnInit {
constructor(
private clienteService: ClienteService,
private ambienteService: AmbienteService,
private armaService: ArmaService,
private reservaService: ReservaService,
private router: Router,
private route: ActivatedRoute
) { }
/**
* variavaveis
* https://stackoverflow.com/questions/52364998/get-data-from-url-in-angular-5
*/
clientes: any[];
ambientes: any[];
reserva_id;
armas: any[];
armaSelecionada: any;
armasSelecionadas: {
id: number,
descricao:string,
calibre: string,
quantidade: number
}[] = new Array();
reserva: any = new Object;
formArma:FormGroup = new FormGroup({
arma: new FormControl('arma')
});
formReserva:FormGroup = new FormGroup({
id: new FormControl('id'),
cliente: new FormControl('cliente'),
ambiente: new FormControl('ambiente'),
dataHoraInicio: new FormControl('dataHoraInicio'),
dataHoraFim: new FormControl('dataHoraFim')
});
ngOnInit() {
this.bindClients();
this.bindAmbiente();
this.bindArma();
this.reserva_id = this.route.snapshot.paramMap.get("reserva_id");
if(this.reserva_id !== null){
this.bindFormData();
}else {
this.ff.id.value == "";
}
}
/**
* Carrega objeto clientes no options Clientes
*/
bindClients(): void {
this.clienteService.getClients().subscribe(data => {
this.clientes = data.content;
});
}
/**
* carrega objeto arma no options armas
*/
bindAmbiente(): void {
this.ambienteService.getAmbientes().subscribe(data => {
this.ambientes = data.content;
});
}
bindArma(): void {
this.armaService.getArmas().subscribe(data => {
this.armas = data.content;
});
}
/**
* Carrega formulário de Editar
*/
bindFormData(): void {
this.reservaService.listaReservaPorId(this.reserva_id).subscribe( data => {
console.log(data);
this.formReserva.setValue({
id: this.reserva_id,
cliente: data.cliente.id,
ambiente: data.ambiente.id,
dataHoraInicio: data.inicioDaLocacao,
dataHoraFim: data.fimDaLocacao
});
for (let i = 0; i < data.armaLocadas.length; i++){
this.armasSelecionadas.push(data.armaLocadas[i].arma);
}
});
}
public reservar(){
let armasReservadas = new Array();
for(let i = 0; i< this.armasSelecionadas.length; i++){
armasReservadas.push({id: this.armasSelecionadas[i].id, quantidade: 1});
}
console.log(this.ff.id.value);
this.reservaService.salvaReserva(
(this.ff.id.value === "id" ? null : this.ff.id.value),
this.ff.cliente.value,
this.ff.ambiente.value,
this.ff.dataHoraInicio.value,
this.ff.dataHoraFim.value,
armasReservadas
).subscribe( data => {
this.router.navigate(['/reserva-list'])
}, error => {
this.router.navigate(['/reserva-list'])
});
}
adicionaArma(): void {
this.armasSelecionadas.push(this.f.arma.value);
console.log(this.armasSelecionadas);
}
removeArma(index): void {
console.log("Chegou aqui");
console.log(index);
this.armasSelecionadas.splice(index, 1);
}
get f() {
return this.formArma.controls;
}
get ff(){
return this.formReserva.controls;
}
}
<file_sep>package br.com.stand.artilharia.exception;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class NotFoundException extends CustomException {
private static final long serialVersionUID = 4099874611502515942L;
public NotFoundException(String message, String hint, String error) {
super(message, hint, error);
}
}<file_sep>package br.com.stand.artilharia.controller;
import br.com.stand.artilharia.model.Cliente;
import br.com.stand.artilharia.service.ClienteService;
import javax.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@AllArgsConstructor
public class ClienteController extends DefaultController<Cliente> {
private ClienteService service;
@Override
@GetMapping("/clientes")
public ResponseEntity<Page<Cliente>> getAll(@RequestParam("pagina") int pagina,
@RequestParam("tamanho") int tamanho, String busca) {
return ResponseEntity.ok()
.body(service.getAll(busca, (PageRequest.of(pagina, tamanho, Sort.by("id").descending()))));
}
@Override
@GetMapping("/clientes/{id}")
public ResponseEntity<Cliente> get(@PathVariable("id") Long id) {
return ResponseEntity.ok().body(service.findOne(id));
}
@Override
@PostMapping("/clientes")
public ResponseEntity<Cliente> post(@Valid @RequestBody Cliente obj) {
return ResponseEntity.ok().body(service.save(obj));
}
@Override
@PutMapping("/clientes/{id}")
public ResponseEntity<Cliente> put(@PathVariable Long id,@Valid @RequestBody Cliente obj) {
return ResponseEntity.ok().body(service.update(id, obj));
}
@Override
@DeleteMapping("/clientes/{id}")
public ResponseEntity<Boolean> delete(@PathVariable Long id) {
return ResponseEntity.ok().body(service.delete(id));
}
}<file_sep>package br.com.stand.artilharia.exception;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
/**
* Kudos
* http://www.petrikainulainen.net/programming/spring-framework/spring-from-the-trenches-adding-validation-to-a-rest-api/
*
*/
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class MethodArgumentNotValidExceptionHandler extends ResponseEntityExceptionHandler {
// error handle for @Valid
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", new Date());
body.put("status", status.value());
//Get all errors
List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
body.put("errors", errors);
return new ResponseEntity<>(body, headers, status);
}
}
<file_sep>INSERT INTO cliente
(id,primeiro_nome,ultimo_nome,rg,cpf,telefone,data_nascimento)
VALUES
(1001, 'maria', 'joaquina', 46466874, 46456456, 30215445, '2001-07-01');<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ArmaService {
constructor(
private http : HttpClient
) { }
/**
* Retorna armas
*/
public getArmas () {
return this.http.get<any>('http://127.0.0.1:9090/api/armas?busca=&pagina=0&tamanho=20');
};
}
<file_sep>package br.com.stand.artilharia.security;
import java.io.IOException;
import java.util.Collections;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import br.com.stand.artilharia.exception.InvalidCredentialsExeception;
import br.com.stand.artilharia.model.Credenciais;
import lombok.extern.log4j.Log4j2;
@Log4j2
public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
public JWTLoginFilter(String url, AuthenticationManager authManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws JsonParseException, JsonMappingException, IOException {
Credenciais credentials = new ObjectMapper().readValue(request.getInputStream(), Credenciais.class);
try {
return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(credentials.getUsername(),
credentials.getPassword(), Collections.emptyList()));
} catch (Exception e) {
log.info(e);
throw new InvalidCredentialsExeception("Credenciais Inválidas", "Se esta conta te pertencer, tente recuperar",
"error.credential.credentials.invalid");
}
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain, Authentication auth) {
TokenAuthenticationService.addAuthentication(response, auth.getName());
}
}
<file_sep>package br.com.stand.artilharia;
import java.util.Locale;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import lombok.Getter;
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class AbstractIntegrationTestsNamosca {
@Getter
@Value("http://localhost:${local.server.port}")
String baseUrl;
/*-------------------------------------------------------------------
* ATTRIBUTES
*-------------------------------------------------------------------*/
/*-------------------------------------------------------------------
* CONSTRUCTORS
*-------------------------------------------------------------------*/
/*-------------------------------------------------------------------
* BEHAVIORS
*-------------------------------------------------------------------*/
/**
*
*/
@Before
public void beforeTest() {
Locale.setDefault(new Locale("pt"));
}
}
<file_sep>package br.com.stand.artilharia.exception;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
public abstract class CustomException extends RuntimeException {
private static final long serialVersionUID = -4079610358760664887L;
private String message;
private String hint;
private String error;
}<file_sep>package br.com.stand.artilharia.enums;
public enum Marca {
TAURUS, ROSSI, GLOCK, CBC, CZ
}<file_sep>package br.com.stand.artilharia.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import lombok.Getter;
import lombok.Setter;
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@Getter
@Setter
public class InvalidCredentialsExeception extends CustomException {
private static final long serialVersionUID = -4079610358760664887L;
public InvalidCredentialsExeception(String message, String hint, String error) {
super(message, hint, error);
}
}<file_sep>import { TestBed } from '@angular/core/testing';
import { ArmaService } from './arma.service';
describe('ArmaService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: ArmaService = TestBed.get(ArmaService);
expect(service).toBeTruthy();
});
});
<file_sep>import { TestBed } from '@angular/core/testing';
import { AmbienteService } from './ambiente.service';
describe('AmbienteService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: AmbienteService = TestBed.get(AmbienteService);
expect(service).toBeTruthy();
});
});
| 1f4bf3f58cf81ce2de09ddd2084758e6a76dc8b0 | [
"SQL",
"Markdown",
"INI",
"Java",
"TypeScript"
] | 39 | Java | LVKILL/DKL-System | b95f841b64e80c7fa516abe5588881e5d9140d4a | 35cda39f01e87693a877537682d8ee33f2a99ba0 |
refs/heads/master | <file_sep>package com.example.andy.hw5;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends ListActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(android.R.id.list);
ArrayList<AlbumItem> albumlist = new ArrayList<AlbumItem>();
albumlist.add(new AlbumItem("金州 勇士",R.drawable.icon1,"聖安東尼奧 馬刺",R.drawable.icons2));
AlbumArrayAdapter adapter = new AlbumArrayAdapter(this, albumlist);
listView.setAdapter(adapter);
//ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, albumlist);
//listView.setAdapter(adapter);
}
} | 38359656270317fc2ee91fe2d21f9788f826d24c | [
"Java"
] | 1 | Java | chenchunwei24k/Android-HW5 | df009047b339c559f985da13c20aae7f74e55a49 | 70e410c03b9becdaccfde34862821967ddf128b8 |
refs/heads/master | <repo_name>ImmrBhattarai/Calculator<file_sep>/program.py
a = 10
b = 20
sum = a + b
diff = b - a
mul = a * b
print(sum)
print(diff)
print(mul)
| 988bccfcf2581b9560f07cfa030cde437fe0c926 | [
"Python"
] | 1 | Python | ImmrBhattarai/Calculator | d68a465bd78335fb7b6c9cae7a595b5e68c54e88 | 2111ffc7c763fb3ba95c764f8ddfa15b01c09170 |
refs/heads/main | <file_sep>#include "money_man.hpp"
#include <iostream>
void mm::handling_input(mm::game& game, bool& quit, mm::object& player, bool& intro)
{
//input queue
SDL_Event event;
while(SDL_PollEvent(&event))
{
if(event.type==SDL_QUIT)
{
quit=true;
}
}
//keyboard
const uint8_t *keyboard_state=SDL_GetKeyboardState(NULL);
if(keyboard_state[SDL_SCANCODE_ESCAPE]) //ending game
{
quit=true;
}
if(keyboard_state[SDL_SCANCODE_SPACE] && (player.y+player.m_h) == game.floor_y) //jump
{
player.y_speed=-(int)(0.75*(float)RES_Y);
intro=false;
}
if(keyboard_state[SDL_SCANCODE_A]) //moving left
{
player.x_speed=-(int)(0.20*(float)RES_X);
}
if(keyboard_state[SDL_SCANCODE_D]) //moving right
{
player.x_speed=(int)(0.20*(float)RES_X);
}
if(keyboard_state[SDL_SCANCODE_A] && keyboard_state[SDL_SCANCODE_D])
{
player.x_speed=0;
}
}<file_sep>#include "money_man.hpp"
//rectangle collision
bool mm::is_colliding(mm::object& a, mm::object& b)
{
if( a.x+a.m_w > b.x &&
a.x < b.x+b.m_w &&
a.y+a.m_h > b.y &&
a.y < b.y+b.m_h)
{
return true;
}
else
{
return false;
}
}<file_sep>#include "money_man.hpp"
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <iostream>
mm::object::object(mm::game *game, const char* path, const int x_in, const int y_in, const int w, const int h)
{
m_game=game;
m_w=w;
m_h=h;
x=x_in;
y=y_in;
SDL_Surface *tmp_surface=IMG_Load(path);
if(tmp_surface==NULL)
{
std::cout << "[WARNING]: sprite at " << path << " couldn't be loaded" << std::endl;
exit(0);
}
texture=SDL_CreateTextureFromSurface(m_game->renderer, tmp_surface);
SDL_FreeSurface(tmp_surface);
}
void mm::object::render()
{
SDL_Rect dst_rect;
dst_rect.x=x;
dst_rect.y=y;
dst_rect.w=m_w;
dst_rect.h=m_h;
SDL_RenderCopy(m_game->renderer, texture, NULL, &dst_rect);
}
//render at a certain location
void mm::object::render(const int x_in, const int y_in)
{
SDL_Rect dst_rect;
dst_rect.x=x_in;
dst_rect.y=y_in;
dst_rect.w=m_w;
dst_rect.h=m_h;
SDL_RenderCopy(m_game->renderer, texture, NULL, &dst_rect);
}
void mm::object::render_frame(const int num_frame,const int x_in, const int y_in)
{
SDL_Rect src_rect;
src_rect.x=m_w*num_frame;
src_rect.y=0;
src_rect.w=m_w;
src_rect.h=m_h;
SDL_Rect dst_rect;
dst_rect.x=x_in;
dst_rect.y=y_in;
dst_rect.w=m_w;
dst_rect.h=m_h;
SDL_RenderCopy(m_game->renderer, texture, &src_rect, &dst_rect);
}
void mm::object::physics_update(const float time_secs, const uint32_t flags)
{
//location update
x=x+(x_speed)*time_secs;
y=y+(y_speed)*time_secs;
//bumping into screen borders
if(flags & SCREEN_COLLISION_FLAG)
{
if(x<0)
{
x=0;
x_speed=-x_speed;
}
if((x+m_w)>m_game->res_x)
{
x=m_game->res_x-m_w;
x_speed=-x_speed;
}
}
//gravity
if(flags & GRAVITY_FLAG)
{
y_speed=y_speed+(m_game->gravity*time_secs);
if((y+m_h) > m_game->floor_y)
{
x_speed=0;
y_speed=0;
y=m_game->floor_y-m_h;
}
}
}<file_sep>#include "money_man.hpp"
void mm::player_animate(mm::object& player, mm::time& time)
{
if(player.y==RES_Y-FLOOR_OFFSET-player.m_h)
{
mm::player_animation_idle(player, time);
}
if(player.y<RES_Y-FLOOR_OFFSET-player.m_h)
{
mm::player_animation_jump(player, time);
}
}
void mm::player_animation_idle(mm::object& player, mm::time& time)
{
static float idle_time=0;
if((player.y==RES_Y-FLOOR_OFFSET-player.m_h) && player.x_speed==0)
{
idle_time+=time.frametime_sec();
}
else
{
idle_time=0;
}
if(idle_time>0.5)
{
player.render_frame(1, player.x, player.y);
}
else
{
player.render_frame(0, player.x, player.y);
}
if(idle_time>1)
{
idle_time=0;
}
}
void mm::player_animation_jump(mm::object& player, mm::time& time)
{
if(player.y!=RES_Y-FLOOR_OFFSET-player.m_h)
{
player.render_frame(2, player.x, player.y);
}
}<file_sep>#include "money_man.hpp"
#include <ratio>
#include <chrono>
#include <iostream>
mm::time::time()
{
clock_begin=std::chrono::steady_clock::now();
clock_end=std::chrono::steady_clock::now();
frametime=std::chrono::duration_cast<std::chrono::duration<float>>(clock_end-clock_begin);
}
float mm::time::frametime_update_sec()
{
clock_end=std::chrono::steady_clock::now();
frametime=std::chrono::duration_cast<std::chrono::duration<float>>(clock_end-clock_begin);
clock_begin=clock_end;
return frametime.count();
}
float mm::time::frametime_sec()
{
return frametime.count();
}
void mm::time::keep_fps(int fps)
{
float frametime_total=(float)1/(float)fps;
float frametime_left=frametime_total-frametime.count();
if(frametime_left<0)
{
return;
}
frametime_left=frametime_left*1000;
SDL_Delay((uint32_t)frametime_left/2);
} <file_sep>#include "money_man.hpp"
#include <iostream>
#include <chrono>
#include <ratio>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <cstdio>
#include <SDL2/SDL.h>
#define PATH_PRE_RELEASE ..
#define PATH_LINUX_RELEASE /usr/games/money-man
#undef main
int main(int argc, char *argv[])
{
SDL_Color text_color={45, 44, 44, 0};
int floor_level;
std::cout << "init game base: " << std::endl;
mm::game game(GRAVITY_CONSTANT, floor_level, "../assets/font/Retroscape.ttf");
srand(time(NULL)); //initializing random seed
mm::time frametime;
//loading assets
std::cout << "loading assets:" << std::endl;
mm::object player(&game, "../assets/player_anim.png", RES_X/2, 0, 43, 127);
mm::object floor(&game, "../assets/ground_tile.png", 0, RES_Y-FLOOR_OFFSET, 128, 64);
mm::object dollar(&game, "../assets/dollar.png", 500, DOLLAR_MAX_HEIGHT, (int)(0.025*(float)RES_X), (int)(0.036*(float)RES_Y));
std::vector<mm::object> cloud;
for(int i=0; i<NUM_CLOUDS; i++)
{
cloud.push_back(mm::object(&game, "../assets/cloud1.png", rand()%RES_X, rand()%(int)(0.3*(float)RES_Y), (int)(0.0667*(float)RES_X), (int)(0.059*(float)RES_Y)));
cloud[i].x_speed=rand()%((int)(0.021*(float)RES_X))+(int)(0.005*(float)RES_X);
}
std::vector<mm::object> background;
int num_background_buildings_front=rand()%9+5;
int num_background_buildings_back=rand()%11+6;
int num_background_buildings=num_background_buildings_front+num_background_buildings_back;
//backrow of houses
for(int i=0; i<num_background_buildings_back; i++)
{
if(i%2==1)
{
background.push_back(
mm::object(
&game,
"../assets/building3.png",
rand()%RES_X,
(int)(0.7*(float)RES_Y),
(int)(0.025*(float)RES_X),
(int)(0.3*(float)RES_Y)));
}
else
{
background.push_back(
mm::object(
&game,
"../assets/building4.png",
rand()%RES_X,
(int)(0.8*(float)RES_Y),
(int)(0.035*(float)RES_X),
(int)(0.2*(float)RES_Y)));
}
}
//front row of houses
for(int i=0; i<num_background_buildings_front; i++)
{
if(i%2==1)
{
background.push_back(
mm::object(
&game,
"../assets/building1.png",
rand()%RES_X,
(int)(0.55*(float)RES_Y),
(int)(0.050*(float)RES_X),
(int)(0.5*(float)RES_Y)));
}
else
{
background.push_back(
mm::object(
&game,
"../assets/building2.png",
rand()%RES_X,
(int)(0.71*(float)RES_Y),
(int)(0.065*(float)RES_X),
(int)(0.29*(float)RES_Y)));
}
}
//text preparation
text_color={228,225,228,0};
mm::text intro_text1(&game, "WELCOME TO MONEY MAN", text_color);
mm::text intro_text2(&game, "YOU JUST GOT YOUR FIRST JOB", text_color);
mm::text intro_text3(&game, "BUT DO YOU HAVE WHAT IT TAKES", text_color);
mm::text intro_text4(&game, "TO WORK UNTIL RETIREMENT?", text_color);
mm::text intro_text5(&game, "PRESS <SPACE> TO START", text_color);
mm::text end_of_game1(&game, "CONGRATULATIONS!", text_color);
mm::text end_of_game2(&game, "YOU ARE NOW RETIRED", text_color);
mm::text end_of_game3(&game, "BUT SADLY YOU DIED TWO YEARS", text_color);
mm::text end_of_game4(&game, "LATER BECAUSE OF CANCER", text_color);
text_color={45,44,44,0};
char age[]="AGE: XX YEARS";
std::vector<mm::text> text_age;
int current_age=0;
for(int i=18; i<=65; i++)
{
sprintf(age+5, "%i YEARS", i);
text_age.push_back(mm::text(&game, age, text_color));
std::cout << age << std::endl;
}
int current_month=0;
mm::text text_month[]=
{
mm::text(&game, "JANUARY", text_color),
mm::text(&game, "FEBRUARY", text_color),
mm::text(&game, "MARCH", text_color),
mm::text(&game, "APRIL", text_color),
mm::text(&game, "MAY", text_color),
mm::text(&game, "JUNE", text_color),
mm::text(&game, "JULY", text_color),
mm::text(&game, "AUGUST", text_color),
mm::text(&game, "SEPTEMBER", text_color),
mm::text(&game, "OCTOBER", text_color),
mm::text(&game, "NOVEMBER", text_color),
mm::text(&game, "DECEMBER", text_color),
};
//main loop
bool intro=true;
bool quit=false;
while(!quit)
{
mm::handling_input(game, quit, player, intro);
if(intro==false)
{
//player hits dollars
if(mm::is_colliding(player, dollar)==true)
{
dollar.x=rand()%(RES_X-dollar.m_w);
dollar.y=rand()%(400)+DOLLAR_MAX_HEIGHT;
current_month++;
if(current_month==12)
{
current_month=0;
current_age++;
}
}
}
//Frame time management
std::cout << "Frame calculation time: " << frametime.frametime_sec()*1000 << " ms" << std::endl;
//render
//clouds
for(int i=0; i<NUM_CLOUDS; i++)
{
cloud[i].render();
cloud[i].physics_update(frametime.frametime_sec(), 0);
if(cloud[i].x>RES_X)
{
cloud[i].x=-cloud[i].m_w;
}
}
for(int i=0; i<num_background_buildings; i++)
{
background[i].render();
}
dollar.render();
//player animations
mm::player_animate(player, frametime);
for(int i=0; i<((RES_X/floor.m_w)+1); i++)
{
floor.render(i*floor.m_w,RES_Y-FLOOR_OFFSET);
}
if(current_age<=47)
{
text_age[current_age].render(0,0);
text_month[current_month].render(RES_X-500,0);
}
//end of game
if(current_age>47)
{
end_of_game1.render((int)(0.15*(float)RES_X),(int)(0.35*(float)RES_Y));
end_of_game2.render((int)(0.15*(float)RES_X),(int)(0.45*(float)RES_Y));
end_of_game3.render((int)(0.15*(float)RES_X),(int)(0.51*(float)RES_Y));
end_of_game4.render((int)(0.15*(float)RES_X),(int)(0.57*(float)RES_Y));
}
if(intro==true)
{
intro_text1.render((int)(0.15*(float)RES_X),(int)(0.35*(float)RES_Y));
intro_text2.render((int)(0.15*(float)RES_X),(int)(0.45*(float)RES_Y));
intro_text3.render((int)(0.15*(float)RES_X),(int)(0.51*(float)RES_Y));
intro_text4.render((int)(0.15*(float)RES_X),(int)(0.57*(float)RES_Y));
intro_text5.render((int)(0.15*(float)RES_X),(int)(0.65*(float)RES_Y));
}
//player physics
player.physics_update(frametime.frametime_sec(), GRAVITY_FLAG | SCREEN_COLLISION_FLAG);
frametime.keep_fps(TARGET_FPS);
frametime.frametime_update_sec();
game.update();
}
return 0;
}<file_sep>#include "money_man.hpp"
#include <SDL2/SDL.h>
void mm::game::update()
{
SDL_RenderPresent(renderer);
SDL_SetRenderDrawColor(renderer, 0, 187, 255, 0); //Skylike color
SDL_RenderClear(renderer);
}<file_sep># WELCOME TO MONEY MAN
Money Man is a simple 2D game about capitalism and earning money.
The goal is quite simple jump and move to get your monthly paycheck
to reach your ultimate goal of retiring.


## Download
There are releases on Github for Windows and Linux.
If you download the Linux version, there is a tar-ball available but
would have to make sure that libsdl2, libsdl2-image and libsdl2-ttf
are installed on your system. Otherwise you can use the .deb-package
then it is also possible to start the game by a simple
`money-man`
command.
## Compilation
CMake is used for building Money Man, so it is supposed to work under
windows too.
To build Money Man it is important to have SDL2, SDL2_image, SDL2_ttf,
CMake and a C++-compiler.
### Linux
The building instructions on Debian-based distributions are the following
ones:
`sudo apt install libsdl2-dev libsdl2-image-dev libsdl2-ttf-dev cmake`
`git clone git@github.com:tevoran/money-man.git`
`cd money-man`
`mkdir build`
`cd build`
`cmake ..`
`make`
`./money-man`
<file_sep>#include "money_man.hpp"
#include <SDL2/SDL.h>
#include <iostream>
int RES_Y=0;
int RES_X=0;
mm::game::~game()
{
TTF_Quit();
SDL_Quit();
}
mm::game::game(const float gravity_in, int& floor_level, const char *font_path)
{
gravity=gravity_in;
SDL_Init(SDL_INIT_EVERYTHING);
//getting system's resolution
SDL_DisplayMode vinfo;
if(SDL_GetDesktopDisplayMode(0, &vinfo)!=0)
{
std::cout << "[WARNING]: Couldn't get desktop resolution" << std::endl;
std::cout << SDL_GetError() << std::endl;
exit(0);
}
floor_level=vinfo.h-FLOOR_OFFSET;
floor_y=(float)floor_level;
RES_X=vinfo.w;
RES_Y=vinfo.h;
res_x=RES_X;
res_y=RES_Y;
window=SDL_CreateWindow("Money Man", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, res_x, res_y, SDL_WINDOW_FULLSCREEN);
if(window==NULL)
{
std::cout << "SDL can't create a window" << std::endl;
exit(0);
}
renderer=SDL_CreateRenderer(window, -1, 0);
if(renderer==NULL)
{
std::cout << "SDL can't create a renderer" << std::endl;
exit(0);
}
std::cout << "TTF Init: " << TTF_Init() << std::endl;
font=TTF_OpenFont(font_path, (int)(0.04*(float)RES_Y));
if(font==NULL)
{
std::cout << "[WARNING]: Font wasn't found at: " << font_path << std::endl;
std::cout << "ERROR: " << TTF_GetError() << std::endl;
exit(0);
}
}<file_sep>#pragma once
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <chrono>
#include <ratio>
#define GRAVITY_CONSTANT 750
#define FLOOR_OFFSET 64
#define DOLLAR_MAX_HEIGHT 0.5*RES_Y
#define NUM_CLOUDS 20
#define TARGET_FPS 60
#define GRAVITY_FLAG 0x01
#define SCREEN_COLLISION_FLAG 0x02
extern int RES_X;
extern int RES_Y;
namespace mm
{
class time
{
private:
std::chrono::steady_clock::time_point clock_begin;
std::chrono::steady_clock::time_point clock_end;
std::chrono::duration<float> frametime;
public:
time();
float frametime_update_sec();
float frametime_sec();
void keep_fps(int fps);
};
class game
{
private:
SDL_Window *window=NULL;
public:
int res_x=0;
int res_y=0;
float gravity=0;
float floor_y=0;
TTF_Font *font=NULL;
SDL_Renderer *renderer=NULL;
game(const float gravity_in, int& floor_level, const char *font_path);
~game();
void update();
};
class object
{
private:
SDL_Texture *texture=NULL;
mm::game *m_game=NULL;
public:
float x_speed=0;
float y_speed=0;
float x=0;
float y=0;
int m_w=0;
int m_h=0;
object(mm::game *game, const char* path, const int x_in, const int y_in, const int w, const int h);
void render();
void render(const int x_in, const int y_in);
void physics_update(const float time_secs, const uint32_t flags);
void render_frame(const int num_frame,const int x_in, const int y_in);
};
class text
{
private:
SDL_Texture *text_texture=NULL;
mm::game *m_game=NULL;
int m_w;
int m_h;
public:
text(mm::game *game, const char *text, SDL_Color& text_color);
void render(int x, int y);
};
void handling_input(mm::game& game, bool& quit, mm::object& player, bool& intro);
bool is_colliding(mm::object& a, mm::object& b);
void player_animate(mm::object& player, mm::time& time);
void player_animation_idle(mm::object& player, mm::time& time);
void player_animation_jump(mm::object& player, mm::time& time);
}<file_sep>#include "money_man.hpp"
#include <iostream>
mm::text::text(mm::game *game, const char *text, SDL_Color& text_color)
{
SDL_Surface *tmp_surface=TTF_RenderText_Solid(game->font, text, text_color);
text_texture=SDL_CreateTextureFromSurface(game->renderer, tmp_surface);
m_game=game;
m_h=tmp_surface->h;
m_w=tmp_surface->w;
SDL_FreeSurface(tmp_surface);
}
void mm::text::render(int x, int y)
{
SDL_Rect rect;
rect.w=m_w;
rect.h=m_h;
rect.x=x;
rect.y=y;
SDL_RenderCopy(m_game->renderer, text_texture, NULL, &rect);
} | 9acfa075f7b393c750c733dd4f950ec656bf38a3 | [
"Markdown",
"C++"
] | 11 | C++ | tevoran/money-man | 8aa2b0d44a5ba9b05d4c8404d7b4b4329ff306f6 | 6dad8516a792904788002f69913d74d9075a5e4a |
refs/heads/master | <file_sep>import * as introspector from "@langion/introspector";
import * as _ from "lodash";
import * as path from "path";
import { Prism } from "../../Prism";
import * as types from "../../typings";
import * as utils from "../../utils";
export abstract class Emitter<O extends string, E extends string, Context extends types.Context<O, E>>
implements types.EmitArgs<O, E> {
public prism: Prism<O, E>;
public introspections: Record<O, introspector.Introspection<O>>;
protected emit = {} as Record<O, types.Emit<O, E>>;
constructor(public emission: E, private args: types.EmitArgs<O, E>) {
this.prism = args.prism;
this.introspections = args.introspections;
}
public create(requestedFromEmission = this.emission) {
_.forEach(this.introspections, (i) => this.emitIntrospection(i, requestedFromEmission));
return this.emit;
}
protected hasUnknownSources() {
const result = _.some(this.introspections, (i) => i.origin === this.prism.config.unknown.origin);
return result;
}
protected addSpace(lines: string[]) {
const lastChar = _.last(lines);
if (lastChar !== "") {
lines.push("");
}
}
protected emitIntrospection(introspection: introspector.Introspection<O>, requestedFromEmission: E) {
const context = this.createContext(introspection, requestedFromEmission);
this.fillIntrospection(context.emit.lines, context);
this.fillHeadlines(context.emit.headlines, context);
if (this.args.transformEmit) {
this.args.transformEmit(context);
}
}
protected fillHeadlines(headlines: string[], context: types.Context<O, E>) {
this.fillImports(headlines, context);
}
protected fillImports(headlines: string[], context: types.Context<O, E>) {
const imports: string[] = [];
const emitFolder = this.prism.getFilePath(context.emit, false);
const connections = _.uniqWith(context.emit.connections, _.isEqual);
_.forEach(connections, (c) => {
if ("path" in c) {
let exportPath = c.path;
if (path.isAbsolute(exportPath)) {
exportPath = utils.getRelativePath(emitFolder, exportPath);
}
const line = `import ${c.import} from '${exportPath}';`;
imports.push(line);
return;
}
const name = this.prism.getEmissionName(c);
const importFolder = this.prism.getFilePath(c, false);
const file = utils.getRelativePath(emitFolder, importFolder);
const isNotThisFile = !!file;
if (isNotThisFile) {
const line = `import * as ${name} from '${file}';`;
if (!_.includes(imports, line)) {
imports.push(line);
}
}
});
this.mergeLines(headlines, imports);
}
protected createContext(introspection: introspector.Introspection<O>, requestedFromEmission: E) {
const requestedFrom: types.Connection<O, E> = {
origin: introspection.origin,
emission: requestedFromEmission,
};
const emit = this.prism.getEmit(this.emit, requestedFrom);
return { emit, requestedFrom, introspection } as Context;
}
protected mergeLines(dest: string[], source: string[]) {
source.forEach((v) => dest.push(v));
}
protected abstract fillIntrospection(lines: string[], context: Context): void;
}
<file_sep>import * as introspector from "@langion/introspector";
import * as _ from "lodash";
import { ApiraApi } from ".";
import { Emitter } from "../core/Emitter";
import * as types from "../typings";
import { GraphqlDefinition } from "./GraphqlDefinition";
export interface ControllersList<O extends string> {
name: string;
origin: O;
}
export interface GraphqlAggregatorProps {
resolveTypePath: string;
}
export class GraphqlAggregator<
O extends string,
E extends string,
Context extends types.Context<O, E> = types.Context<O, E>
> extends Emitter<O, E, Context> {
protected queryControllers: Array<ControllersList<O>> = [];
protected mutationControllers: Array<ControllersList<O>> = [];
private names = this.getGqlNames();
constructor(emission: E, args: types.EmitArgs<O, E>, public props: GraphqlAggregatorProps) {
super(emission, args);
}
public create() {
const result = super.create();
this.createGqlControllers(this.queryControllers, true);
this.createGqlControllers(this.mutationControllers, false);
return result;
}
public getNameForGql(
name: string,
isDuplicate: boolean,
origin: O,
gqlPostfix = "",
variablesNames: string[] = [],
) {
const graphql = this.prism.getEmitter<GraphqlAggregator<O, E, Context>>(GraphqlAggregator);
let result = name;
const isNameUsed = _.includes(graphql.names, result);
if (isNameUsed || isDuplicate) {
const originName = this.prism.getOriginName(origin);
const newName = `${result}${originName}${gqlPostfix}`;
if (_.includes(graphql.names, newName)) {
result = this.getNameForGql(newName, isDuplicate, origin, gqlPostfix, variablesNames);
} else {
result = newName;
}
}
result = variablesNames.length ? `${result}_${variablesNames.join("_")}` : result;
result = result.replace(/[\[\]]/g, "");
graphql.names.push(result);
return result;
}
protected fillHeadlines(headlines: string[], context: types.Context<O, E>) {
context.emit.connections.push({ import: "{resolveType}", path: this.props.resolveTypePath });
super.fillHeadlines(headlines, context);
headlines.push(`import * as graphql from 'graphql'`);
}
protected fillIntrospection(lines: string[], context: types.Context<O, E>): void {
this.prism.getEmit(this.emit, context.requestedFrom);
_.forEach(context.introspection.controllers, (c) => {
this.createQueryController(lines, c, context);
this.createMutationController(lines, c, context);
});
}
private getGqlNames() {
const names: string[] = [];
_.forEach(this.introspections, (i) => {
names.push(i.origin);
_.forEach(i.controllers, (c) => {
names.push(this.getQueryControllerName(c));
names.push(this.getMutationControllerName(c));
});
});
return names;
}
private createGqlControllers(controllers: Array<ControllersList<O>>, isQuery: boolean) {
const origin = isQuery ? ("query" as O) : ("mutation" as O);
const requestedFrom: types.Connection<O, E> = { origin, emission: this.emission };
this.prism.getEmit(this.emit, requestedFrom);
const emit = this.emit[requestedFrom.origin];
const name = isQuery ? "Query" : "Mutation";
const lines: string[] = [];
this.addSpace(lines);
lines.push(`export class ${name} {`);
lines.push("public create() {");
lines.push("return {");
const byService = _.groupBy(controllers, (c: introspector.Controller<O>) => c.origin);
_.forEach(byService, ({}, i) => {
const service = isQuery ? i : `${i}${name}`;
const serviceName = _.upperFirst(service);
lines.push(`${serviceName}: {type: new graphql.GraphQLObjectType({`);
lines.push(`name: '${serviceName}',`);
lines.push(`fields: {`);
controllers
.filter((c) => c.origin === i)
.forEach((c) => {
const type = this.prism.type.get({
kind: "TypeScript",
emit: this.emit,
requestedFrom: { origin, emission: this.emission },
typeLocation: { origin: c.origin, emission: this.emission },
type: {
comment: "",
generics: [],
kind: introspector.TypeKind.Entity,
name: c.name,
origin: c.origin,
isDuplicate: false,
},
});
lines.push(`${c.name}: {type: ${type}, resolve: () => ({})},`);
});
lines.push("}");
lines.push("}),");
lines.push("resolve: () => ({})},");
});
lines.push("}");
lines.push("}");
lines.push("}");
this.addSpace(lines);
this.fillHeadlines(emit.headlines, {
emit,
introspection: {
controllers: [],
origin: requestedFrom.origin,
addedFrom: requestedFrom.origin,
sources: [],
},
requestedFrom,
});
this.mergeLines(emit.lines, lines);
}
private createQueryController(
lines: string[],
controller: introspector.Controller<O>,
context: types.Context<O, E>,
) {
const methods = _.filter(controller.methods, (m) => m.request === "get");
if (!methods.length) {
return "";
}
const name = this.getQueryControllerName(controller);
this.queryControllers.push({ name, origin: context.introspection.origin });
const result = this.createController(lines, name, controller, methods, context.requestedFrom, context);
return result;
}
private createMutationController(
lines: string[],
controller: introspector.Controller<O>,
context: types.Context<O, E>,
) {
const methods = _.filter(controller.methods, (m) => m.request !== "get");
if (!methods.length) {
return "";
}
const name = this.getMutationControllerName(controller);
this.mutationControllers.push({ name, origin: context.introspection.origin });
const result = this.createController(lines, name, controller, methods, context.requestedFrom, context);
return result;
}
private getQueryControllerName(controller: introspector.Controller<O>) {
return controller.name;
}
private getMutationControllerName(controller: introspector.Controller<O>) {
return `${controller.name}Mutation`;
}
private createController(
lines: string[],
name: string,
controller: introspector.Controller<O>,
methods: Array<introspector.Method<O>>,
requestedFrom: types.Connection<O, E>,
context: types.Context<O, E>,
) {
const interplayName = this.getInterplayName(name);
this.addSpace(lines);
lines.push(`export namespace ${interplayName} {`);
this.addSpace(lines);
const introspection: introspector.Introspection<O> = {
controllers: [],
origin: requestedFrom.origin,
addedFrom: controller.addedFrom,
sources: controller.interplay,
};
const introspections = {} as Record<O, introspector.Introspection<O>>;
introspections[requestedFrom.origin] = introspection;
const emitter = this.prism.getEmitter(GraphqlDefinition) as GraphqlDefinition<O, E, types.Context<O, E>>;
const definitions = new GraphqlDefinition<O, E>(
emitter.emission,
{
prism: this.prism,
introspections,
},
{ rawTypePath: emitter.props.rawTypePath, gqlPostfix: interplayName, nullable: false },
);
const models = definitions.create(this.emission);
_.forEach(models, (e) => {
this.mergeLines(context.emit.headlines, e.headlines);
this.mergeLines(lines, e.lines);
});
const gqlName = this.getNameForGql(name, false, controller.origin);
lines.push(`}`);
this.addSpace(lines);
lines.push(`export const ${name} = new graphql.GraphQLObjectType({`);
lines.push(`name:"${gqlName}",`);
lines.push(`fields: {`);
_.forEach(methods, (m) => lines.push(this.createMethod(m, requestedFrom, interplayName)));
lines.push(`}`);
lines.push(`})`);
this.addSpace(lines);
}
private createMethod(method: introspector.Method<O>, requestedFrom: types.Connection<O, E>, interplayName: string) {
const returns = _.toArray(method.response);
let filtered =
returns.length > 1
? returns.filter(
(r) =>
![
introspector.TypeKind.Object,
introspector.TypeKind.Boolean,
introspector.TypeKind.List,
introspector.TypeKind.Date,
introspector.TypeKind.Number,
introspector.TypeKind.String,
introspector.TypeKind.Void,
].some((t) => t === r.kind),
)
: returns;
const definitionEmitter = this.prism.getEmitter(GraphqlDefinition);
if (filtered.length > 1) {
const withoutScalars: typeof filtered = [];
filtered.forEach((r) => {
if (r.kind === introspector.TypeKind.Entity) {
withoutScalars.push(r);
} else {
// tslint:disable-next-line:no-console
console.log(
`Cannot add Scalars to GraphQL response. Controller: "${method.controller.name}", Method: "${
method.name
}", Response: "${r.name}"`,
);
}
});
filtered = withoutScalars;
}
const response = filtered.map((r) =>
this.prism.type.get({
kind: "GraphQL",
isInputType: false,
type: r,
requestedFrom,
typeLocation: { origin: requestedFrom.origin, emission: definitionEmitter.emission },
emit: this.emit,
}),
);
const emitter = this.prism.getEmitter(ApiraApi);
const resolver = this.prism.type.get({
kind: "TypeScript",
type: {
name: `${method.controller.name}.${method.name === "delete" ? "del" : method.name}`,
comment: "",
generics: [],
kind: introspector.TypeKind.Entity,
origin: requestedFrom.origin,
isDuplicate: false,
},
requestedFrom,
emit: this.emit,
typeLocation: { origin: requestedFrom.origin, emission: emitter.emission },
});
let type = "Raw";
if (response.length === 1) {
type = response[0];
} else if (response.length > 1) {
const name = this.getNameForGql(
`${method.name}${method.controller.name}Response`,
false,
method.controller.origin,
);
type = `
(function() {
const types = [${response.join()}];
return new graphql.GraphQLUnionType({
name: '${name}',
resolveType: (v, c, i) => resolveType(v, c, i, types),
types
});
})()
`;
/* type = `
(function() {
const types = [${response.join()}];
return new graphql.GraphQLUnionType({
name: '${name}',
resolveType: (v, {}, i) => {
let path: string[] = [];
const updatePath = (part = i.path) => {
path.push(part.key.toString());
if (part.prev) {
updatePath(part.prev);
}
};
updatePath();
path = path.reverse();
const set = path.reduce(
(a: graphql.SelectionSetNode, c: string) => {
const node = a.selections.filter(s => 'name' in s && s.name.value == c);
const result = node.pop()!;
if ('selectionSet' in result) {
return result.selectionSet!;
} else {
return a;
}
},
i.operation.selectionSet
);
let type = types[0];
set.selections.forEach(s => {
if ('typeCondition' in s) {
const names = s.selectionSet.selections
.map(sel => ('name' in sel ? sel.name.value : ''))
.filter(sel => !!sel && sel !== '__typename');
const hasField = names.some(n => !!v[n]);
if (hasField) {
const result = types.find(t => t.name === s.typeCondition!.name.value);
if (result) {
type = result;
}
}
}
});
return type;
},
types
});
})()
`; */
}
const args = this.getArgs(method, requestedFrom, interplayName);
const field = this.createField(method, type, args, resolver);
return field;
}
private createField(method: introspector.Method<O>, type: string, args: string, resolver: string) {
const lines: string[] = [];
const path = method.path.replace(/\$/g, "\\$");
lines.push(`${method.name}: {`);
lines.push(`description: \`Path: ${path}\\n${method.comment}\`,`);
lines.push(`type: ${type}, `);
lines.push(`args: ${args},`);
lines.push("resolve: (source: any, args: any, c: any, info: any) =>");
lines.push(`${resolver} (args, {source, info, origin: '${method.controller.origin}', ...c})`);
lines.push("},");
const result = lines.join("");
return result;
}
private getArgs(method: introspector.Method<O>, requestedFrom: types.Connection<O, E>, interplayName: string) {
const lines: string[] = ["{"];
if (method.query.kind === introspector.TypeKind.Entity) {
const query = this.prism.type.get({
kind: "GraphQL",
isInputType: true,
emit: this.emit,
type: method.query,
requestedFrom,
typeLocation: requestedFrom,
});
lines.push(`query: {type: ${interplayName}.${query}},`);
}
if (method.params.kind === introspector.TypeKind.Entity) {
const params = this.prism.type.get({
kind: "GraphQL",
isInputType: true,
type: method.params,
requestedFrom,
typeLocation: requestedFrom,
emit: this.emit,
});
lines.push(`params: {type: new graphql.GraphQLNonNull(${interplayName}.${params})},`);
}
const emitter = this.prism.getEmitter(GraphqlDefinition);
const payload = _.map(method.payload, (p) =>
this.prism.type.get({
kind: "GraphQL",
isInputType: true,
emit: this.emit,
type: p,
requestedFrom,
typeLocation: {
origin: requestedFrom.origin,
emission: emitter.emission,
},
}),
);
if (payload.length === 1) {
lines.push(`payload: {type: new graphql.GraphQLNonNull(${payload[0]})},`);
} else if (payload.length > 1) {
lines.push(`payload: {type: new graphql.GraphQLNonNull(${payload[1]})},`);
}
lines.push("}");
return lines.join("\n");
}
private getInterplayName(name: string) {
return `${name}Interplay`;
}
}
<file_sep>import * as path from "path";
export function getRelativePath(source: string, target: string) {
if (source === target) {
return "";
}
const sourceWithoutFile = path.dirname(source);
const targetWithoutFile = path.dirname(target);
if (sourceWithoutFile === targetWithoutFile) {
const file = path.basename(target);
return `./${file}`;
} else {
const file = (path as any).relative(source, target);
const normalized = file.replace(/\\/g, "/").replace("../", "");
return normalized;
}
}
<file_sep>import * as graphql from "graphql";
export const Raw = new graphql.GraphQLScalarType({
name: "Raw",
description: "Сырое значение как есть",
serialize: (v: any) => {
return v;
},
parseValue: (v: any) => {
return v;
},
parseLiteral(ast: any) {
switch (ast.kind) {
case "BooleanValue":
return ast.value;
case "EnumValue":
return ast.value;
case "FloatValue":
return ast.value;
case "IntValue":
return ast.value;
case "ListValue":
return ast.values;
case "NullValue":
return null;
case "ObjectValue":
const result = {} as any;
ast.fields.forEach((f: any) => {
const asNumber = parseFloat(f.value.value);
result[f.name.value] = isNaN(asNumber) ? f.value.value : asNumber;
});
return result;
case "StringValue":
return ast.value;
case "Variable":
return ast.name;
}
},
});
<file_sep>import * as introspector from "@langion/introspector";
export function hasComment(shape: introspector.Shape) {
return !!shape.comment;
}
export function fillMultilineComment(lines: string[], shape: introspector.Shape) {
if (!hasComment(shape)) {
return false;
}
lines.push("/**");
const wraped = wrap(shape.comment);
wraped.forEach((l) => lines.push(`* ${l.trim()}`));
lines.push("*/");
return true;
}
function wrap(comment: string) {
const maxLength = 80;
const words = comment.split(" ");
const withLineBreaks = words.reduce(
(r, w) => {
if (r.count > maxLength) {
return { count: 0, line: `${r.line}\n${w}` };
} else {
return { count: r.count + w.length, line: `${r.line} ${w}` };
}
},
{
count: 0,
line: "",
},
);
const lines = withLineBreaks.line.split("\n");
return lines;
}
<file_sep>import * as introspector from "@langion/introspector";
import * as _ from "lodash";
import * as types from "../../typings";
import { Type } from "./Type";
export class BaseType<O extends string, E extends string> {
constructor(protected type: Type<O, E>) {}
protected getGenerics(desc: types.TypeDesc<O, E>) {
const generics = _.map(desc.type.generics, (t) => {
const genericData: types.TypeDesc<O, E> = {
...desc,
type: t.type,
typeLocation: { origin: t.type.origin, emission: desc.typeLocation.emission },
};
const generic = this.type.get(genericData);
return generic;
});
return generics;
}
protected getAnotherFilePrefix(desc: types.TypeDesc<O, E>) {
let prefix = "";
const isFromAnotherFile = !_.isEqual(desc.requestedFrom, desc.typeLocation);
const isInternalType = !(
desc.type.kind === introspector.TypeKind.Entity || desc.type.kind === introspector.TypeKind.Enumeration
);
if (isFromAnotherFile && !isInternalType) {
const connection: types.Connection<O, E> = {
origin: desc.type.origin,
emission: desc.typeLocation.emission,
};
prefix = this.type.prism.getEmissionName(connection);
const emit = this.type.prism.getEmit(desc.emit, desc.requestedFrom);
emit.connections.push(connection);
}
return prefix;
}
}
<file_sep>import * as graphql from "graphql";
export function resolveType<TSource, TContext>(
value: TSource,
{ }: TContext,
info: graphql.GraphQLResolveInfo,
types: graphql.GraphQLObjectType[],
) {
let path: string[] = [];
const updatePath = (part = info.path) => {
path.push(part.key.toString());
if (part.prev) {
updatePath(part.prev);
}
};
updatePath();
path = path.reverse();
const set = path.reduce(
(a: graphql.SelectionSetNode, c: string) => {
const node = a.selections.filter((s) => "name" in s && s.name.value === c);
const result = node.pop()!;
if ("selectionSet" in result) {
return result.selectionSet!;
} else {
return a;
}
},
info.operation.selectionSet,
);
let type = types[0];
set.selections.forEach((s) => {
if ("typeCondition" in s) {
const names = s.selectionSet.selections
.map((sel) => ("name" in sel ? sel.name.value : ""))
.filter((sel) => !!sel && sel !== "__typename");
const hasField = names.some((n) => !!(value as any)[n]);
if (hasField) {
const result = types.find((t) => t.name === s.typeCondition!.name.value);
if (result) {
type = result;
}
}
}
});
return type;
}
<file_sep>import * as introspector from "@langion/introspector";
import * as _ from "lodash";
import * as path from "path";
import { Emitter } from "../core/Emitter";
import * as types from "../typings";
import * as utils from "../utils";
import { TypeScriptDefinition } from "./TypeScriptDefinition";
export class ApiraApi<
O extends string,
E extends string,
Context extends types.Context<O, E> = types.Context<O, E>
> extends Emitter<O, E, Context> {
constructor(emission: E, private config: types.ApiraApiArgs<O, E>) {
super(emission, config);
}
protected fillHeadlines(headlines: string[], context: types.Context<O, E>) {
super.fillHeadlines(headlines, context);
const emitFolder = this.prism.getFilePath(context.emit, false);
const parsed = path.parse(this.config.apiAbsolutePath);
const apiAbsolutePath = path.join(parsed.dir, parsed.name);
const apiPath = utils.getRelativePath(emitFolder, apiAbsolutePath);
headlines.push(`import {api} from '${apiPath}'`);
}
protected fillIntrospection(lines: string[], context: types.Context<O, E>): void {
_.forEach(context.introspection.controllers, (c) => this.fillController(lines, c, context));
}
private fillController(lines: string[], controller: introspector.Controller<O>, context: types.Context<O, E>) {
this.addSpace(lines);
lines.push(`export namespace ${controller.name} {`);
const introspection: introspector.Introspection<O> = {
controllers: [],
origin: context.requestedFrom.origin,
addedFrom: controller.addedFrom,
sources: controller.interplay,
};
const introspections = {} as Record<O, introspector.Introspection<O>>;
introspections[context.requestedFrom.origin] = introspection;
const emitter = this.prism.getEmitter(TypeScriptDefinition);
const model = new TypeScriptDefinition<O, E>(emitter.emission, {
prism: this.prism,
introspections,
});
const models = model.create(this.emission);
_.forEach(models, (e) => {
this.mergeLines(context.emit.headlines, e.headlines);
this.mergeLines(lines, e.lines);
});
_.forEach(controller.methods, (m) => this.createMethod(lines, m, context.requestedFrom));
lines.push(`}`);
}
private createMethod(lines: string[], method: introspector.Method<O>, requestedFrom: types.Connection<O, E>) {
const url = this.createPath(method, requestedFrom);
const emitter = this.prism.getEmitter(TypeScriptDefinition);
const query = this.prism.type.get({
kind: "TypeScript",
emit: this.emit,
type: method.query,
requestedFrom,
typeLocation: requestedFrom,
});
const response =
_.map(method.response, (r) =>
this.prism.type.get({
kind: "TypeScript",
emit: this.emit,
type: r,
requestedFrom,
typeLocation: {
origin: requestedFrom.origin,
emission: emitter.emission,
},
}),
).join("|") || "void";
const payload =
_.map(method.payload, (p) =>
this.prism.type.get({
kind: "TypeScript",
emit: this.emit,
type: p,
requestedFrom,
typeLocation: {
origin: requestedFrom.origin,
emission: emitter.emission,
},
}),
).join("|") || "void";
const name = method.name === "delete" ? "del" : method.name;
this.addSpace(lines);
lines.push(`export const ${name} = api`);
lines.push(url);
lines.push(`.request<${response},${query}, ${payload}>('${method.request}')`);
lines.push(".build()");
this.addSpace(lines);
}
private createPath(method: introspector.Method<O>, requestedFrom: types.Connection<O, E>) {
const parts = [".path("];
if (method.params.name !== "void") {
const param = this.prism.type.get({
kind: "TypeScript",
type: method.params,
requestedFrom,
typeLocation: requestedFrom,
emit: this.emit,
});
const url = method.path.replace(/{/g, "${p.");
parts.push(`(p:${param}) => \`${url}\``);
} else {
parts.push(`'${method.path}'`);
}
parts.push(")");
return parts.join("");
}
}
<file_sep>import * as introspector from "@langion/introspector";
import * as prettier from "prettier";
import { Emitter } from "../core/Emitter";
import { Prism } from "../Prism";
import { Context } from "./Prism.types";
export interface SideOrigin<O extends string> {
origin: O;
name: string;
}
export interface EmitArgs<O extends string, E extends string> {
prism: Prism<O, E>;
introspections: Record<O, introspector.Introspection<O>>;
transformEmit?: (context: Context<O, E>) => void;
}
export interface ApiraApiArgs<O extends string, E extends string> extends EmitArgs<O, E> {
apiAbsolutePath: string;
}
export interface TSLintConfig {
enabled: boolean;
tslintConfigAbsolutePath: string;
addTsIgnore: boolean;
}
export interface PrismConfig<O extends string, E extends string> {
outFolderAbsolutePath: string;
introspections: Record<O, introspector.Introspection<O>>;
emitters: Array<(args: EmitArgs<O, E>) => Emitter<O, E, Context<O, E>>>;
unknown: SideOrigin<O>;
tslint: TSLintConfig;
prettier?: prettier.Options;
}
<file_sep>import * as fs from "fs";
import * as _ from "lodash";
import * as mkdirp from "mkdirp";
import * as path from "path";
import * as prettier from "prettier";
import { Configuration, Linter } from "tslint";
import { Emitter } from "./core/Emitter";
import { Type } from "./core/Type";
import * as types from "./typings";
export class Prism<O extends string, E extends string> {
public static emit<O extends string, E extends string>(config: types.PrismConfig<O, E>) {
const introemitter = new Prism(config);
const result = introemitter.emit();
return result;
}
public type: Type<O, E> = new Type<O, E>(this);
private files: Record<string, string[]> = {};
private emitters: Array<Emitter<O, E, types.Context<O, E>>> = [];
private constructor(public config: types.PrismConfig<O, E>) {}
public async emit() {
this.sort();
this.config.emitters.forEach((e) => this.addEmit(e));
this.emitters.forEach((e) => this.createEmit(e));
return await this.emitFiles();
}
public getEmit(emit: Record<O, types.Emit<O, E>>, connection: types.Connection<O, E>) {
if (!emit[connection.origin]) {
emit[connection.origin] = {
connections: [],
lines: [],
headlines: [],
origin: connection.origin,
emission: connection.emission,
};
}
return emit[connection.origin];
}
public getOriginName(origin: O) {
let name = _.upperFirst(origin);
if (origin === this.config.unknown.origin) {
name = this.config.unknown.name;
}
const result = _.upperFirst(name);
return result;
}
public getEmissionName(connection: types.Connection<O, E>) {
const origin = this.getOriginName(connection.origin);
const emission = _.upperFirst(connection.emission);
const name = `${origin}${emission}`;
return name;
}
public getEmitter<T extends Emitter<O, E, types.Context<O, E>>>(kind: new (...args: any[]) => T): T {
const emitter = _.find(this.emitters, (e) => e instanceof kind);
if (emitter) {
return emitter as any;
} else {
throw new Error(`Emitter ${kind.name} is not found`);
}
}
public getFilePath(connection: types.Connection<O, E>, withExtension: boolean) {
const folder = connection.emission.toLowerCase();
const base = this.config.outFolderAbsolutePath;
const name = this.getOriginName(connection.origin);
const file = withExtension ? `${name}.ts` : name;
const result = path.join(base, folder, file);
return result;
}
/**
* Enumerations should got last
*/
private sort() {
_.forEach(
this.config.introspections,
(i) => (i.sources = _.sortBy(i.sources, (s) => s.shape.kind === "Enumeration")),
);
}
private addEmit(createEmitter: (args: types.EmitArgs<O, E>) => Emitter<O, E, types.Context<O, E>>) {
const args: types.EmitArgs<O, E> = { introspections: this.config.introspections, prism: this };
const emitter = createEmitter(args);
this.emitters.push(emitter);
}
private createEmit(emitter: Emitter<O, E, types.Context<O, E>>) {
const emit = emitter.create();
this.addToFiles(emit);
}
private addToFiles(emit: Record<O, types.Emit<O, E>>) {
_.forEach(emit, (e) => {
if (!e.lines.length) {
return;
}
const file = this.getFilePath(e, true);
let headlines = _.uniq(e.headlines);
headlines = _.sortBy(headlines);
const page = headlines.concat(e.lines);
this.files[file] = page;
});
}
private async emitFiles() {
for (const file in this.files) {
if (file in this.files) {
const content = this.files[file];
await this.write(content, file);
}
}
}
private async write(page: string[], file: string) {
const folder = path.parse(file).dir;
await new Promise((resolve, reject) => mkdirp(folder, (err) => (err ? reject(err) : resolve())));
let content = page.join("\n");
const options: prettier.Options = {
printWidth: 120,
parser: "typescript",
...this.config.prettier,
};
try {
content = prettier.format(content, options);
} catch (e) {
// tslint:disable-next-line:no-console
console.error(`Error in prettier: ${e} in file ${file}`);
}
await this.writeContent(file, content);
if (this.config.tslint.enabled) {
const linter = new Linter({ fix: true });
const configuration = Configuration.loadConfigurationFromPath(this.config.tslint.tslintConfigAbsolutePath);
linter.lint(file, content, configuration);
const result = linter.getResult();
content = result.output;
}
if (this.config.tslint.addTsIgnore) {
const lines = ["/* tslint:disable */\n"];
lines.push("\n");
let fileContent = fs.readFileSync(file).toString();
lines.push(fileContent);
fileContent = lines.join("");
await this.writeContent(file, fileContent);
}
}
private async writeContent(file: string, content: string) {
await new Promise((resolve, reject) => fs.writeFile(file, content, (err) => (err ? reject(err) : resolve())));
}
}
<file_sep>import * as introspector from "@langion/introspector";
import * as _ from "lodash";
import { GraphqlDefinition } from "../../emitters";
import * as types from "../../typings";
import { Reference } from "../../typings";
import { BaseType } from "./BaseType";
import { Type } from "./Type";
export class GraphQLType<O extends string, E extends string> extends BaseType<O, E> {
constructor(private desc: types.GraphQLTypeGetter<O, E>, type: Type<O, E>) {
super(type);
}
public get() {
let name = this.mapType(this.desc.type.kind);
if (name) {
return name;
}
if (this.desc.type.kind === introspector.TypeKind.TypeParameter) {
return `${this.desc.type.name}!`;
}
name = this.desc.type.name;
const generics = this.getGenerics(this.desc);
if (this.desc.type.kind === introspector.TypeKind.List) {
let line = generics.join();
if (!line) {
line = this.getRawType();
}
name = `new graphql.GraphQLList(${line})`;
return name;
} else if (this.desc.type.kind === introspector.TypeKind.Map) {
return this.getRawType();
}
const prefix = this.getAnotherFilePrefix(this.desc);
if (prefix) {
name = `${prefix}.${name}`;
}
const genericLine = generics.join();
if (this.desc.type.kind === introspector.TypeKind.Enumeration) {
return name;
}
if (_.isNil(this.desc.isInputType)) {
name = `${name}(isInput, ${genericLine})`;
} else {
name = `${name}(${this.desc.isInputType}, ${genericLine})`;
}
return name;
}
public getRawType(): string {
const emitter = this.type.prism.getEmitter(GraphqlDefinition) as GraphqlDefinition<O, E, types.Context<O, E>>;
const reference: Reference = {
import: "{Raw}",
path: emitter.props.rawTypePath,
};
const emit = this.type.prism.getEmit(this.desc.emit, this.desc.requestedFrom);
emit.connections.push(reference);
return "Raw";
}
private mapType(kind: introspector.TypeKind) {
switch (kind) {
case introspector.TypeKind.Boolean:
return "graphql.GraphQLBoolean";
case introspector.TypeKind.Date:
return this.getRawType();
case introspector.TypeKind.Number:
return "graphql.GraphQLFloat";
case introspector.TypeKind.String:
return "graphql.GraphQLString";
case introspector.TypeKind.Object:
return this.getRawType();
case introspector.TypeKind.Void:
return this.getRawType();
default:
return "";
}
}
}
<file_sep>import * as introspector from "@langion/introspector";
export interface Connection<O extends string, E extends string> {
origin: O;
emission: E;
}
export interface Reference {
import: string;
path: string;
}
export interface Emit<O extends string, E extends string> extends Connection<O, E> {
headlines: string[];
lines: string[];
connections: Array<Connection<O, E> | Reference>;
}
export interface TypeInfo<O extends string, E extends string> {
type: introspector.Type<O>;
typeLocation: Connection<O, E>;
requestedFrom: Connection<O, E>;
emit: Record<O, Emit<O, E>>;
}
export interface TypeScriptTypeGetter<O extends string, E extends string> extends TypeInfo<O, E> {
kind: "TypeScript";
}
export interface GraphQLTypeGetter<O extends string, E extends string> extends TypeInfo<O, E> {
kind: "GraphQL";
isInputType?: boolean;
}
export type TypeDesc<O extends string, E extends string> = TypeScriptTypeGetter<O, E> | GraphQLTypeGetter<O, E>;
export interface Context<O extends string, E extends string> {
emit: Emit<O, E>;
requestedFrom: Connection<O, E>;
introspection: introspector.Introspection<O>;
}
<file_sep>import * as introspector from "@langion/introspector";
import * as types from "../../typings";
import { BaseType } from "./BaseType";
import { Type } from "./Type";
export class TypeScriptType<O extends string, E extends string> extends BaseType<O, E> {
constructor(private desc: types.TypeScriptTypeGetter<O, E>, type: Type<O, E>) {
super(type);
}
public get() {
let name = this.mapType(this.desc.type.kind);
if (name) {
return name;
}
name = this.desc.type.name;
const generics = this.getGenerics(this.desc);
const isMap = this.desc.type.kind === introspector.TypeKind.Map;
if (this.desc.type.kind === introspector.TypeKind.List) {
name = "Array";
} else if (isMap) {
name = "Record";
} else if (this.desc.type.kind === introspector.TypeKind.TypeParameter) {
return name;
}
const prefix = this.getAnotherFilePrefix(this.desc);
if (prefix) {
name = `${prefix}.${name}`;
}
if (generics.length) {
const line = isMap ? `string,${generics[1]}` : generics.join();
name = `${name}<${line}>`;
}
return name;
}
private mapType(kind: introspector.TypeKind) {
switch (kind) {
case introspector.TypeKind.Boolean:
return "boolean";
case introspector.TypeKind.Date:
return "Date";
case introspector.TypeKind.Number:
return "number";
case introspector.TypeKind.String:
return "string";
case introspector.TypeKind.Object:
return "{} | any";
case introspector.TypeKind.Void:
return "void";
default:
return "";
}
}
}
<file_sep>export * from "./ApiraApi";
export * from "./GraphqlAggregator";
export * from "./GraphqlDefinition";
export * from "./TypeScriptDefinition";
<file_sep>export * from "./config.types";
export * from "./Prism.types";
<file_sep>export * from "./Prism";
export * from "./emitters";
export * from "./typings";
<file_sep>import * as introspector from "@langion/introspector";
import * as _ from "lodash";
import { Emitter } from "../core/Emitter";
import * as types from "../typings";
import { GraphqlAggregator } from "./";
export interface GraphqlDefinitionProps {
rawTypePath: string;
gqlPostfix?: string;
nullable?: boolean;
}
export class GraphqlDefinition<
O extends string,
E extends string,
Context extends types.Context<O, E> = types.Context<O, E>
> extends Emitter<O, E, Context> {
constructor(emission: E, args: types.EmitArgs<O, E>, public props: GraphqlDefinitionProps) {
super(emission, args);
if (props.gqlPostfix === undefined) {
props.gqlPostfix = "";
}
if (props.nullable === undefined) {
props.nullable = true;
}
}
protected fillHeadlines(headlines: string[], context: types.Context<O, E>) {
context.emit.connections.push({ import: "{Raw}", path: this.props.rawTypePath });
super.fillHeadlines(headlines, context);
headlines.push(`import * as graphql from 'graphql'`);
}
protected fillIntrospection(lines: string[], context: types.Context<O, E>): void {
this.addSpace(lines);
_.forEach(context.introspection.sources, (s) => this.fillSource(lines, s, context));
}
private fillSource(lines: string[], source: introspector.Source<O>, context: types.Context<O, E>) {
if (source.shape.kind === "Enumeration") {
this.fillEnumeration(lines, source.shape, source.origin);
} else {
this.fillInterface(lines, source.shape, source.origin, context);
}
}
private fillEnumeration(lines: string[], enumeration: introspector.Enumeration, origin: O) {
const emitter = this.prism.getEmitter<GraphqlAggregator<O, E, Context>>(GraphqlAggregator);
const name = emitter.getNameForGql(enumeration.name, enumeration.isDuplicate, origin, this.props.gqlPostfix);
lines.push(`export const ${enumeration.name} = new graphql.GraphQLEnumType({`);
lines.push(`name: '${name}',`);
lines.push(`values: {`);
if (_.isEmpty(enumeration.values)) {
lines.push(`'empty': {value: 'empty'},`);
} else {
_.forEach(enumeration.values, (v) => lines.push(`'${v.key}': {value: \`${v.value}\`},`));
}
lines.push(`}`);
lines.push(`})`);
this.addSpace(lines);
}
private fillInterface(
lines: string[],
interfaze: introspector.Interface<O>,
origin: O,
context: types.Context<O, E>,
) {
const fillFields = () => {
_.forEach(interfaze.extends, (e) => this.fillExtends(lines, e, context.requestedFrom));
_.forEach(interfaze.fields, (f) => this.fillField(lines, f, context.requestedFrom));
};
const hasFields = !_.isEmpty(interfaze.fields) || !_.isEmpty(interfaze.extends);
this.fillDefinition(
lines,
interfaze.name,
fillFields,
hasFields,
interfaze.isDuplicate,
origin,
interfaze.comment,
interfaze.variables,
);
this.addSpace(lines);
}
private fillExtends(lines: string[], parent: introspector.Type<O>, requestedFrom: types.Connection<O, E>) {
const type = this.prism.type.get({
kind: "GraphQL",
type: parent,
typeLocation: {
origin: parent.origin,
emission: this.emission,
},
requestedFrom,
emit: this.emit,
});
lines.push("...(function() {");
lines.push(`const fields = ${type}.getFields();`);
lines.push(`const result: any = {};`);
lines.push(
"Object.keys(fields).forEach((k)=>result[k] = {type: fields[k].type, description: fields[k].description});",
);
lines.push("return result;");
lines.push("})(),");
}
private fillField(lines: string[], field: introspector.Field<O>, requestedFrom: types.Connection<O, E>) {
let type = this.prism.type.get({
kind: "GraphQL",
type: field.type,
typeLocation: {
origin: field.type.origin,
emission: this.emission,
},
requestedFrom,
emit: this.emit,
});
if (!this.props.nullable || field.isRequired) {
type = `new graphql.GraphQLNonNull(${type})`;
}
const result = `'${field.name}': {type: ${type}, description: \`${field.comment}\`},`;
lines.push(result);
}
private fillDefinition(
lines: string[],
name: string,
fillFields: () => void,
hasFields: boolean,
isDuplicate: boolean,
origin: O,
comment: string,
variables?: string[],
) {
const varTypesSignature = this.getVarTypes(origin, variables, true);
const varTypes = this.getVarTypes(origin, variables, false);
const emitter = this.prism.getEmitter<GraphqlAggregator<O, E, Context>>(GraphqlAggregator);
const variablesNames = _.map(variables, (v) => `\${${v}}`);
const nameForGql = emitter.getNameForGql(name, isDuplicate, origin, this.props.gqlPostfix, variablesNames);
lines.push(`export const ${name} = (() => {`);
lines.push(`const cache: Record<string, graphql.GraphQLObjectType | graphql.GraphQLInputObjectType> = {};`);
lines.push(``);
lines.push(`function ${name}(isInput: true, ${varTypesSignature.join()}): graphql.GraphQLInputObjectType;`);
lines.push(`function ${name}(isInput: false, ${varTypesSignature.join()}): graphql.GraphQLObjectType;`);
lines.push(`function ${name}(isInput: any, ${varTypes.join()}) {`);
lines.push(`let name = isInput`);
lines.push(`? \`${nameForGql}Input\``);
lines.push(`: \`${nameForGql}\`;`);
lines.push(``);
lines.push(`name = name.replace(/[\\[\\]]/g, '')`);
lines.push(``);
lines.push(`if (!cache[name]) {`);
lines.push(`const c = {`);
lines.push(`name,`);
lines.push(`description: \`${comment}\`,`);
lines.push(`interfaces: [],`);
lines.push(`fields: () => ({`);
lines.push(`raw: {type: Raw},`);
if (hasFields) {
fillFields();
}
lines.push(`}),`);
lines.push(`} as graphql.GraphQLObjectTypeConfig<any, any> | graphql.GraphQLInputObjectTypeConfig;`);
lines.push(``);
lines.push(`cache[name] = isInput`);
lines.push(`? new graphql.GraphQLInputObjectType(c as graphql.GraphQLInputObjectTypeConfig)`);
lines.push(`: new graphql.GraphQLObjectType(c as graphql.GraphQLObjectTypeConfig<any, any>);`);
lines.push(`}`);
lines.push(`return cache[name];`);
lines.push(`};`);
lines.push(``);
lines.push(`return ${name}`);
lines.push(`})();`);
}
private getVarTypes({}: O, variables?: string[], isSignature?: boolean) {
const baseTypes = "graphql.GraphQLOutputType | graphql.GraphQLInputObjectType | undefined";
const varTypes = _.map(variables, (v) => (isSignature ? `${v}?: ${baseTypes}` : `${v}: ${baseTypes} = Raw`));
return varTypes;
}
}
<file_sep># Prism
Emit Introspections into files.
<file_sep>import { Prism } from "../../Prism";
import * as types from "../../typings";
import { GraphQLType } from "./GraphQLType";
import { TypeScriptType } from "./TypeScriptType";
export class Type<O extends string, E extends string> {
constructor(public prism: Prism<O, E>) {}
public get(desc: types.TypeDesc<O, E>) {
switch (desc.kind) {
case "GraphQL":
return this.getAsGrapqhQL(desc);
case "TypeScript":
return this.getAsTypeScript(desc);
default:
const unknown = JSON.stringify(desc, undefined, 4);
throw new Error(`There is no Type ${unknown}`);
}
}
private getAsGrapqhQL(desc: types.GraphQLTypeGetter<O, E>) {
const type: GraphQLType<O, E> = new GraphQLType<O, E>(desc, this);
const result = type.get();
return result;
}
private getAsTypeScript(desc: types.TypeScriptTypeGetter<O, E>) {
const type: TypeScriptType<O, E> = new TypeScriptType<O, E>(desc, this);
const result = type.get();
return result;
}
}
<file_sep>import * as introspector from "@langion/introspector";
import * as _ from "lodash";
import { Emitter } from "../core/Emitter";
import * as types from "../typings";
import * as utils from "../utils";
export class TypeScriptDefinition<
O extends string,
E extends string,
Context extends types.Context<O, E> = types.Context<O, E>
> extends Emitter<O, E, Context> {
private enumNamesByOrigin = {} as Record<string, Record<string, number>>;
protected fillIntrospection(lines: string[], context: types.Context<O, E>) {
_.forEach(context.introspection.sources, (s) => this.fillSource(lines, s, context));
}
private fillSource(lines: string[], source: introspector.Source<O>, context: types.Context<O, E>) {
if (source.shape.kind === "Enumeration") {
this.fillEnumeration(lines, source.shape, context);
} else {
this.fillInterface(lines, source.shape, context);
}
}
private fillEnumeration(lines: string[], enumeration: introspector.Enumeration, context: types.Context<O, E>) {
if (!this.enumNamesByOrigin[context.emit.origin]) {
this.enumNamesByOrigin[context.emit.origin] = {};
}
const enumNames = this.enumNamesByOrigin[context.emit.origin];
this.addSpace(lines);
utils.fillMultilineComment(lines, enumeration);
let asTypeName = enumeration.name;
let asEnumName = `${enumeration.name}Enum`;
if (enumNames[asTypeName] === undefined) {
enumNames[asTypeName] = 1;
} else {
enumNames[asTypeName]++;
asTypeName = `${asTypeName}_${enumNames[asTypeName]}`;
}
if (enumNames[asEnumName] === undefined) {
enumNames[asEnumName] = 1;
} else {
enumNames[asEnumName]++;
asEnumName = `${asEnumName}_${enumNames[asEnumName]}`;
}
lines.push(`export enum ${asEnumName} {`);
_.forEach(enumeration.values, (v) => lines.push(`${v.key} = "${this.escapeString(v.value)}",`));
lines.push(`}`);
this.addSpace(lines);
const enumValues = _.map(enumeration.values, (v) => `"${this.escapeString(v.value)}"`);
const enumType = enumValues.length ? enumValues.join("|") : "string";
lines.push(`export type ${asTypeName} = ${enumType};`);
this.addSpace(lines);
}
private fillInterface(lines: string[], interfaze: introspector.Interface<O>, context: types.Context<O, E>) {
this.addSpace(lines);
utils.fillMultilineComment(lines, interfaze);
const name = this.getName(interfaze, context.requestedFrom);
lines.push(name);
_.forEach(interfaze.fields, (f) => this.fillField(lines, f, context.requestedFrom));
lines.push(`}`);
this.addSpace(lines);
}
private fillField(lines: string[], field: introspector.Field<O>, requestedFrom: types.Connection<O, E>) {
const type = this.prism.type.get({
kind: "TypeScript",
type: field.type,
requestedFrom,
typeLocation: {
emission: this.emission,
origin: field.type.origin,
},
emit: this.emit,
});
const hasComment = utils.hasComment(field);
if (hasComment) {
this.addSpace(lines);
}
utils.fillMultilineComment(lines, field);
const result = field.isRequired ? `"${field.name}":${type}` : `"${field.name}"?:${type}`;
lines.push(result);
if (hasComment) {
this.addSpace(lines);
}
}
private escapeString(str: string) {
const result = str
.replace(/\\/g, "\\\\")
.replace(/\$/g, "\\$")
.replace(/'/g, "\\'")
.replace(/"/g, '\\"');
return result;
}
private getName(interfaze: introspector.Interface<O>, requestedFrom: types.Connection<O, E>) {
const name = ["export", "interface", interfaze.name];
if (!_.isEmpty(interfaze.variables)) {
name.push("<");
const typeVariables = _.map(interfaze.variables, (v) => `${v}=void`).join();
name.push(typeVariables);
name.push(">");
}
if (!_.isEmpty(interfaze.extends)) {
name.push("extends");
const parents = _.map(interfaze.extends, (e) =>
this.prism.type.get({
kind: "TypeScript",
type: e,
requestedFrom,
typeLocation: {
emission: this.emission,
origin: e.origin,
},
emit: this.emit,
}),
);
name.push(parents.join());
}
name.push("{");
const result = name.join(" ");
return result;
}
}
| 80b29b3a47ba36a0bf6c25b9f6b3650581635ec1 | [
"Markdown",
"TypeScript"
] | 20 | TypeScript | Langion/prism | ad91227cb6f4e64d4b4ef3c5a578b7a09a3979f6 | cbb8b87563cd51971d819861c26af8cfec8bf604 |
refs/heads/master | <file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('five-great-lessons', {
url: '/about/five-great-lessons',
templateUrl: 'app/about/five-great-lessons/five-great-lessons.html',
controller: 'FiveGreatLessonsCtrl'
});
});
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('volunteer-info', {
url: '/pto/volunteer-info',
templateUrl: 'app/pto/volunteer-info/volunteer-info.html',
controller: 'VolunteerInfoCtrl'
});
});
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('alex', {
url: '/classrooms/alex',
templateUrl: 'app/classrooms/alex/alex.html',
controller: 'AlexCtrl'
});
});<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('montessori-student-handbook', {
url: '/about/montessori-student-handbook',
templateUrl: 'app/about/montessori-student-handbook/montessori-student-handbook.html',
controller: 'MontessoriStudentHandbookCtrl'
});
});
<file_sep><div ng-include="'app/header/header-contact.html'"></div>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h1>Contact Info</h1>
<p>
Lagunitas School is located in the heart of the San Geronimo Valley, just behind the San Geronimo Valley Community Center.
</p>
<p>
Sir Francis Drake & Meadow Way<br>
P.O. Box 308<br>
San Geronimo, 94963 CA
</p>
<p>
<strong>Montessori Secretary: <NAME></strong>
<br>
Phone: (415) 488-9437 (voice)<br>
Fax: (415) 488-9617 (fax)<br>
Email: <a href="mailto:<EMAIL>" class="blacklink" target="_blank"><EMAIL></a>
</p>
<p>
<strong>Lagunitas School District Info:</strong>
<br>
<a ui-sref="district-homepage">Lagunitas School District Website</a>
</p>
<p>Here's the Community Center on Google Maps (note that Google Maps currently shows the wrong location for the school):</p>
<p>
<iframe class="center-block" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3143.3192279745267!2d-122.6740058624268!3d38.01633671534455!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8085bfb56293b44d%3A0x5a2d0a8bc6907725!2sSan+Geronimo+Valley+Community+Center!5e0!3m2!1sen!2sus!4v1421019429751" width="100%" height="400" frameborder="0" style="border:0"></iframe>
</p>
</div>
</div>
</div>
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('nathan', {
url: '/classrooms/nathan',
templateUrl: 'app/classrooms/nathan/nathan.html',
controller: 'NathanCtrl'
});
});<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('erin', {
url: '/classrooms/erin',
templateUrl: 'app/classrooms/erin/erin.html',
controller: 'ErinCtrl'
});
});
<file_sep><div ng-include="'app/header/header-about.html'"></div>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h1>Frequently Asked Questions</h1>
<ol class="faq">
<li><span class="faq-question">What is the difference between Montessori and traditional education?</span>
<p>Montessori emphasizes learning through all five senses, not just through listening. watching or reading. Children in Montessori classes learn at their own pace and plan their work time independently, according to their own choice of activities. Learning is an exciting process of discovery, leading to concentration, motivation, self-discipline and a love of learning. Children learn in multi-age classes, forming communities in which the older children spontaneously share their knowledge with the younger children. Montessori represents an entirely different and very effective approach to education with a curriculum based in studies of geography, history, zoology, and botany.</p>
</li>
<li><span class="faq-question">Is Montessori good for children with learning disabilities? What about gifted children?</span>
<p>Montessori is designed to help all children reach their fullest potential in their own unique pace. A classroom whose children have varying abilities is a community in which everyone learns from one another and contributes. Moreover, multi-age grouping allows each child to find his or her own pace without feeling "ahead" or "behind" in relation to peers. Students do not receive letter grades and learning is co-operative rather than competitive. Our district has a resource program with speech and occupational therapy for students with identified needs.</p>
</li>
<li><span class="faq-question">Can I do Montessori at home with my child?</span>
<p>Yes, you can use Montessori principles of child development at home. Look at your home through your child's eyes. Children need sense of belonging and they get it by participating fully in the routines of everyday life. "Help me do it by myself" is the life theme of the child. Can you find ways for your child to participate in meal preparations, cleaning, gardening, caring for clothes, shoes, toys? Providing opportunities for independence is the surest way to build your child's self esteem.</p>
</li>
<li><span class="faq-question">What part does the teacher play in guiding the child?</span>
<p>The teacher builds on natural human tendencies toward exploration, hard work, creativity and communication to create a learning environment that heeds the evolving passions of the children. Through extensive observation and record-keeping, the teacher plans individual projects to enable each child to learn what s/he needs to progress. Each class has a teacher's aide during the morning, so both teacher and aide present small group lessons.</p>
</li>
<li><span class="faq-question">How much are parents involved? How frequent is communication with teachers?</span>
<p>We encourage as much parent participation as possible. These hours may be devoted to whatever activity the parent feels they can most effectively contribute (i.e. special classroom projects, field trips, preparation of classroom materials, gardening, special skills, etc. ) Many parents take a very active role assisting in the enrichment of their child's classroom. There are opportunities to communicate with teachers on a daily basis after 3:00 p.m. and request for longer discussions may be made at any time during the academic year. Formal parent/teacher conferences are scheduled in October and January.</p>
</li>
<li><span class="faq-question">Are Montessori children successful later in life?</span>
<p>Studies show that Montessori children are well prepared for later life, academically, socially and emotionally. In addition to scoring well on standardized testes, Montessori children have a sense of social responsibility and a stewardship for the world that comes from realizing they are citizens of the world. Graduates of Montessori programs are known to be responsible, ask provocative questions, show enthusiasm for learning, adapt easily to new situations and resolve conflicts peacefully.</p>
</li>
<li><span class="faq-question">Is Lagunitas Public Montessori religious?</span>
<p>Our school is independent of any religious affiliation. We believe it is important to nurture the spirit of the child and to respect all religious beliefs and spiritual paths.</p>
</li>
<li><span class="faq-question">What special training do your teachers have?</span>
<p>The traditional Montessori training is at least a full year of graduate level work for each multi-age grouping and stages of development of children. We have at least one certified (or partially certified) Montessori teacher and one aide in each classroom and often have additional teacher in training.</p>
</li>
<li><span class="faq-question">How long is the school year?</span>
<p>The schoolyear is about 10 months, from Late August to mid June.</p>
</li>
<li><span class="faq-question">What are the Montessori School hours?</span>
<p>Kindergarten:<br>
8:35 a.m. - 12:00 p.m. (Mon. - Fri.)</p>
<p>1st - 5th grade:<br>
8:35 a.m. - 2:55 p.m. (Mon, Tue, Thu, Fri.)<br>
8:35 a.m. - 2:00 p.m. (Wed.)</p>
</li>
<li><span class="faq-question">Is extended care available?</span>
<p>Extended Care is availabe at the San Geronimo Community Center.</p>
</li> <p>Kindergarten 7:00 a.m.-8:45 a.m.; 12:00 p.m.-6 p.m. $5.50/hr<br>
1st – 4th grade: 7:00 a.m.-8:45 a.m.; 3:00 p.m.-6 p.m. $5.50/hr<br>
Teens: SGV Teen Loft Center – 3:00 p.m.- 5 p.m. ($135 per year)<br>
Holiday childcare is also available.</p>
</li>
<li><span class="faq-question">Is school lunch available?</span>
<p>Daily, organic, hot lunches are available for $4.00, or reduced cost for families in need.</p>
</li>
<li><span class="faq-question">Is there a school bus?</span>
<p>There is a free school bus service, for students in the San Geronimo Valley.</p>
</li>
<li><span class="faq-question">How much is tuition?</span>
<p>Tuition is free! There are very few public Montessori schools and we are proud to be one of them.</p>
</li>
</ol>
</div>
</div>
</div>
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('prospective-families', {
url: '/about/prospective-families',
templateUrl: 'app/about/prospective-families/prospective-families.html',
controller: 'ProspectiveFamiliesCtrl'
});
});
<file_sep><div ng-include="'app/header/header-parents.html'"></div>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h1>Info for Prospective Families</h1>
<h2>Lagunitas School District</h2>
<p>The Lagunitas School District is composed of two campuses, San Geronimo Valley School and Lagunitas School. The district offers parents a unique opportunity to choose between two progressive educational programs for elementary-aged children. The Public Montessori Program and the Middle School are located on the lower Lagunitas School campus. The
Open Classroom operates from the upper San Geronimo Valley School campus. Students from all three programs continue their education at the Middle School at the Lagunitas School
campus.</p>
<p>The District Governing Board is responsible to the community at large and meets regularly at the Lagunitas School campus. Meetings are open to the public and agenda notices are posted via email and on the <a href="http://lagunitas.org/" target="_blank">Lagunitas School District website</a>.</p>
<p>The district employs an administrative staff for the combined three programs
including a superintendent, principal, and business manager. Together the superintendent and principal represent school and staff concerns to the District Governing Board. The school principal is available for conference appointments and encourages parents to freely communicate their ideas and concerns.</p>
<h2>Lagunitas Public Montessori Program</h2>
<p>Read the other pages of the <a ui-sref="lagunitas-montessori">about</a> section on this website for an overview of our Montessori program. If you want more fine-grained info, check out the <a ui-sref="montessori-student-handbook">Montessori program student handbook</a> and the <a ui-sref="district-student-handbook">Lagunitas School District student handbook</a>.</p>
<h2>Prospective Family Info Night</h2>
<p>Each spring, we host an infomrational session for prospective families, which includes introductions to each program in the district. This year's session will be on (add date here!).</p>
</div>
</div>
</div>
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('terry', {
url: '/classrooms/terry',
templateUrl: 'app/classrooms/terry/terry.html',
controller: 'TerryCtrl'
});
});
<file_sep>'use strict';
describe('Service: navMenu', function () {
// load the service's module
beforeEach(module('sgvmApp'));
// instantiate service
var navMenu;
beforeEach(inject(function (_navMenu_) {
navMenu = _navMenu_;
}));
it('should do something', function () {
expect(!!navMenu).toBe(true);
});
});
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('pauline', {
url: '/classrooms/pauline',
templateUrl: 'app/classrooms/pauline/pauline.html',
controller: 'PaulineCtrl'
});
});<file_sep>'use strict';
angular.module('sgvmApp')
.controller('HeaderCtrl', function ($scope) {
// Scheme: Math.random() * (max-non-inclusive - min-inclusive) + min-inclusive
// In other words, if there are 4 photos, use Math.random() * (5 - 1) + 1, with 1-based numbering in the photo names
$scope.randomPhotoNumber = Math.floor( Math.random() * (5 - 1) + 1 );
});
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('faq', {
url: '/about/faq',
templateUrl: 'app/about/faq/faq.html',
controller: 'FaqCtrl'
});
});
<file_sep>sgvmontessori
=============
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('about-pto', {
url: '/pto/about-pto',
templateUrl: 'app/pto/about-pto/about-pto.html',
controller: 'AboutPtoCtrl'
});
});
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('montessori-philosophy', {
url: '/about/montessori-philosophy',
templateUrl: 'app/about/montessori-philosophy/montessori-philosophy.html',
controller: 'MontessoriPhilosophyCtrl'
});
});
<file_sep><div ng-include="'app/header/header-parents.html'"></div>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h1>Montessori Student Handbook</h1>
<p>* Note that there's also a separate <a ui-sref="district-student-handbook"><span style="font-weight: bold; font-style: italic;">Lagunitas School District</span> Student Handbook</a>.</p>
<p><br><a class="btn btn-info" href="../../assets/docs/LPMHandbookJanuary2015.pdf" target="_blank" role="button">Download the Montessori Student Handbook</a><br><br></p>
<embed src="../../assets/docs/LPMHandbookJanuary2015.pdf" width="100%" height="600" type='application/pdf'>
</div>
</div>
</div>
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('meeting-schedule', {
url: '/pto/meeting-schedule',
templateUrl: 'app/pto/meeting-schedule/meeting-schedule.html',
controller: 'MeetingScheduleCtrl'
});
});
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('bylaws', {
url: '/pto/bylaws',
templateUrl: 'app/pto/bylaws/bylaws.html',
controller: 'BylawsCtrl'
});
});
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('michelle', {
url: '/classrooms/michelle',
templateUrl: 'app/classrooms/michelle/michelle.html',
controller: 'MichelleCtrl'
});
});<file_sep><div ng-include="'app/header/header-about.html'"></div>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h1>About the Lagunitas Public Montessori Program</h1>
<p>The Montessori Program, situated on the Lagunitas School campus, spans grade levels kindergarten through fifth grade. The program derives its philosophical base from the teachings of Dr. <NAME>, and is committed to her educational precepts and practices. Montessori believed that learning is an exciting process of discovery, leading to concentration, motivation, self-discipline, love of learning and peace.</p>
<p>The actual <a ui-sref="curriculum">curriculum</a> reflects a fusion of the teachings and materials supported by Montessori and the educational requirements delineated in the California State Frameworks. Through the cultural subjects of—history, geography, and the sciences—students are encouraged to see themselves as the citizens of the world, and they learn to recognize the interrelationships of all living things. It is our goal that children develop a lifelong sense of responsibility for themselves and for the earth.</p>
<h2>History of our Program</h2>
<p>Convinced that the Montessori method of education suited their children, a group of parents committed themselves to the task of creating a public Montessori program within the Lagunitas School District. Thus, in November of 1981, Marin Parents for a Public Montessori (MPPM) was founded in San Geronimo. By the fall of 1982, this dedicated group realized their dream. After surmounting the political and financial obstacles inherent in implementing such a program, MPPM proudly opened the doors of Marin County’s first public Montessori classrooms serving students from Kindergarten through grade two at the San Geronimo Campus. The growing needs of the program required the yearly creation of a new classroom that was furnished, financed, and staffed. Motivated parents and staff dedicated to the creation of a public Montessori program successfully met these challenges.</p>
<p>Parents and staff, throughout the program’s history, have worked to embody the principles of community, cooperation, respect, responsibility, and individual as well as group effort. Making education an adventure has contributed greatly to the Montessori program’s success.</p>
<h2>Staff</h2>
<p>All teachers hold a California teaching credential and, pursuant to Lagunitas School District Board policy, training as a Montessori instructor. Newly hired teachers and any teachers being considered for reassignment into the Montessori program are required to hold specialized Montessori training. Candidates with full Montessori Certification are preferred and all training should be complete before teaching in the program. In the classroom, a part-time teacher’s aide and parent volunteers support each teacher. District resource specialists provide consultation and additional instruction for children with special needs in reading, math, and language. Teacher education and staff and curriculum development are
ongoing processes. Staff participation in workshops, in-service training, and continuing education courses enhances the curriculum and keep teachers in touch with current developments in education. These trainings also enable integration of newer approaches into the Montessori sequence.</p>
<h2>Classroom Environment</h2>
<p>The Montessori classroom is a very engaging place where children learn through experience. Two fundamental aspects are observed—the child centered-environment and the effort to maintain a low student-to-teacher ratio achieved with teachers’ aides and volunteering parents. The teacher establishes and prepares the environment and presents a variety of lessons. Beginning in the earliest years, students are gradually expected to manage their own time in light of the work to be done. Thus they learn to focus their attention on a wide variety of project-based activities that allow for the application of knowledge and skills to real world situations. Activities provide purpose, procedure, closure and opportunity for success.</p>
<p>This sort of curriculum is designed to promote independence, a love of learning, and increasing levels of responsibility for planning work time. To address the needs of the whole child, the curriculum also specifically nurtures cognitive, physical, social-emotional, spiritual, and psychological development. The overall goal is that children experience the joy of self development and mastery and that they perceive themselves as the source of their own learning and growth.</p>
<h3>Teachers</h3>
<p>Our program’s teachers embody the core beliefs of Montessori philosophy, such as respect for the individual learner, preparation of the classroom environment, respect for each student’s emotional and developmental needs, and recognizing the intrinsically motivating factors in each individual student. Teachers encourage students’ spontaneous intellectual activity, support self teaching, provide opportunities for community building and give clear and
meaningful individual and small group lessons.</p>
<h3>Multi-age Grouping</h3>
<p>Integral to the Montessori philosophy is the implementation of multi-age classroom groupings. The rationale is that leading, sharing, and modeling peers in a developmental range offers a maximum opportunity for interactive learning. It allows the child to accelerate, review past lessons as needed and reinforce concepts at progressively abstract levels. The Montessori
curriculum, coupled with wide age groupings, challenges each student to excel.</p>
<p>A pure Montessori configuration would place children from three to six years of age together, those from six to nine together, and those from nine to twelve together. These groupings (based on child development research) are not always possible in our small public school setting. The program strives to maintain class configurations to include two or three grade levels in which children spend those years in the same class. From the origination of the Montessori Program, the parent organization, (currently PTO) has provided input and feedback to the teacher group and administration on the proposed class configurations for the following year.</p>
<h3>Physical Environment</h3>
<p>The Program’s classrooms are equipped with as full as possible range of Montessori materials to support the curriculum. Materials are easily accessible to students and are displayed in an aesthetically pleasing manner. Teachers inspect and evaluate the inventory of specialized Montessori materials and furnishings for completeness and good working condition. The PTO gathers information from the teachers to assess the need to invest in updated Montessori tools and enhancements. Key features in the Montessori classrooms are cleanliness and order, logical organization of materials, appropriately sized furnishings, areas allowing for varying activities (individual/group, floor/table, noisy/quiet, and active/sedentary), and a provision for the display of students’ work.</p>
<h3>Independence</h3>
<p>Development is the result of an individual’s own work and experience. As Montessori stated, “My vision is of individuals passing from one stage of independence to a higher, by means of their own activity through their own effort of will, which constitutes the inner evolution of the individual.” The Montessori program respects and encourages the child’s ability to work independently, taking care not to pamper, patronize, or overprotect. Children are assigned real responsibilities and they are expected within reason to act for themselves. Nurturing of the child is directed toward increasing independence and self-sufficiency. Large blocks of uninterrupted instructional time support focused student learning. The Program schedules enrichment activities and transitions to accommodate these blocks.</p>
<h3>Respect</h3>
<p>Independent thinking is valued and students are encouraged to express their ideas clearly and respectfully. A sense of respect is extended to the use of material objects in the classroom and the campus facility at large.</p>
<h3>Class Meetings</h3>
<p>In addition to the morning circle that begins each day, class meetings are held on a regular or as needed basis. The students often set the agenda, and either a teacher or a student leads the discussion. In this setting, topics such as class projects, playground and interpersonal issues, and future plans are discussed.</p>
<h3>Punctuality</h3>
<p>Parents are responsible for ensuring that their children arrive at school on time. It is essential that all students be present at the beginning of class so that they may feel part of the group and oriented for the day’s activities. Interruptions by late children take time and energy from the rest of the class as well as the teacher. Parents should hold any morning social conversations in the parking lot away from classrooms and walkways.</p>
<h3>Field Trips</h3>
<p>The curriculum of study for the elementary-aged child is the world. Whenever possible the world is brought into the classroom. Yet, the interests of the child naturally extend beyond the classroom walls. Students are offered opportunities to explore the community, environment, and other settings outside the classroom. Parents attend field trips as volunteer drivers and chaperones—this is essential to the success of each trip. Every effort is made to keep the extra cost of field trips low. In order to provide educational opportunities outside the classroom the Program requests from parents field trip-specific donations to help cover the cost of charges associated with outside excursions. Sometimes, a fee (rather than a requested donation) is required for chaperoning adults. Field trips change each year but some examples or regular favorites include:</p>
<ul>
<li>Dance Palace programming</li>
<li>California Academy of Sciences</li>
<li>Exploratorium</li>
<li>Marin Organic Farm Field Studies</li>
<li>Marin Sanitation</li>
<li>Cultural performances through Marin County Youth in Arts </li>
<li>Stapleton Theatre Company</li>
<li>Various other museums in the Bay Area</li>
<li>Annual Spring Equinox hike to Divide Meadow (see traditions)</li>
<li>Biannual trips to Heart’s Desire Beach (see traditions)</li>
<li>4th-5th grade only field trips include:</li>
<li>Malikoff Diggins California History – 2 night/3 day field trip (alternating years)</li>
<li>Marin Headlands YMCA – 2 night/3 day field trip (alternating years)</li>
</ul>
<h2>What's Great About Montessori</h2>
<ul>
<li>Fosters a love for learning – from using manipulatives while learning math and grammar to researching areas of interest, students have fun while learning.</li>
<li>Inspired - students are proud of themselves for the good work they have completed rather than looking for external approval from teacher or parents.</li>
<li>Independence - students learn to be accountable for their own work and learning.</li>
<li>Collaboration - group projects allow students to work together and learn from other students.</li>
<li>Freedom within a structured, prepared environment.</li>
<li><a ui-sref="five-great-lessons">The 5 Great Lessons</a> are taught at the beginning of every school year and students gain a new level of understanding each time they are presented.
<ul>
<li>First Great Lesson – The Story of the Beginning of the Universe</li>
<li>Second Great Lesson – The Coming of Life</li>
<li>Third Great Lesson – The Story of Human Beings</li>
<li>Fourth Great Lesson – The Story of Language</li>
<li>Fifth Great Lesson - The Story of Numbers</li>
</ul>
</li>
<li>Organization and self-regulation – Within the prepared environment, students get to choose what work to do and (in the older classrooms) how to manage their time.</li>
<li>Multi-age environment – there are usually 2 grades in each classroom allowing the younger kids to learn from the older. Mentoring between older and younger kids through the buddy program. Middle school kids work as aides in some classrooms. All of this creates a tight-knit family-like school community.</li>
<li>Strong cultural/geographic Studies – each year a continent is studied culminating in the Continent Day celebration. A North American country is also studied each year. Montessori education creates responsible citizens of the world.</li>
<li>Many types of instruction - individual, small group, and whole class instruction; hands on learning; learning through student presentations.</li>
<li>Personal motivation and perseverance - students learn to be self-motivated and to persevere until the work is done.</li>
<li>Strong academics - State Standards are blended with Montessori Philosophy to create strong academics in a fun environment.</li>
<li>Well-prepared for Middle School – Montessori teachers work closely with Middle School teachers to make sure students are ready for 6th grade.</li>
<li>Strong community - many community events through the year: back to school potluck, Montessori campout, Fall Festival fundraiser, Montessori social nights, overnight fieldtrips.</li>
<li>Creative expression - Montessori’s Cultural Curriculum naturally includes the arts and opportunities for creative expression in the course of daily classroom activities. In addition to this, there are weekly enrichment classes.</li>
<li>Enrichments classes - in art, music, garden, technology, and band (for 4th and 5th grades).</li>
<li>Positive discipline approach to behavior is used. Emotional literacy vocabulary and concepts are emphasized in the classroom. A Peace Table format is used in the classrooms and is facilitated by the teachers for conflict resolution between students.</li>
</ul>
<!-- content to add? Maybe add this stuff in a section called Facts? Or in the FAQ?
Current number of students?
Student to Teacher/Aide Ratio:<br>
Classrooms include a full time teacher, a part-time teacher's aide and daily parent volunteers.<br><br>
Extracurricular Activities:<br>
Music, Art, Environmental Education, Band, Gardening, Wellness & Nutrition, Interscholastic Sports, Field Trips, Spanish Lab (4th & 5th grades)<br><br>
Financial Aid for Field Trips:<br>
Assistance is available based on need<br><br>
SGVCC Summer Program:<br>
Summer day camp: Kindergarten through 5th Grade<br><br>
SGVCC After School Enrichment Classes:<br>
Drawing, Performance Workshop, Martial Arts, Belly/Modern Dance, Ballet, Vet Care, Cooking, Capoeira, Yoga, Fencing, Knitting and more classes for kids/adults!<br><br>
The Montessori/Middle School Library:<br>
The School library is offers a wealth of resources in a warm and friendly setting.<br><br>
San Geronimo Valley Cultural Center:<br>
The SGVCC is adjacent to the Montessori campus and is a huge asset to the school. The SGVCC builds a strong community by focusing on human services and educational programs.<br><br>
</p>
-->
</div>
</div>
</div>
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('lagunitas-montessori', {
url: '/about/lagunitas-montessori',
templateUrl: 'app/about/lagunitas-montessori/lagunitas-montessori.html',
controller: 'LagunitasMontessoriCtrl'
});
});
<file_sep>'use strict';
angular.module('sgvmApp')
.config(function ($stateProvider) {
$stateProvider
.state('fall-festival', {
url: '/pto/fall-festival',
templateUrl: 'app/pto/fall-festival/fall-festival.html',
controller: 'FallFestivalCtrl'
});
});
| 66a747d1f94bb83dc48f6b188091db27d1dcdf5c | [
"JavaScript",
"HTML",
"Markdown"
] | 25 | JavaScript | seantcoyote/sgvmontessori | 2475ef866dd642dfa7db44a771574f8ed0a9a2ee | 8b1a5fa2402982abc5c8250eae778f7248ca251b |
refs/heads/master | <file_sep>include_recipe 'build-essential'
include_recipe 'git'
directory "#{Chef::Config[:file_cache_path]}/Singularity" do
owner node[:singularity][:user]
end
git "#{Chef::Config[:file_cache_path]}/Singularity" do
repository 'https://github.com/HubSpot/Singularity.git'
reference node[:singularity][:git_ref]
user node[:singularity][:user]
action :export
end
execute 'build_singularity' do
action :run
# Maven (or rather npm) has issues with
# being run as root.
user node[:singularity][:user]
environment('HOME' => node[:singularity][:home])
command '/usr/bin/mvn clean package -DskipTests'
creates "#{Chef::Config[:file_cache_path]}/Singularity/" \
'SingularityService/target/' \
"SingularityService-#{node[:singularity][:version]}-" \
'SNAPSHOT-shaded.jar'
cwd "#{Chef::Config[:file_cache_path]}/Singularity"
end
<file_sep>logrotate_app 'singularity' do
path node[:singularity][:log_file]
if node[:singularity][:size]
size node[:singularity][:size]
else
frequency node[:singularity][:frequency]
end
rotate node[:singularity][:logs_to_keep]
create '644 root root'
template_mode '0644'
options %w(copytruncate
missingok
compress
delaycompress)
end
<file_sep>default[:singularity][:log_file] = '/var/log/singularity/singularity.log'
default[:singularity][:logs_to_keep] = 14
default[:singularity][:log_rotate_frequency] = 'daily'
| e622e188ac443d787728830c5734ec9b89e51387 | [
"Ruby"
] | 3 | Ruby | samsalisbury/Singularity | fe6028d6165969d7db2a17820c504285f19a7bce | 5b89deb5579d93fd13671f0b8c6115399686b65c |
refs/heads/master | <file_sep>const { MongoClient, ObjectID } = require('mongodb');
MongoClient.connect(
'mongodb://localhost:27017/TodoApp',
(error, client) => {
if (error) {
return console.log('Unable to connect to Database', error);
}
console.log('Connected to MongoDB server.');
const db = client.db('TodoApp');
// db.collection('Todos')
// .find()
// .count()
// .then(
// count => {
// console.log("To Do's count:");
// console.log(count);
// },
// err => {
// console.log('Unable to fetch ToDos.', err);
// }
// );
// client.close();
db.collection('Users')
.find({ name: 'Valerie' })
.count()
.then(
count => {
console.log(`Valerie is inside your array ${count} times!`);
},
err => {
console.log('Unable to fetch data.', err);
}
);
}
);
| c3caa616cd2f3280b1c737c53bcf7ecd7aafcd43 | [
"JavaScript"
] | 1 | JavaScript | v-ern/node-course-2-todo-api | 5b6bf5bb2c7d7010aef1f78bbce08b7bd303bf37 | d3a559feac65dbf37c47a6b216ee3d83b0529f71 |
refs/heads/master | <file_sep>from config import DB as db
from models import User, Message
db.connect()
db.create_tables([User, Message])
db.close()
| 4b1652b7fa5837824bf6057f72048c820b40ec7b | [
"Python"
] | 1 | Python | joyin1211/FirstInnoBotTest | 54c7ef8bc8712d9aa8e2e6107afbc294fd4859ea | 89c963796a4db6c950a33bf920345fe9131815b5 |
refs/heads/master | <repo_name>subhanmahmood/netbeansCh5<file_sep>/src/MainForm.java
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
/*
* 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.
*/
/**
*
* @author subha
*/
public class MainForm extends javax.swing.JFrame {
final double luxuryRate = 1.75;
final double standardRate = 1.00;
final double economyRate = 0.45;
double estimatedCost;
/**
* Creates new form MainForm
*/
public MainForm() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTabbedPane5 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtIDVerified = new javax.swing.JTextField();
txtNameVerified = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txtEmailVerified = new javax.swing.JTextField();
txtSurnameVerified = new javax.swing.JTextField();
jSeparator1 = new javax.swing.JSeparator();
txtID = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txtSurname = new javax.swing.JTextField();
txtAddress1 = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
txtName = new javax.swing.JTextField();
txtAddress2 = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
txtPostCode = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
txtCountry = new javax.swing.JTextField();
jLabel12 = new javax.swing.JLabel();
txtPhone = new javax.swing.JTextField();
jLabel13 = new javax.swing.JLabel();
txtEmail = new javax.swing.JTextField();
chkVerify = new javax.swing.JCheckBox();
txtImage = new javax.swing.JTextField();
reset = new javax.swing.JButton();
attach = new javax.swing.JButton();
lblImage = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jSeparator2 = new javax.swing.JSeparator();
jLabel19 = new javax.swing.JLabel();
jLabel20 = new javax.swing.JLabel();
paintType = new javax.swing.JComboBox<>();
chkUndercoat = new javax.swing.JCheckBox();
jLabel21 = new javax.swing.JLabel();
txtLength = new javax.swing.JTextField();
txtHeight = new javax.swing.JTextField();
txtWidth = new javax.swing.JTextField();
txtHeight2 = new javax.swing.JTextField();
lblPaintTypeCost = new javax.swing.JLabel();
lblCost = new javax.swing.JLabel();
lblUndercoatCost = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jLabel22 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
jLabel24 = new javax.swing.JLabel();
jLabel26 = new javax.swing.JLabel();
jLabel29 = new javax.swing.JLabel();
txtNameReport = new javax.swing.JTextField();
txtSurnameReport = new javax.swing.JTextField();
txtIDReport = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
txtAddressReport = new javax.swing.JTextArea();
jLabel25 = new javax.swing.JLabel();
jLabel27 = new javax.swing.JLabel();
jLabel28 = new javax.swing.JLabel();
txtPhoneReport = new javax.swing.JTextField();
txtEmailReport = new javax.swing.JTextField();
jSeparator3 = new javax.swing.JSeparator();
jLabel30 = new javax.swing.JLabel();
txtTotalReport = new javax.swing.JTextField();
calculate = new javax.swing.JButton();
jLabel31 = new javax.swing.JLabel();
jLabel32 = new javax.swing.JLabel();
jLabel33 = new javax.swing.JLabel();
txtLengthReport = new javax.swing.JTextField();
txtHeightReport = new javax.swing.JTextField();
txtWidthReport = new javax.swing.JTextField();
jLabel34 = new javax.swing.JLabel();
paintTypeReport = new javax.swing.JComboBox<>();
chkUndercoatReport = new javax.swing.JCheckBox();
jLabel35 = new javax.swing.JLabel();
print = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Customer ID");
jLabel2.setText("Name");
txtIDVerified.setEditable(false);
txtNameVerified.setEditable(false);
txtNameVerified.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNameVerifiedActionPerformed(evt);
}
});
jLabel3.setText("Email");
jLabel4.setText("Surname");
txtEmailVerified.setEditable(false);
txtSurnameVerified.setEditable(false);
jLabel6.setText("Customer ID");
jLabel7.setText("Last Name");
jLabel8.setText("First Name");
jLabel9.setText("Address");
jLabel10.setText("Postal Code");
jLabel11.setText("Country");
jLabel12.setText("Phone");
txtPhone.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtPhoneActionPerformed(evt);
}
});
jLabel13.setText("Email");
chkVerify.setText("Verify details");
chkVerify.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
chkVerifyStateChanged(evt);
}
});
chkVerify.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chkVerifyActionPerformed(evt);
}
});
reset.setText("Reset");
reset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resetActionPerformed(evt);
}
});
attach.setText("Attach");
attach.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
attachActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(chkVerify)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtIDVerified, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtNameVerified, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(47, 47, 47)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtEmailVerified, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtSurnameVerified, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(11, 11, 11)
.addComponent(txtSurname, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(47, 47, 47)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtID))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtAddress1, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
.addComponent(txtAddress2)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(jLabel12)
.addComponent(jLabel13))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtEmail)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtPostCode, javax.swing.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE)
.addComponent(txtPhone))
.addGap(49, 49, 49)
.addComponent(jLabel11)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtCountry))))))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtImage, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(reset)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
.addComponent(attach))
.addComponent(lblImage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtIDVerified, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(txtEmailVerified, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtNameVerified, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(txtSurnameVerified, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(jLabel6)
.addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(txtSurname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(lblImage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(txtAddress1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtImage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtAddress2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(reset)
.addComponent(attach))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(jLabel11)
.addComponent(txtCountry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPostCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(txtPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13)
.addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(chkVerify)
.addContainerGap(216, Short.MAX_VALUE))
);
jTabbedPane5.addTab("Customer Details", jPanel1);
jLabel5.setFont(new java.awt.Font("Roboto Black", 0, 12)); // NOI18N
jLabel5.setText("Walls A and C");
jLabel14.setFont(new java.awt.Font("Roboto Black", 0, 12)); // NOI18N
jLabel14.setText("Walls B and D");
jLabel15.setText("Length");
jLabel16.setText("Height");
jLabel17.setText("Width");
jLabel18.setText("Height");
jLabel19.setFont(new java.awt.Font("Roboto Black", 0, 12)); // NOI18N
jLabel19.setText("Paint Details");
jLabel20.setText("Paint Type");
paintType.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Luxury", "Standard", "economy"}));
paintType.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
paintTypeActionPerformed(evt);
}
});
chkUndercoat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chkUndercoatActionPerformed(evt);
}
});
jLabel21.setText("Undercoat");
txtWidth.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtWidthActionPerformed(evt);
}
});
lblPaintTypeCost.setText(" ");
lblCost.setText(" ");
lblUndercoatCost.setText(" ");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel5)
.addComponent(jLabel14)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel17)
.addGap(18, 18, 18)
.addComponent(txtWidth, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel18)
.addGap(18, 18, 18)
.addComponent(txtHeight2, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel19)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel20)
.addComponent(jLabel21))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(chkUndercoat)
.addComponent(paintType, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15)
.addComponent(jLabel16))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtHeight)
.addComponent(txtLength))))
.addGap(37, 37, 37)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblPaintTypeCost)
.addComponent(lblCost)
.addComponent(lblUndercoatCost))
.addContainerGap(383, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5)
.addGap(73, 73, 73)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(txtLength, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(txtHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel17)
.addComponent(txtWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel18)
.addComponent(txtHeight2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblPaintTypeCost))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel19)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel20)
.addComponent(paintType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(chkUndercoat)
.addComponent(jLabel21)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(lblCost)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblUndercoatCost)))
.addContainerGap(167, Short.MAX_VALUE))
);
jTabbedPane5.addTab("Room Details", jPanel2);
jLabel22.setFont(new java.awt.Font("Roboto Black", 0, 12)); // NOI18N
jLabel22.setText("Walls A and C");
jLabel23.setText("<NAME>");
jLabel24.setText("<NAME>");
jLabel26.setText("Customer ID");
jLabel29.setFont(new java.awt.Font("Roboto Black", 0, 12)); // NOI18N
jLabel29.setText("Room Details");
txtNameReport.setEditable(false);
txtSurnameReport.setEditable(false);
txtIDReport.setEditable(false);
txtAddressReport.setEditable(false);
txtAddressReport.setColumns(20);
txtAddressReport.setRows(5);
jScrollPane1.setViewportView(txtAddressReport);
jLabel25.setText("Address");
jLabel27.setText("Phone");
jLabel28.setText("Email");
txtPhoneReport.setEditable(false);
txtEmailReport.setEditable(false);
jLabel30.setFont(new java.awt.Font("Roboto Black", 0, 12)); // NOI18N
jLabel30.setText("Total");
txtTotalReport.setEditable(false);
calculate.setText("Calculate");
calculate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculateActionPerformed(evt);
}
});
jLabel31.setText("Length");
jLabel32.setText("Height");
jLabel33.setText("Width");
txtLengthReport.setEditable(false);
txtHeightReport.setEditable(false);
txtWidthReport.setEditable(false);
jLabel34.setText("Paint Type");
paintTypeReport.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Luxury", "Standard", "economy"}));
chkUndercoatReport.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chkUndercoatReportActionPerformed(evt);
}
});
jLabel35.setText("Undercoat");
print.setText("print");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator3)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel22)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel23)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtNameReport, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel26)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtIDReport, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel24)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtSurnameReport, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(jLabel25)
.addGap(18, 18, 18))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel27)
.addGap(27, 27, 27)))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE)
.addComponent(txtPhoneReport, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtEmailReport))))
.addComponent(jLabel28))
.addGap(18, 18, 18)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel31)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtLengthReport))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel32)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtHeightReport, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel33)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtWidthReport, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel29)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel34)
.addComponent(jLabel35))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(chkUndercoatReport)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 111, Short.MAX_VALUE))
.addComponent(paintTypeReport, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(print)))))
.addContainerGap())
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel30)
.addGap(18, 18, 18)
.addComponent(txtTotalReport, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculate)
.addGap(20, 20, 20))))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel22)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel23)
.addComponent(jLabel26)
.addComponent(txtNameReport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtIDReport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(print))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel24)
.addComponent(txtSurnameReport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel25))
.addGap(7, 7, 7)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel27)
.addComponent(txtPhoneReport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel28)
.addComponent(txtEmailReport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel29)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel31)
.addComponent(txtLengthReport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel32)
.addComponent(txtHeightReport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel33)
.addComponent(txtWidthReport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel34)
.addComponent(paintTypeReport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel35)
.addComponent(chkUndercoatReport))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel30)
.addComponent(txtTotalReport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(calculate))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTabbedPane5.addTab("Price Quote", jPanel3);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane5)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane5)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtPhoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPhoneActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtPhoneActionPerformed
private void txtNameVerifiedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNameVerifiedActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtNameVerifiedActionPerformed
private void chkUndercoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkUndercoatActionPerformed
// TODO add your handling code here:
double length = Double.parseDouble(txtLength.getText());
double width = Double.parseDouble(txtWidth.getText());
double height = Double.parseDouble(txtHeight.getText());
if(chkUndercoat.isSelected()){
lblUndercoatCost.setText("Addition £0.50 / sqm ( + £" + (((length * width) + (2 * length * height) + (2 * height * width) * 0.50) + ")"));
chkUndercoat.setSelected(true);
}else{
lblUndercoatCost.setText("No extra charges!");
}
chkUndercoatReport.setSelected(chkUndercoat.isSelected());
}//GEN-LAST:event_chkUndercoatActionPerformed
private void txtWidthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtWidthActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtWidthActionPerformed
private void chkUndercoatReportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkUndercoatReportActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chkUndercoatReportActionPerformed
private void chkVerifyStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_chkVerifyStateChanged
// TODO add your handling code here:
}//GEN-LAST:event_chkVerifyStateChanged
private void chkVerifyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkVerifyActionPerformed
// TODO add your handling code here:
String customerName, customerSurname, customerID, customerEmail, customerAddress, customerPhone;
customerID = txtID.getText();
customerName = txtName.getText();
customerSurname = txtSurname.getText();
customerAddress = txtAddress1.getText() + " " + txtAddress2.getText() + " " + txtPostCode.getText() + " " + txtCountry.getText();
customerPhone = txtPhone.getText();
customerEmail = txtEmail.getText();
if(chkVerify.isSelected()){
txtIDVerified.setText(customerID);
txtEmailVerified.setText(customerEmail);
txtNameVerified.setText(customerName);
txtSurnameVerified.setText(customerSurname);
txtIDReport.setText(customerID);
txtEmailReport.setText(customerEmail);
txtNameReport.setText(customerName);
txtSurnameReport.setText(customerSurname);
txtAddressReport.setText(customerAddress);
txtPhoneReport.setText(customerPhone);
}
}//GEN-LAST:event_chkVerifyActionPerformed
private void resetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetActionPerformed
// TODO add your handling code here:
txtImage.setText("");
}//GEN-LAST:event_resetActionPerformed
private void attachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_attachActionPerformed
// TODO add your handling code here:
JFileChooser image = new JFileChooser();
int returnval = image.showOpenDialog(this);
if(returnval==JFileChooser.APPROVE_OPTION){
File file = image.getSelectedFile();
String filename = file.getName();
txtImage.setText(filename);
BufferedImage bi;
try {
bi = ImageIO.read(file);
Image attached;
attached = ScaledImage(bi, lblImage.getWidth(), lblImage.getHeight());
lblImage.setIcon(new ImageIcon(attached));
}catch(IOException e){
}
}
this.pack();
}//GEN-LAST:event_attachActionPerformed
private void paintTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_paintTypeActionPerformed
// TODO add your handling code here:
double length = Double.parseDouble(txtLength.getText());
double width = Double.parseDouble(txtWidth.getText());
double height = Double.parseDouble(txtHeight.getText());
JComboBox list = (JComboBox) evt.getSource();
String selection = (String) list.getSelectedItem();
double cost;
switch(selection){
case "Luxury":
cost = luxuryRate;
lblPaintTypeCost.setText("Luxury: £1.75 / sqm");
estimatedCost = (length * width) + (2 * length * height) + (2 * width * height) * cost;
lblCost.setText("Estimated cost: £" + estimatedCost);
break;
case "Standard":
cost = standardRate;
lblPaintTypeCost.setText("Standard: £1.00 / sqm");
estimatedCost = (length * width) + (2 * length * height) + (2 * width * height) * cost;
lblCost.setText("Estimated cost: £" + estimatedCost);
break;
case "economy":
cost = economyRate;
lblPaintTypeCost.setText("Economy: £0.45 / sqm");
estimatedCost = (length * width) + (2 * length * height) + (2 * width * height) * cost;
lblCost.setText("Estimated cost: £" + estimatedCost);
break;
}
txtLengthReport.setText("" + length);
txtWidthReport.setText("" + width);
txtHeightReport.setText("" + height);
paintTypeReport.setSelectedItem((String)selection);
}//GEN-LAST:event_paintTypeActionPerformed
private void calculateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_calculateActionPerformed
// TODO add your handling code here:
double length = Double.parseDouble(txtLength.getText());
double width = Double.parseDouble(txtWidth.getText());
double height = Double.parseDouble(txtHeight.getText());
double total = 0;
double undercoatCost = 0;
if(chkUndercoat.isSelected()){
undercoatCost = (length * width) + (2 * length * height) + (2 * height * width) * 0.50;
}else{
undercoatCost = 0;
}
total = estimatedCost + undercoatCost;
txtTotalReport.setText("£" + String.valueOf(total));
}//GEN-LAST:event_calculateActionPerformed
private Image ScaledImage(Image img, int w, int h){
BufferedImage resizedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedImage.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0, w, h, null);
g2.dispose();
return resizedImage;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton attach;
private javax.swing.JButton calculate;
private javax.swing.JCheckBox chkUndercoat;
private javax.swing.JCheckBox chkUndercoatReport;
private javax.swing.JCheckBox chkVerify;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel29;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel32;
private javax.swing.JLabel jLabel33;
private javax.swing.JLabel jLabel34;
private javax.swing.JLabel jLabel35;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JTabbedPane jTabbedPane5;
private javax.swing.JLabel lblCost;
private javax.swing.JLabel lblImage;
private javax.swing.JLabel lblPaintTypeCost;
private javax.swing.JLabel lblUndercoatCost;
private javax.swing.JComboBox<String> paintType;
private javax.swing.JComboBox<String> paintTypeReport;
private javax.swing.JButton print;
private javax.swing.JButton reset;
private javax.swing.JTextField txtAddress1;
private javax.swing.JTextField txtAddress2;
private javax.swing.JTextArea txtAddressReport;
private javax.swing.JTextField txtCountry;
private javax.swing.JTextField txtEmail;
private javax.swing.JTextField txtEmailReport;
private javax.swing.JTextField txtEmailVerified;
private javax.swing.JTextField txtHeight;
private javax.swing.JTextField txtHeight2;
private javax.swing.JTextField txtHeightReport;
private javax.swing.JTextField txtID;
private javax.swing.JTextField txtIDReport;
private javax.swing.JTextField txtIDVerified;
private javax.swing.JTextField txtImage;
private javax.swing.JTextField txtLength;
private javax.swing.JTextField txtLengthReport;
private javax.swing.JTextField txtName;
private javax.swing.JTextField txtNameReport;
private javax.swing.JTextField txtNameVerified;
private javax.swing.JTextField txtPhone;
private javax.swing.JTextField txtPhoneReport;
private javax.swing.JTextField txtPostCode;
private javax.swing.JTextField txtSurname;
private javax.swing.JTextField txtSurnameReport;
private javax.swing.JTextField txtSurnameVerified;
private javax.swing.JTextField txtTotalReport;
private javax.swing.JTextField txtWidth;
private javax.swing.JTextField txtWidthReport;
// End of variables declaration//GEN-END:variables
}
| 3f830d3c482127ab0dc7715004b4152b6369bfef | [
"Java"
] | 1 | Java | subhanmahmood/netbeansCh5 | 6d4cc59a50058ea118ebe2521756b3b03817ae97 | 8da2338b23d57a8a10e5a73ea75c8f1dd9a4203a |
refs/heads/master | <file_sep>// JS yay!
<file_sep># TicTacToe
My first try to make an easy tic tac toe game with JS
| df66221f1ca4fc10651c34876f29536822ac9309 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Esclaire/TicTacToe | a5f90a1420482a0a7d7d61b22726c2ab7e893cfe | 3a2e85dba0e57b8e56fb4015729daabd0ce05199 |
refs/heads/master | <repo_name>josh-privata/WaterChargeCalculator-School<file_sep>/WaterChargeCalculator.java
/**
*******************************************************************
* All code contained within is released under the GNU v3 license
*
* Please respect and support open source software and it's creators
*
* Project Name - Water Charge Calculator
* Project Purpose - To determine the total charge owed from a pre-
* determined number of clients. Total charge will be determined via
* a sliding rate scale according to usage amount.
*
*
* Initial Creation Date is Jul 24, 2013
* Written by <NAME>
*/
import java.text.DecimalFormat;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class WaterChargeCalculator {
// User Defined Variables
private int tier_max = 24; // Rate (in kL) at which tiers change
private double rate = 0.7; //Rate (as a decimal) at which water is charged per kL
final int N = 8; //Higest number in strudent number
// Do Not Edit Past This Line
public double charge;
public String name;
public int usage;
public double avg;
public double max;
public double tot;
String project = "Water Use Charge Caluclator";
Scanner input = new Scanner(System.in);
String results = "";
DecimalFormat d;
// Initialise Usage Constructor
public WaterChargeCalculator () {
usage = 0;
} // end usage constructor
// Start Method beginCharge
public void beginCharge( ) {
int count = 0;
d= new DecimalFormat("$# 00.00");
System.out.printf("\n\n**** Welcome to the %s ****\n\n", project);
while ( count < N) {
System.out.print("Enter Resident's Name Please : ");
name = input.nextLine();
System.out.printf("\nEnter %s's Usage Please : ", name);
usage = input.nextInt();
while (usage < 1 || usage > 200) {
System.out.print("Water usage is too low, Please enter an amount between 1 and 200\n");
System.out.printf("Enter %s's Usage Please : ", name);
usage = input.nextInt();
}
calculateCharge (usage);
System.out.printf("\nThe total charge for resident - %s is : %s\n\n-----------------------------------------------\n\n", name, d.format(charge));
if (charge > max){
max = charge;
}
tot = tot + charge;
avg = (tot / N);
results = results +""+name+" "+usage+"kL "+d.format(charge)+"\n";
input.nextLine();
count++;
}
}
// Start Method calculateCharge
public double calculateCharge (int u) {
if (u <= tier_max)
charge = usage*rate;
else if (u <=(2*tier_max))
charge= (24*rate)+(usage-24)*(rate*1.05);
else if (u <=(3*tier_max))
charge= (24*rate )+(25*(rate*1.05))+(usage-49)*(rate*1.10);
else
charge= (24*rate)+(25*(rate*1.05))+(25*(rate*1.10))+(usage-74)*(rate*1.15);
return charge;
} // end calculateCharge
// Start Method displayInfo
public void displayInfo() {
System.out.println(" Water Charge Calculator ");
System.out.println("===========================================");
System.out.println("Name Usage Charge ");
System.out.println("===========================================");
System.out.println(results+"\n");
String message = String.format("The total charge for all residents is: %s\nThe average charge for all users is: %s\nThe maximum charge is: %s\n", d.format(tot), d.format(avg), d.format(max));
System.out.printf("%s",message);
System.out.printf("\n\nThankyou for using the %s. \nPlease have a nice day, and remember...\nWe are in short supplies, Be water wise!!!", project);
JOptionPane.showMessageDialog(null,message);
} // end displayInfo
} //End Class WaterChargeCalculator
<file_sep>/README.md
<h1 align="center">
<a href="http://java.com/en"><img src="https://cloud.githubusercontent.com/assets/5771200/19331298/6f964780-9127-11e6-88bd-55ac19e1ad12.jpg" alt="Java" height="150"></a>
<br>
<br>
Water Charge Calculator
<br>
<br>
</h1>
<h4 align="center">A simple java program to calculate the charge of residents water usage</h4>
<p align="center">
<a href=""><img src="https://img.shields.io/travis/feross/standard/master.svg" alt="Passing"></a>
<a href="https://java.com/en/"><img src="https://img.shields.io/badge/Java-1.8.0__101-brightgreen.svg" alt="Java 1.8.0_101"></a>
<a href="https://opensource.org/licenses/BSD-2-Clause"><img src="https://img.shields.io/badge/License-BSD-blue.svg" alt="BSD License"></a>
</p>
<br>
## Table of Contents
- [Synopsis](#synopsis)
- [Install](#install)
- [Usage](#usage)
- [Screenshots](#screenshots)
- [License](#license)
## Synopsis
The problem put forward was to design a program that could calculate
a residents water usage based on a tier pricing schedule. It was required
that the user is asked for a residents name and water usage and upon
completion of the data entry, the user would be displayed a summary of
the information in tabular form along with the average, max and total of all
residents calculated charge.
The program was required to use the given classes of WaterChargeCalculator
and WaterChargeCalculatorTest. Modules beginCharge, calculateCharge and
displayInfo were to be used in the final code.
## Install
First, make a directory to install the files to and change to that directory using :
```bash
mkdir watercharge && cd watercharge
```
Then all you need to do is clone the project from github into the directory by using :
```bash
git clone https://github.com/josh-privata/WaterChargeCalculator.git
```
## Usage
##### Note: [Java Runtime](https://java.com/en/download/) is required to run the preceding commands.
Initially the program needs to be compiled. After you have copied the *.java files to a directory, run the command :
```bash
$ javac *.java
```
Then run the program using the command :
```bash
$ java WaterChargeCalculatorTest
```
## Screenshots
<p align="center"><img src="https://cloud.githubusercontent.com/assets/5771200/19331299/738f1c90-9127-11e6-8d85-67b474ded730.jpg" width="75%" alt="Screenshot"></p>
## License
[BSD](LICENSE) Copyright (c) 2016 [<NAME>](http://joshcannons.com).
<file_sep>/WaterChargeCalculatorTest.java
/**
*******************************************************************
* All code contained within is released under the GNU v3 license
*
* Please respect and support open source software and it's creators
*
* Project Name - Water Charge Calculator
* Project Purpose - To determine the total charge owed from a pre-
* determined number of clients. Total charge will be determined via
* a sliding rate scale according to usage amount.
*
*
* Initial Creation Date is Jul 24, 2013
* Written by <NAME>
*/
//WaterChargeCalculator Main Class
public class WaterChargeCalculatorTest
{
//Method main creates WaterChargeCalculator object, calls beginCharge and displayInfo
public static void main (String[] args) {
WaterChargeCalculator app;
app = new WaterChargeCalculator();
app.beginCharge();
app.displayInfo();
}//End method main
}//End WaterChargeCalculatorTest | 59198a806cdbed1dc55561dbd8274a165e67e306 | [
"Markdown",
"Java"
] | 3 | Java | josh-privata/WaterChargeCalculator-School | a6090e4b450e94a4315615011254e0d8522fdefc | 6189b6a7d9dfc393e7e931c71935e60ee03fc589 |
refs/heads/master | <file_sep>const { luhn_validate, info_card } = require('./index');
(async function () {
// Tarjeta incorrecta
let data1 = await info_card(1234567890);
console.log(data1);
// tarjeta correcta
let data2 = await info_card(4152311235);
console.log(data2);
})();
<file_sep># Util credit/debit cards
## Features
- Validation number card (algorithm Luhn) | 472b065821726ba652863b2c40579271d40c48e4 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | linaresbda/util-credit-cards | 053021de9803d6c916fcd9f2da09ce03cdfb00ba | 8a6a23611d744925991bd863eea6f32b207220a2 |
refs/heads/main | <file_sep>const $levels = { "easy": 3, "medium": 4, "hard": 5 };
const $imgsTheme = { "default": "../img/buracoNuvem.gif", "active": "../img/nuvem.gif", "dead": "../img/deadNuvem.gif" }
const $imgWidth = 100; // largura da toupeira
const $imgHeight = 80; //altura da toupeira
const $initialTime = 10; //temp de jogabilidade independente da fase
var $timeGame = $initialTime;
var $idChronoGame; //ira controlar o setInterval do cronometro
var $idChronoStartGame; //ira controlar o setInterval do cronometro do jogo
var userId = sessionStorage.getItem("id");
console.log("Passado pela sessionStorage: " + sessionStorage.getItem("id"))
var tabela_rank = ""
$(document).ready(function () {
fillBoard();
$("#chrono").text($initialTime);
$("#btnPlay").click(function () {
btnCtrl();
$idChronoStartGame = setInterval(startGame, 3000);
$idChronoGame = setInterval(startChronoGame, 1000);
});
$("#btnPause").click(function () { pauseGame() });
$("#btnStop").click(function () { endGame() });
$("#btnExit").click(function () { window.open("login.html", "_self") });
});
function startChronoGame() {
($timeGame > 0) ? $("#chrono").text(--$timeGame) : andGame();
}
function andGame() {
clearInterval($idChronoGame);
clearInterval($idChronoStartGame);
//alert(`Fim de jogo. Sua pontuaçao foi = ${("#score").text()}`)
alertWifi(`Fim de Jogo. Sua pontuação foi = ${$("#score").text()}\n<table id='tab-rank'></table>`, false, 0, `img/${$imgsTheme.active}`, "50");
readUsers();
fillBoard();
$("#score").text("0");
$timeGame = $initialTime;
$("#chrono").text($timeGame);
}
function pauseGame() {
clearInterval($chronoGame);
clearInterval($chronoTime);
fillBoard();
$("#btnPlay").prop("disabled", false);
$("#btnPause").prop("disabled", true);
}
function btnCtrl() {
$("btnPause").prop("disabled", false); //Habilita
$("btnStop").prop("disabled", false); //Habilita
$("btnPlay").prop("disabled", true); //desabilita
}
//Cria a moldura do tabuleiro conforme o nível de dificuldade
function fillBoard() {
$level = getLevel();
$boardWidth = $imgWidth * $level;
$boardHeight = $imgHeight * $level;
$("#board").css({ "width": $boardWidth, "height": $boardHeight });
placeHolesBoard($level);
}
//insere os buracos das toupeiras no tabuleiro
function placeHolesBoard($level) {
$("#board").empty();
for ($i = 0; $i < Math.pow($level, 2); $i++) {
$div = $("<div></div>");//attr("id",`mole_${$i+1}`);
$img = $("<img>").attr({ "src": `img/${$imgsTheme.default}`, "id": `mole_${$i + 1}` });
$($img).click(function () { updateScore(this) });//alert($(this).attr("id"))
$($div).append($img);
$("#board").append($div);
}
}
// Atualiza a pontuaco ao clicar sobre a toupeira
function updateScore($img) {
if ($($img).attr("src").search($imgsTheme.active)!= -1) {
$("#score").text((String(parseInt($("#score").text())+1)));
$($img).attr("src",`img/${$imgsTheme.dead}`);
}
}
function startGame() {
fillBoard(); // Melhorar: trocar apenas a toupeira do tabuleiro pelo buraco ao inves de limpar todo o tabuleiro
$level = getLevel();
$randNumber = getRanNumber(1, Math.pow($level, 2));
$(`#mole_${$randNumber}`).attr({ "src": `img/${$imgsTheme.active}` });
setTimeout(() => { //implementado
$(`#mole_${$randNumber}`).attr("src", `img/${$imgsTheme.default}`)
}, 1000);
}
// Gera um numero aleatorio entre "min" e "max"
function getRanNumber(min, max) {
return Math.round((Math.random() * Math.abs(max - min)) + min);
}
function getLevel() {
return $levels[$("#level").val()]
}
// CHAMA O RANKING E MOSTRA SUA PONTUAÇAO
function readUsers() {
const dados = {
"usuario": {
"id": userId
},
"pontuacao": $("#score").text(),
"nivel": $("#level").val()
} //salva pontuação
console.log(dados)
const url = "http://localhost:8080/ranking";
axios.post(url, dados)
.then(() => axios.get(url + `/${$("#level").val()}`))
.then(
(rank) =>
rank.data.forEach(registro => {
//console.log(registro),
tabela_rank = tabela_rank +
`<tr>
<td>${registro.usuario.user}</td>
<td>${registro.pontuacao}</td>
</tr>`
document.getElementById("tab-rank").innerHTML = tabela_rank
}) //imprime pontuacao e mostra para o usuario.
)
.catch(err => console.log(err));
}
<file_sep>$(document).ready(function () {
//TELA LOGIN
$("#btnLogin").click(function () {
const $user = $("#user").val();
const $pwd = $("#pwd").val();
if ($user && $pwd) {
$.getJSON("http://localhost:8080/usuarios",
function ($registros) {
//console.log($registros)
//console.log($registros.filter($usuario => $usuario.user == $user && $usuario.pwd == $pwd))
var usr = $registros.find($usuario => $usuario.user == $user && $usuario.pwd == $pwd);
//if ($registros.filter($usuario => $usuario.user == $user && $usuario.pwd == $pwd).length > 0)
if (usr) {
sessionStorage.setItem("id", usr.id);
window.open(`index.html?id_usuario=${usr.id}`, "_self")
} else alert("Usuário Inválido");
});
} else {
alert("Erro: favor informar usuário e senha")
}
})
//TELA CADASTRO
$("#btnCadastro").click(function () {
let $user = $("#user").val();
let $pwd = $("#pwd").val();
let data = { "user": $user, "pwd": <PASSWORD> };
if ($user && $pwd) {
console.log('enviando requisição: ' + JSON.stringify(data))
const url = "http://localhost:8080/usuarios";
axios.post(url, data).then(() => window.location.href = 'login.html');
} else {
alert("Erro: favor informar usuário e senha")
}
})
});<file_sep>const $level = {"easy":3, "medium":5, "hard":7}
const $imgWidth = 100; //largura
const $imgHeight = 80; //altura
$(document).ready(function() {
fillBoard();
$("#btnPlay").click(function(){
startGame();
});
});
function fillBoard(){
$level = $levels[$("#level").val()];
$boardWidth = $imgWidth * $level;
$boardHeight = $imgHeight * $level;
$("#board").css({"width":$boardWidth,"height:":$boardHeight});
placeHolesBoard($level);
}
function placeHolesBoard($level){
$("#board").empty();
for($i=0; s$<Math.pow($level,2); $i++){
$div = $("<div></div>");//.attr("id",`mole_${$i+1}`);
$img = $("<img>").attr({"src":"img/buraco.gif","id":`mole_${$i+1}`});
$($div).append($img);
$("#board").append($div);
}
}
function startGame(){
$level = $getLevel();
$randNumber = getRandomNumber(1,Math.pow($level,2));
$(`#mole_${$randNumber}`).attr("src","img/toupeira.gif")
}
function getRandomNumber(min, max){
return Math.random((Math.random()* Math.abs(max - min)) + min);
}
function getLevel(){
$level = $levels[$("#level").val()];
}<file_sep>function loadCustomers() {
let xhttp = new XMLHttpRequest();
let file = "LISTA02\json\clientes.json";
xhttp.onreadystatechange = function () {
if ((xhttp.readyState == 4) && (xhttp.status == 200)) {
printCustomers(xhttp.responseText, idtable);
}
}
xhttp.open("GET", file, true);
xhttp.send();
}
function printCustomers(clientes) {
let table = document.getElementById(idtable);
let trCliente = document.createElement("tr");
let tdNome = document.createElement("td");
let tdIdade = document.createElement("td");
let tdSexo = document.createElement("td");
clientes = JSON.parse(clientes);
nome = document.createTextNode(clientes.nome);
idade = document.createTextNode(clientes.idade);
sexo = document.createTextNode(clientes.sexo)
tdNome.appendChild(nome);
tdIdade.appendChild(idade);
tdSexo.appendChild(sexo);
trCliente.appendChild(tdNome);
trCliente.appendChild(tdIdade);
trCliente.appendChild(tdSexo);
table.appendChild(trCliente);
}
function loadFeminino(){
if(tdSexo == "F"){
let table = document.getElementById(idtable);
let trCliente = document.createElement("tr");
let tdNome = document.createElement("td");
let tdIdade = document.createElement("td");
clientes = JSON.parse(clientes);
nome = document.createTextNode(clientes.nome);
idade = document.createTextNode(clientes.idade);
tdNome.appendChild(nome);
tdIdade.appendChild(idade);
trCliente.appendChild(tdNome);
trCliente.appendChild(tdIdade);
table.appendChild(trCliente);
}
}
function loadMasculino(){
if(tdSexo == "M"){
let table = document.getElementById(idtable);
let trCliente = document.createElement("tr");
let tdNome = document.createElement("td");
let tdIdade = document.createElement("td");
clientes = JSON.parse(clientes);
nome = document.createTextNode(clientes.nome);
idade = document.createTextNode(clientes.idade);
tdNome.appendChild(nome);
tdIdade.appendChild(idade);
trCliente.appendChild(tdNome);
trCliente.appendChild(tdIdade);
table.appendChild(trCliente);
}
} | 3c2be1b51e810d63875503ef506aa4e2ebd29ce7 | [
"JavaScript"
] | 4 | JavaScript | acNataliaFreitas/jogoNuvemTeste | 2988d15b151008ecfb90ef8b18550491b77d6712 | 56744366c0bef8645edaa36a3bd936aceca26e0c |
refs/heads/master | <repo_name>MubsCompany/RecyclerView3Mubs<file_sep>/app/src/main/java/com/example/recyclerview3mubs/MainActivity.java
package com.example.recyclerview3mubs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.example.recyclerview3mubs.fragment.FirstFragment;
import com.example.recyclerview3mubs.fragment.SecondFragment;
import com.example.recyclerview3mubs.fragment.ThirdFragment;
public class MainActivity extends AppCompatActivity {
FragmentManager fm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
fm = getSupportFragmentManager();
fm.beginTransaction().add( R.id.kontener,new FirstFragment() ).commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate( R.menu.menu,menu );
return super.onCreateOptionsMenu( menu );
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Fragment destinationFragment = null;
fm = getSupportFragmentManager();
switch (item.getItemId()) {
case R.id.mn_satu :
destinationFragment = new FirstFragment();
break;
case R.id.mn_dua :
destinationFragment = new SecondFragment();
break;
case R.id.mn_tiga :
destinationFragment = new ThirdFragment();
break;
}
assert destinationFragment != null;
fm.beginTransaction().replace( R.id.kontener,destinationFragment ).addToBackStack( "any" ).commit();
return super.onOptionsItemSelected( item );
}
}
<file_sep>/app/src/main/java/com/example/recyclerview3mubs/fragment/SecondFragment.java
package com.example.recyclerview3mubs.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.recyclerview3mubs.R;
/**
* A simple {@link Fragment} subclass.
*/
public class SecondFragment extends Fragment {
RecyclerView rvSecond;
SecondAdapter adapterdua;
FragmentManager fm;
String[] arrayNamadua = {"Air Conditioner","Bulb Light","Screen","Curtains","CCTV","Melody","Projector","Tribune"};
int[] arrayGambardua = {R.drawable.ac,R.drawable.bulb,R.drawable.screen,R.drawable.curtains,R.drawable.cctv,R.drawable.melodhy,R.drawable.projector,R.drawable.tribune};
public SecondFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate( R.layout.fragment_second, container, false );
adapterdua = new SecondAdapter();
rvSecond = v.findViewById( R.id.secondlist );
rvSecond.setAdapter( adapterdua );
rvSecond.setLayoutManager( new GridLayoutManager( getActivity(),2 ) );
return v;
}
private class SecondAdapter extends RecyclerView.Adapter<MyViewHolder> implements View.OnClickListener {
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
return new MyViewHolder( LayoutInflater.from( viewGroup.getContext() ).inflate( R.layout.adptr_dua,viewGroup,false ) );
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.txt_namadua.setText( arrayNamadua[i] );
myViewHolder.img_gambardua.setImageResource( arrayGambardua[i] );
myViewHolder.itemView.setOnClickListener( this );
}
@Override
public int getItemCount() {
return arrayNamadua.length;
}
@Override
public void onClick(View v) {
}
}
private class MyViewHolder extends RecyclerView.ViewHolder {
TextView txt_namadua;
ImageView img_gambardua;
public MyViewHolder(@NonNull View itemView) {
super( itemView );
txt_namadua = itemView.findViewById( R.id.tvNamaSecond );
img_gambardua = itemView.findViewById( R.id.imgGambarSecond );
}
}
}
| 9f5a6125e9fbae46f8e73853fc798a3ac8bb2225 | [
"Java"
] | 2 | Java | MubsCompany/RecyclerView3Mubs | f6eb172fa3bfa8d578a66f520d1eea2aa838127f | 67945711d072a4c3986d63ab46adb46f0eca0758 |
refs/heads/main | <repo_name>ttanzhiqiang/onnx-tensorrt_7.2.1<file_sep>/trt_utils.hpp
/*
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "Status.hpp"
#include "TensorOrWeights.hpp"
#include "onnx2trt.hpp"
#include <NvInfer.h>
#include <algorithm>
#include <cassert>
#include <cmath>
namespace onnx2trt
{
inline int getDtypeSize(nvinfer1::DataType trtDtype)
{
switch (trtDtype)
{
case nvinfer1::DataType::kFLOAT: return 4;
case nvinfer1::DataType::kINT8: return 1;
case nvinfer1::DataType::kHALF: return 2;
case nvinfer1::DataType::kINT32:
return 4;
// TRT does not support booleans as a native type, so we treat them like int32 values.
case nvinfer1::DataType::kBOOL:
return 4;
// TODO: Some sort of error handling
default: return -1;
}
}
inline nvinfer1::Dims insert_dim(nvinfer1::Dims const& dims, int idx, int value)
{
assert(idx < dims.nbDims + 1);
nvinfer1::Dims new_dims;
new_dims.nbDims = dims.nbDims + 1;
for (int i = 0; i < idx; ++i)
{
new_dims.d[i] = dims.d[i];
}
new_dims.d[idx] = value;
for (int i = idx + 1; i < new_dims.nbDims; ++i)
{
new_dims.d[i] = dims.d[i - 1];
}
return new_dims;
}
inline nvinfer1::Dims remove_dim(nvinfer1::Dims const& dims, int idx)
{
assert(idx < dims.nbDims);
nvinfer1::Dims new_dims;
new_dims.nbDims = dims.nbDims - 1;
for (int i = 0; i < idx; ++i)
{
new_dims.d[i] = dims.d[i];
}
for (int i = idx; i < new_dims.nbDims; ++i)
{
new_dims.d[i] = dims.d[i + 1];
}
// Special case for scalar result (i.e., there was only one dim originally)
if (new_dims.nbDims == 0)
{
new_dims.nbDims = 1;
new_dims.d[0] = 1;
}
return new_dims;
}
// Adds unitary dimensions on the left
inline nvinfer1::Dims expand_dims(nvinfer1::Dims const& dims, int ndim_new)
{
assert(dims.nbDims <= ndim_new);
nvinfer1::Dims new_dims;
new_dims.nbDims = ndim_new;
int j = 0;
for (; j < ndim_new - dims.nbDims; ++j)
{
new_dims.d[j] = 1;
}
for (int i = 0; i < dims.nbDims; ++i, ++j)
{
new_dims.d[j] = dims.d[i];
}
return new_dims;
}
inline nvinfer1::Permutation remove_first_dim(nvinfer1::Permutation const& perm)
{
assert(perm.order[0] == 0);
nvinfer1::Permutation new_perm;
int ndim = nvinfer1::Dims::MAX_DIMS;
for (int i = 0; i < ndim - 1; ++i)
{
new_perm.order[i] = perm.order[i + 1] - 1;
}
return new_perm;
}
inline nvinfer1::Dims squeeze_trailing_dims(nvinfer1::Dims const& dims)
{
nvinfer1::Dims new_dims = dims;
// Note: TRT requires at least one dimension, so we don't squeeze [1]->[]
while (new_dims.nbDims > 1 && new_dims.d[new_dims.nbDims - 1] == 1)
{
--new_dims.nbDims;
}
return new_dims;
}
inline nvinfer1::Dims squeeze_leading_dims(const nvinfer1::Dims& dims)
{
nvinfer1::Dims newDims;
// Copy dims only if a non-1 has been seen already.
bool non1Seen{false};
newDims.nbDims = std::copy_if(dims.d, dims.d + dims.nbDims, newDims.d,
[&non1Seen](int x) {
non1Seen = (x != 1) ? true : non1Seen;
return non1Seen;
})
- newDims.d;
return newDims;
}
inline nvinfer1::DimsHW operator-(nvinfer1::DimsHW dims)
{
return nvinfer1::DimsHW(-dims.h(), -dims.w());
}
// Note: These are used for checking beg_padding == end_padding
inline bool operator==(nvinfer1::Dims const& a, nvinfer1::Dims const& b)
{
if (a.nbDims != b.nbDims)
{
return false;
}
for (int i = 0; i < a.nbDims; ++i)
{
if (a.d[i] != b.d[i])
{
return false;
}
}
return true;
}
inline bool operator!=(nvinfer1::Dims const& a, nvinfer1::Dims const& b)
{
return !(a == b);
}
inline TensorOrWeights identity(IImporterContext* ctx, TensorOrWeights input)
{
if (input.is_weights())
{
return input;
}
else
{
auto* layer = ctx->network()->addIdentity(input.tensor());
if (!layer)
{
return nullptr;
}
return layer->getOutput(0);
}
}
inline ::ONNX_NAMESPACE::TensorProto_DataType trtDataTypeToONNX(nvinfer1::DataType dt)
{
switch (dt)
{
case nvinfer1::DataType::kFLOAT: return ::ONNX_NAMESPACE::TensorProto::FLOAT;
case nvinfer1::DataType::kHALF: return ::ONNX_NAMESPACE::TensorProto::FLOAT16;
case nvinfer1::DataType::kINT32: return ::ONNX_NAMESPACE::TensorProto::INT32;
case nvinfer1::DataType::kINT8: return ::ONNX_NAMESPACE::TensorProto::INT8;
case nvinfer1::DataType::kBOOL: return ::ONNX_NAMESPACE::TensorProto::BOOL;
default: return ::ONNX_NAMESPACE::TensorProto_DataType_UNDEFINED;
}
throw std::runtime_error{"Unreachable"};
}
} // namespace onnx2trt
<file_sep>/ImporterContext.hpp
/*
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "onnx2trt.hpp"
#include "onnx2trt_utils.hpp"
#include <list>
#include <unordered_map>
namespace onnx2trt
{
class ImporterContext final : public IImporterContext
{
nvinfer1::INetworkDefinition* _network;
nvinfer1::ILogger* _logger;
std::list<std::vector<uint8_t>> _temp_bufs;
StringMap<nvinfer1::ITensor*> _user_inputs;
StringMap<nvinfer1::ITensor**> _user_outputs;
StringMap<int64_t> _opsets;
StringMap<TensorOrWeights> mTensors; // All tensors in the graph mapped to their names.
StringMap<nvinfer1::TensorLocation> mTensorLocations;
StringMap<float> mTensorRangeMins;
StringMap<float> mTensorRangeMaxes;
StringMap<nvinfer1::DataType> mLayerPrecisions;
std::set<std::string> mTensorNames; // Keep track of how many times a tensor name shows up, to avoid duplicate naming in TRT.
std::set<std::string> mLayerNames; // Keep track of how many times a tensor name shows up, to avoid duplicate naming in TRT.
int64_t mSuffixCounter = 0; // increasing suffix counter used to uniquify layer names.
std::unordered_set<std::string> mUnsupportedShapeTensors; // Container to hold output tensor names of layers that produce shape tensor outputs but do not natively support them.
StringMap<std::string> mLoopTensors; // Container to map subgraph tensors to their original outer graph names.
std::string mOnnxFileLocation; // Keep track of the directory of the parsed ONNX file
std::list<std::string> mInitializerNames; // Keep track of unique names of any initializers
RefitMap_t* mRefitMap; // Keep track of names of ONNX refittable weights with their corresponding TRT layer and role
public:
ImporterContext(nvinfer1::INetworkDefinition* network, nvinfer1::ILogger* logger, RefitMap_t* refitMap)
: _network(network)
, _logger(logger)
, mRefitMap(refitMap)
{
}
virtual nvinfer1::INetworkDefinition* network() override
{
return _network;
}
virtual StringMap<TensorOrWeights>& tensors() override
{
return mTensors;
}
virtual StringMap<nvinfer1::TensorLocation>& tensorLocations() override
{
return mTensorLocations;
}
virtual StringMap<float>& tensorRangeMins() override
{
return mTensorRangeMins;
}
virtual StringMap<float>& tensorRangeMaxes() override
{
return mTensorRangeMaxes;
}
virtual StringMap<nvinfer1::DataType>& layerPrecisions() override
{
return mLayerPrecisions;
}
virtual std::unordered_set<std::string>& unsupportedShapeTensors() override
{
return mUnsupportedShapeTensors;
}
virtual StringMap<std::string>& loopTensors() override
{
return mLoopTensors;
}
virtual void setOnnxFileLocation(std::string location) override
{
mOnnxFileLocation = location;
}
virtual std::string getOnnxFileLocation() override
{
return mOnnxFileLocation;
}
virtual void insertRefitMap(std::string weightsName, std::string layerName, nvinfer1::WeightsRole role) override
{
(*mRefitMap)[weightsName] = WeightsPair_t{layerName, role};
}
// This actually handles weights as well, but is named this way to be consistent with the tensors()
virtual void registerTensor(TensorOrWeights tensor, const std::string& basename) override
{
// TRT requires unique tensor names.
const std::string uniqueName = generateUniqueName(mTensorNames, basename);
if (tensor)
{
auto* ctx = this; // To enable logging.
if (tensor.is_tensor())
{
tensor.tensor().setName(uniqueName.c_str());
LOG_VERBOSE("Registering tensor: " << uniqueName << " for ONNX tensor: " << basename);
}
else if (tensor.is_weights())
{
mInitializerNames.push_back(uniqueName);
const auto& weights = tensor.weights();
if (tensor.weights().type == ::ONNX_NAMESPACE::TensorProto::INT64)
{
tensor = ShapedWeights{::ONNX_NAMESPACE::TensorProto::INT32,
convertINT64(reinterpret_cast<int64_t*>(weights.values), weights.shape, ctx), weights.shape};
}
tensor.weights().setName(mInitializerNames.back().c_str());
}
}
// Overwrite previous tensors registered with the same name (this only happens when there are subgraphs,
// and in that case, overwriting is the desired behavior).
this->tensors()[basename] = std::move(tensor);
}
virtual void registerLayer(nvinfer1::ILayer* layer, const std::string& basename) override
{
// No layer will be added for Constant nodes in ONNX.
if (layer)
{
const std::string name = basename.empty() ? layer->getName() : basename;
const std::string uniqueName = generateUniqueName(mLayerNames, name);
auto* ctx = this; // To enable logging.
if (layer->getType() == nvinfer1::LayerType::kCONSTANT)
{
LOG_VERBOSE("Registering constant layer: " << uniqueName << " for ONNX initializer: " << basename);
}
else
{
LOG_VERBOSE("Registering layer: " << uniqueName << " for ONNX node: " << basename);
}
layer->setName(uniqueName.c_str());
}
}
virtual nvinfer1::ILogger& logger() override
{
return *_logger;
}
virtual ShapedWeights createTempWeights(ShapedWeights::DataType type, nvinfer1::Dims shape) override
{
ShapedWeights weights(type, nullptr, shape);
// Need special logic for handling scalars.
if (shape.nbDims == 0)
{
_temp_bufs.push_back(std::vector<uint8_t>(getDtypeSize(type)));
}
else
{
_temp_bufs.push_back(std::vector<uint8_t>(weights.size_bytes()));
}
weights.values = _temp_bufs.back().data();
return weights;
}
bool setUserInput(const char* name, nvinfer1::ITensor* input)
{
_user_inputs[name] = input;
return true;
}
bool setUserOutput(const char* name, nvinfer1::ITensor** output)
{
_user_outputs[name] = output;
return true;
}
nvinfer1::ITensor* getUserInput(const char* name)
{
if (!_user_inputs.count(name))
{
return nullptr;
}
else
{
return _user_inputs.at(name);
}
}
nvinfer1::ITensor** getUserOutput(const char* name)
{
if (!_user_outputs.count(name))
{
return nullptr;
}
else
{
return _user_outputs.at(name);
}
}
StringMap<nvinfer1::ITensor**> const& getUserOutputs() const
{
return _user_outputs;
}
void clearOpsets()
{
_opsets.clear();
}
void addOpset(std::string domain, int64_t version)
{
_opsets.emplace(domain, version);
}
virtual int64_t getOpsetVersion(const char* domain = "") const override
{
if (_opsets.empty())
{
return 1;
}
else if (_opsets.size() == 1)
{
return _opsets.begin()->second;
}
else
{
assert(_opsets.count(domain));
return _opsets.at(domain);
}
}
private:
std::string generateUniqueName(std::set<std::string>& namesSet, const std::string& basename)
{
std::string candidate = basename;
while (namesSet.find(candidate) != namesSet.end())
{
candidate = basename + "_" + std::to_string(mSuffixCounter);
++mSuffixCounter;
}
namesSet.insert(candidate);
return candidate;
}
};
} // namespace onnx2trt
<file_sep>/main.cpp
/*
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "NvOnnxParser.h"
#include "onnx_utils.hpp"
#include "common.hpp"
#include <onnx/optimizer/optimize.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <fstream>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
#include "win_getopt.h" // For ::getopt on windows
#else
#include <unistd.h> // For ::getopt on linux
#endif
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <ctime>
#include <fcntl.h> // For ::open
#include <limits>
void print_usage() {
cout << "ONNX to TensorRT model parser" << endl;
cout << "Usage: onnx2trt onnx_model.pb" << "\n"
<< " [-o engine_file.trt] (output TensorRT engine)" << "\n"
<< " [-t onnx_model.pbtxt] (output ONNX text file without weights)" << "\n"
<< " [-T onnx_model.pbtxt] (output ONNX text file with weights)" << "\n"
<< " [-m onnx_model_out.pb] (output ONNX model)" << "\n"
<< " [-b max_batch_size (default 32)]" << "\n"
<< " [-w max_workspace_size_bytes (default 1 GiB)]" << "\n"
<< " [-d model_data_type_bit_depth] (32 => float32, 16 => float16)" << "\n"
<< " [-O passes] (optimize onnx model. Argument is a semicolon-separated list of passes)" << "\n"
<< " [-p] (list available optimization passes and exit)" << "\n"
<< " [-l] (list layers and their shapes)" << "\n"
<< " [-g] (debug mode)" << "\n"
<< " [-F] (optimize onnx model in fixed mode)" << "\n"
<< " [-v] (increase verbosity)" << "\n"
<< " [-q] (decrease verbosity)" << "\n"
<< " [-V] (show version information)" << "\n"
<< " [-h] (show help)" << endl;
}
int main(int argc, char* argv[]) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
std::string engine_filename;
std::string model_filename;
std::string text_filename;
std::string optimization_passes_string;
std::string full_text_filename;
size_t max_batch_size = 32;
size_t max_workspace_size = 1 << 30;
int model_dtype_nbits = 32;
int verbosity = (int)nvinfer1::ILogger::Severity::kWARNING;
bool optimize_model = false;
bool optimize_model_fixed = false;
bool print_optimization_passes_info = false;
bool print_layer_info = false;
bool debug_builder = false;
int arg = 0;
while( (arg = ::getopt(argc, argv, "o:b:w:t:T:m:d:O:plgFvqVh")) != -1 ) {
switch (arg){
case 'o':
if( optarg ) { engine_filename = optarg; break; }
else { cerr << "ERROR: -o flag requires argument" << endl; return -1; }
case 'm':
if( optarg ) { model_filename = optarg; break; }
else { cerr << "ERROR: -m flag requires argument" << endl; return -1; }
case 't':
if( optarg ) { text_filename = optarg; break; }
else { cerr << "ERROR: -t flag requires argument" << endl; return -1; }
case 'T':
if( optarg ) { full_text_filename = optarg; break; }
else { cerr << "ERROR: -T flag requires argument" << endl; return -1; }
case 'b':
if( optarg ) { max_batch_size = atoll(optarg); break; }
else { cerr << "ERROR: -b flag requires argument" << endl; return -1; }
case 'w':
if( optarg ) { max_workspace_size = atoll(optarg); break; }
else { cerr << "ERROR: -w flag requires argument" << endl; return -1; }
case 'd':
if( optarg ) { model_dtype_nbits = atoi(optarg); break; }
else { cerr << "ERROR: -d flag requires argument" << endl; return -1; }
case 'O':
optimize_model = true;
if( optarg ) { optimization_passes_string = optarg; break; }
else { cerr << "ERROR: -O flag requires argument" << endl; return -1; }
case 'p': print_optimization_passes_info = true; break;
case 'l': print_layer_info = true; break;
case 'g': debug_builder = true; break;
case 'F': optimize_model_fixed = true; optimize_model = true; break;
case 'v': ++verbosity; break;
case 'q': --verbosity; break;
case 'V': common::print_version(); return 0;
case 'h': print_usage(); return 0;
}
}
std::vector<std::string> optimizationPassNames;
if(optimize_model || print_optimization_passes_info) {
optimizationPassNames = ::ONNX_NAMESPACE::optimization::GetAvailablePasses();
}
if(print_optimization_passes_info) {
cout << "Available optimization passes are:" << endl;
for( auto it = optimizationPassNames.begin(); it != optimizationPassNames.end(); it++ )
{
cout << " " << it->c_str() << endl;
}
return 0;
}
int num_args = argc - optind;
if( num_args != 1 ) {
print_usage();
return -1;
}
std::string onnx_filename = argv[optind];
nvinfer1::DataType model_dtype;
if( model_dtype_nbits == 32 ) { model_dtype = nvinfer1::DataType::kFLOAT; }
else if( model_dtype_nbits == 16 ) { model_dtype = nvinfer1::DataType::kHALF; }
//else if( model_dtype_nbits == 8 ) { model_dtype = nvinfer1::DataType::kINT8; }
else {
cerr << "ERROR: Invalid model data type bit depth: " << model_dtype_nbits << endl;
return -2;
}
if (!std::ifstream(onnx_filename.c_str())) {
cerr << "Input file not found: " << onnx_filename << endl;
return -3;
}
::ONNX_NAMESPACE::ModelProto _the_onnx_model;
::ONNX_NAMESPACE::ModelProto& onnx_model = _the_onnx_model;
bool is_binary = common::ParseFromFile_WAR(&onnx_model, onnx_filename.c_str());
if( !is_binary && !common::ParseFromTextFile(&onnx_model, onnx_filename.c_str()) ) {
cerr << "Failed to parse ONNX model" << endl;
return -3;
}
if( verbosity >= (int)nvinfer1::ILogger::Severity::kWARNING ) {
int64_t opset_version = (onnx_model.opset_import().size() ?
onnx_model.opset_import(0).version() : 0);
cout << "----------------------------------------------------------------" << endl;
cout << "Input filename: " << onnx_filename << endl;
cout << "ONNX IR version: " << common::onnx_ir_version_string(onnx_model.ir_version()) << endl;
cout << "Opset version: " << opset_version << endl;
cout << "Producer name: " << onnx_model.producer_name() << endl;
cout << "Producer version: " << onnx_model.producer_version() << endl;
cout << "Domain: " << onnx_model.domain() << endl;
cout << "Model version: " << onnx_model.model_version() << endl;
cout << "Doc string: " << onnx_model.doc_string() << endl;
cout << "----------------------------------------------------------------" << endl;
}
if( onnx_model.ir_version() > ::ONNX_NAMESPACE::IR_VERSION ) {
cerr << "WARNING: ONNX model has a newer ir_version ("
<< common::onnx_ir_version_string(onnx_model.ir_version())
<< ") than this parser was built against ("
<< common::onnx_ir_version_string(::ONNX_NAMESPACE::IR_VERSION) << ")." << endl;
}
if( !model_filename.empty() ) {
if( optimize_model ) {
std::vector<std::string> passes;
std::string curPass;
std::stringstream passStream(optimization_passes_string);
while( std::getline(passStream, curPass, ';') ) {
if( std::find(optimizationPassNames.begin(), optimizationPassNames.end(), curPass) != optimizationPassNames.end() ) {
passes.push_back(curPass);
}
}
if( !passes.empty() ) {
cout << "Optimizing '" << model_filename << "'" << endl;
::ONNX_NAMESPACE::ModelProto _the_onnx_model_optimized = optimize_model_fixed
? ::ONNX_NAMESPACE::optimization::OptimizeFixed(onnx_model, passes)
: ::ONNX_NAMESPACE::optimization::Optimize(onnx_model, passes);
onnx_model = _the_onnx_model_optimized;
}
}
if( !common::MessageToFile( &onnx_model, model_filename.c_str() ) ) {
cerr << "ERROR: Problem writing ONNX model" << endl;
}
}
if( !text_filename.empty() ) {
if( verbosity >= (int)nvinfer1::ILogger::Severity::kWARNING ) {
cout << "Writing ONNX model (without weights) as text to " << text_filename << endl;
}
std::ofstream onnx_text_file(text_filename.c_str());
std::string onnx_text = pretty_print_onnx_to_string(onnx_model);
onnx_text_file.write(onnx_text.c_str(), onnx_text.size());
}
if( !full_text_filename.empty() ) {
if( verbosity >= (int)nvinfer1::ILogger::Severity::kWARNING ) {
cout << "Writing ONNX model (with weights) as text to " << full_text_filename << endl;
}
std::string full_onnx_text;
google::protobuf::TextFormat::PrintToString(onnx_model, &full_onnx_text);
std::ofstream full_onnx_text_file(full_text_filename.c_str());
full_onnx_text_file.write(full_onnx_text.c_str(), full_onnx_text.size());
}
const auto explicitBatch = 1U << static_cast<uint32_t>(nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH);
common::TRT_Logger trt_logger((nvinfer1::ILogger::Severity)verbosity);
auto trt_builder = common::infer_object(nvinfer1::createInferBuilder(trt_logger));
auto trt_network = common::infer_object(trt_builder->createNetworkV2(explicitBatch));
auto trt_parser = common::infer_object(nvonnxparser::createParser(
*trt_network, trt_logger));
// TODO: Fix this for the new API
//if( print_layer_info ) {
// parser->setLayerInfoStream(&std::cout);
//}
(void)print_layer_info;
if( verbosity >= (int)nvinfer1::ILogger::Severity::kWARNING ) {
cout << "Parsing model" << endl;
}
{
std::ifstream onnx_file(onnx_filename.c_str(),
std::ios::binary | std::ios::ate);
std::streamsize file_size = onnx_file.tellg();
onnx_file.seekg(0, std::ios::beg);
std::vector<char> onnx_buf(file_size);
if( !onnx_file.read(onnx_buf.data(), onnx_buf.size()) ) {
cerr << "ERROR: Failed to read from file " << onnx_filename << endl;
return -4;
}
if( !trt_parser->parse(onnx_buf.data(), onnx_buf.size()) ) {
int nerror = trt_parser->getNbErrors();
for( int i=0; i<nerror; ++i ) {
nvonnxparser::IParserError const* error = trt_parser->getError(i);
if( error->node() != -1 ) {
::ONNX_NAMESPACE::NodeProto const& node =
onnx_model.graph().node(error->node());
cerr << "While parsing node number " << error->node()
<< " [" << node.op_type();
if( node.output().size() ) {
cerr << " -> \"" << node.output(0) << "\"";
}
cerr << "]:" << endl;
if( verbosity >= (int)nvinfer1::ILogger::Severity::kINFO ) {
cerr << "--- Begin node ---" << endl;
cerr << node << endl;
cerr << "--- End node ---" << endl;
}
}
cerr << "ERROR: "
<< error->file() << ":" << error->line()
<< " In function " << error->func() << ":\n"
<< "[" << static_cast<int>(error->code()) << "] " << error->desc()
<< endl;
}
return -5;
}
}
bool fp16 = trt_builder->platformHasFastFp16();
if( !engine_filename.empty() ) {
if( verbosity >= (int)nvinfer1::ILogger::Severity::kWARNING ) {
cout << "Building TensorRT engine, FP16 available:"<< fp16 << endl;
cout << " Max batch size: " << max_batch_size << endl;
cout << " Max workspace size: " << max_workspace_size / (1024. * 1024) << " MiB" << endl;
}
trt_builder->setMaxBatchSize(max_batch_size);
trt_builder->setMaxWorkspaceSize(max_workspace_size);
if( fp16 && model_dtype == nvinfer1::DataType::kHALF) {
trt_builder->setHalf2Mode(true);
} else if( model_dtype == nvinfer1::DataType::kINT8 ) {
// TODO: Int8 support
//trt_builder->setInt8Mode(true);
cerr << "ERROR: Int8 mode not yet supported" << endl;
return -5;
}
trt_builder->setDebugSync(debug_builder);
auto trt_engine = common::infer_object(trt_builder->buildCudaEngine(*trt_network.get()));
auto engine_plan = common::infer_object(trt_engine->serialize());
std::ofstream engine_file(engine_filename.c_str());
if (!engine_file) {
cerr << "Failed to open output file for writing: "
<< engine_filename << endl;
return -6;
}
if( verbosity >= (int)nvinfer1::ILogger::Severity::kWARNING ) {
cout << "Writing TensorRT engine to " << engine_filename << endl;
}
engine_file.write((char*)engine_plan->data(), engine_plan->size());
engine_file.close();
}
if( verbosity >= (int)nvinfer1::ILogger::Severity::kWARNING ) {
cout << "All done" << endl;
}
return 0;
}
<file_sep>/onnx2trt.hpp
/*
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "NvOnnxParser.h"
#include "ShapedWeights.hpp"
#include "Status.hpp"
#include "TensorOrWeights.hpp"
#include <NvInfer.h>
#include <functional>
#include <onnx/onnx_pb.h>
#include <unordered_map>
#include <unordered_set>
#include <fstream>
#include <vector>
using WeightsPair_t = std::pair<std::string, nvinfer1::WeightsRole>;
using RefitMap_t = std::unordered_map<std::string, WeightsPair_t>;
namespace onnx2trt
{
class IImporterContext;
// TODO: Find ABI-safe alternative approach for this:
// Can't use std::vector
// Can't use ::onnx::NodeProto
// Can't use std::function
typedef ValueOrStatus<std::vector<TensorOrWeights>> NodeImportResult;
typedef std::function<NodeImportResult(
IImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node, std::vector<TensorOrWeights>& inputs)>
NodeImporter;
template <typename T>
using StringMap = std::unordered_map<std::string, T>;
class IImporterContext
{
public:
virtual nvinfer1::INetworkDefinition* network() = 0;
virtual StringMap<TensorOrWeights>& tensors() = 0;
virtual StringMap<nvinfer1::TensorLocation>& tensorLocations() = 0;
virtual StringMap<float>& tensorRangeMins() = 0;
virtual StringMap<float>& tensorRangeMaxes() = 0;
virtual StringMap<nvinfer1::DataType>& layerPrecisions() = 0;
virtual std::unordered_set<std::string>& unsupportedShapeTensors() = 0;
virtual StringMap<std::string>& loopTensors() = 0;
virtual void setOnnxFileLocation(std::string location) = 0;
virtual std::string getOnnxFileLocation() = 0;
virtual void registerTensor(TensorOrWeights tensor, const std::string& basename) = 0;
virtual void registerLayer(nvinfer1::ILayer* layer, const std::string& basename) = 0;
virtual ShapedWeights createTempWeights(ShapedWeights::DataType type, nvinfer1::Dims shape) = 0;
virtual int64_t getOpsetVersion(const char* domain = "") const = 0;
virtual nvinfer1::ILogger& logger() = 0;
virtual void insertRefitMap(std::string weightsName, std::string layerName, nvinfer1::WeightsRole role) = 0;
protected:
virtual ~IImporterContext()
{
}
};
} // namespace onnx2trt
<file_sep>/ModelImporter.hpp
/*
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "ImporterContext.hpp"
#include "NvInferPlugin.h"
#include "NvOnnxParser.h"
#include "builtin_op_importers.hpp"
#include "onnx_utils.hpp"
#include "utils.hpp"
namespace onnx2trt
{
Status parseGraph(IImporterContext* ctx, const ::ONNX_NAMESPACE::GraphProto& graph, bool deserializingINetwork = false, int* currentNode = nullptr);
class ModelImporter : public nvonnxparser::IParser
{
protected:
string_map<NodeImporter> _op_importers;
virtual Status importModel(::ONNX_NAMESPACE::ModelProto const& model, uint32_t weight_count,
onnxTensorDescriptorV1 const* weight_descriptors);
private:
ImporterContext _importer_ctx;
RefitMap_t mRefitMap;
std::list<::ONNX_NAMESPACE::ModelProto> _onnx_models; // Needed for ownership of weights
int _current_node;
std::vector<Status> _errors;
public:
ModelImporter(nvinfer1::INetworkDefinition* network, nvinfer1::ILogger* logger)
: _op_importers(getBuiltinOpImporterMap())
, _importer_ctx(network, logger, &mRefitMap)
{
}
bool parseWithWeightDescriptors(void const* serialized_onnx_model, size_t serialized_onnx_model_size,
uint32_t weight_count, onnxTensorDescriptorV1 const* weight_descriptors) override;
bool parse(void const* serialized_onnx_model, size_t serialized_onnx_model_size) override;
bool supportsModel(void const* serialized_onnx_model, size_t serialized_onnx_model_size,
SubGraphCollection_t& sub_graph_collection) override;
bool supportsOperator(const char* op_name) const override;
void destroy() override
{
delete this;
}
// virtual void registerOpImporter(std::string op,
// NodeImporter const &node_importer) override {
// // Note: This allows existing importers to be replaced
// _op_importers[op] = node_importer;
//}
// virtual Status const &setInput(const char *name,
// nvinfer1::ITensor *input) override;
// virtual Status const& setOutput(const char* name, nvinfer1::ITensor** output) override;
int getNbErrors() const override
{
return _errors.size();
}
nvonnxparser::IParserError const* getError(int index) const override
{
assert(0 <= index && index < (int) _errors.size());
return &_errors[index];
}
void clearErrors() override
{
_errors.clear();
}
virtual int getRefitMap(const char** weightNames, const char** layerNames, nvinfer1::WeightsRole* roles) override
{
int count = 0;
for (const auto& entry: mRefitMap)
{
if (weightNames != nullptr)
{
weightNames[count] = entry.first.c_str();
}
if (layerNames != nullptr)
{
layerNames[count] = entry.second.first.c_str();
}
if (roles != nullptr)
{
roles[count] = entry.second.second;
}
++count;
}
return mRefitMap.size();
}
//...LG: Move the implementation to .cpp
bool parseFromFile(const char* onnxModelFile, int verbosity) override;
};
} // namespace onnx2trt
<file_sep>/CMakeLists.txt
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
cmake_minimum_required(VERSION 3.13)
cmake_policy(SET CMP0091 NEW)
if (NOT DEFINED MSVC_RUNTIME_LIBRARY)
set(MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>$<$<NOT:$<BOOL:${ONNX_USE_MSVC_STATIC_RUNTIME}>>:DLL>")
message(STATUS "MSVC_RUNTIME_LIBRARY is defined in project onnx-tensorrt." )
endif()
project(onnx2trt LANGUAGES CXX C)
if (MSVC)
option(ONNX_USE_MSVC_STATIC_RUNTIME "ONNX_USE_MSVC_STATIC_RUNTIME" ON)
endif()
set(ONNX2TRT_ROOT ${PROJECT_SOURCE_DIR})
# Set C++11 as standard for the whole project
set(CMAKE_CXX_STANDARD 11)
# Enable compiler warnings
if (CMAKE_COMPILER_IS_GNUCC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-deprecated-declarations -Wno-unused-function")
endif()
if (MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4")
endif()
# Build the libraries with -fPIC
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(PARSER_LINKER_SCRIPT ${ONNX2TRT_ROOT}/libnvonnxparser.version)
#--------------------------------------------------
# Version information
#--------------------------------------------------
set(ONNX2TRT_MAJOR 7)
set(ONNX2TRT_MINOR 2)
set(ONNX2TRT_PATCH 1)
#--------------------------------------------------
# Build configurations, global to all projects
#--------------------------------------------------
set(IMPORTER_SOURCES
NvOnnxParser.cpp
ModelImporter.cpp
builtin_op_importers.cpp
onnx2trt_utils.cpp
ShapedWeights.cpp
ShapeTensor.cpp
LoopHelpers.cpp
RNNHelpers.cpp
OnnxAttrs.cpp
)
# Do not build ONNXIFI by default.
if(BUILD_ONNXIFI)
if (NOT CUDA_TOOLKIT_ROOT_DIR)
set(CUDA_TOOLKIT_ROOT_DIR /usr/local/cuda)
endif()
message(debug "CUDA_TOOLKIT_ROOT_DIR: ${CUDA_TOOLKIT_ROOT_DIR}")
find_path(CUDA_INCLUDE_DIR cuda_runtime.h
HINTS ${CUDA_TOOLKIT_ROOT_DIR}
PATH_SUFFIXES include
)
set(ONNXIFI_SOURCES onnx_trt_backend.cpp)
endif()
set(EXECUTABLE_SOURCES
# as string at configuration step, as generator expression at build step.
$<$<BOOL:${MSVC}>:win_getopt.h>
main.cpp
)
set(API_TESTS_SOURCES
# as string at configuration step, as generator expression at build step.
$<$<BOOL:${MSVC}>:win_getopt.h>
getSupportedAPITest.cpp
ModelImporter.cpp
)
set(HEADERS
NvOnnxParser.h
)
if (NOT TARGET protobuf::libprotobuf)
FIND_PACKAGE(Protobuf REQUIRED)
else()
set(PROTOBUF_LIB "protobuf::libprotobuf")
endif()
if(NOT TARGET onnx_proto)
# Note: This avoids libprotobuf.so complaining about name collisions at runtime
if(NOT ONNX_NAMESPACE)
set(ONNX_NAMESPACE "onnx2trt_onnx")
endif()
add_definitions("-DONNX_NAMESPACE=${ONNX_NAMESPACE}")
add_subdirectory(third_party/onnx EXCLUDE_FROM_ALL)
endif()
# TensorRT
find_path(TENSORRT_INCLUDE_DIR NvInfer.h
HINTS ${TENSORRT_ROOT} ${CUDA_TOOLKIT_ROOT_DIR}
PATH_SUFFIXES include)
MESSAGE(STATUS "Found TensorRT headers at ${TENSORRT_INCLUDE_DIR}")
find_library(TENSORRT_LIBRARY_INFER nvinfer
HINTS ${TENSORRT_ROOT} ${TENSORRT_BUILD} ${CUDA_TOOLKIT_ROOT_DIR}
PATH_SUFFIXES lib lib64 lib/x64)
find_library(TENSORRT_LIBRARY_INFER_PLUGIN nvinfer_plugin
HINTS ${TENSORRT_ROOT} ${TENSORRT_BUILD} ${CUDA_TOOLKIT_ROOT_DIR}
PATH_SUFFIXES lib lib64 lib/x64)
if(WIN32)
find_library(TENSORRT_LIBRARY_MYELIN myelin64_1
HINTS ${TENSORRT_ROOT} ${TENSORRT_BUILD} ${CUDA_TOOLKIT_ROOT_DIR}
PATH_SUFFIXES lib lib64 lib/x64)
else()
find_library(TENSORRT_LIBRARY_MYELIN myelin
HINTS ${TENSORRT_ROOT} ${TENSORRT_BUILD} ${CUDA_TOOLKIT_ROOT_DIR}
PATH_SUFFIXES lib lib64 lib/x64)
endif()
set(TENSORRT_LIBRARY ${TENSORRT_LIBRARY_INFER} ${TENSORRT_LIBRARY_INFER_PLUGIN} ${TENSORRT_LIBRARY_MYELIN})
MESSAGE(STATUS "Find TensorRT libs at ${TENSORRT_LIBRARY}")
find_package_handle_standard_args(
TENSORRT DEFAULT_MSG TENSORRT_INCLUDE_DIR TENSORRT_LIBRARY)
if(NOT TENSORRT_FOUND)
message(ERROR "Cannot find TensorRT library.")
endif()
# --------------------------------
# Importer library
# --------------------------------
add_library(nvonnxparser SHARED ${IMPORTER_SOURCES})
target_include_directories(nvonnxparser PUBLIC ${ONNX_INCLUDE_DIRS} ${TENSORRT_INCLUDE_DIR})
target_link_libraries(nvonnxparser PUBLIC onnx_proto ${PROTOBUF_LIBRARY} ${TENSORRT_LIBRARY})
set_target_properties(nvonnxparser PROPERTIES
VERSION ${ONNX2TRT_MAJOR}.${ONNX2TRT_MINOR}.${ONNX2TRT_PATCH}
SOVERSION ${ONNX2TRT_MAJOR}
LINK_DEPENDS ${PARSER_LINKER_SCRIPT}
)
if (MSVC)
target_compile_options(nvonnxparser PRIVATE /utf-8 /wd4099 /wd4100 /wd4127 /wd4244 /wd4251 /wd4267 /wd4456 /wd4505 /wd4551 /wd4702 /wd4706 /wd4804 /wd4805 /wd4996)
else()
set_target_properties(nvonnxparser PROPERTIESLINK_FLAGS "-Wl,--version-script=${PARSER_LINKER_SCRIPT}")
endif()
add_library(nvonnxparser_static STATIC ${IMPORTER_SOURCES})
target_include_directories(nvonnxparser_static PUBLIC ${ONNX_INCLUDE_DIRS} ${TENSORRT_INCLUDE_DIR})
target_link_libraries(nvonnxparser_static PUBLIC onnx_proto ${PROTOBUF_LIBRARY} ${TENSORRT_LIBRARY})
if (MSVC)
target_compile_options(nvonnxparser_static PRIVATE /utf-8 /wd4099 /wd4100 /wd4127 /wd4244 /wd4251 /wd4267 /wd4456 /wd4505 /wd4551 /wd4702 /wd4706 /wd4804 /wd4805 /wd4996)
endif()
# --------------------------------
# Onnxifi library
# --------------------------------
if(BUILD_ONNXIFI)
add_library(trt_onnxify SHARED ${ONNXIFI_SOURCES})
target_include_directories(trt_onnxify PUBLIC ${CUDA_INCLUDE_DIR} ${ONNX_INCLUDE_DIRS} ${TENSORRT_INCLUDE_DIR})
target_link_libraries(trt_onnxify PUBLIC nvonnxparser_static ${CMAKE_THREAD_LIBS_INIT} ${CMAKE_DL_LIBS})
endif()
# --------------------------------
# Converter executable
# --------------------------------
add_executable(onnx2trt ${EXECUTABLE_SOURCES})
target_include_directories(onnx2trt PUBLIC ${ONNX_INCLUDE_DIRS})
target_link_libraries(onnx2trt PUBLIC ${PROTOBUF_LIB} onnx nvonnxparser_static ${CMAKE_THREAD_LIBS_INIT} ${CMAKE_DL_LIBS}) #${CUDA_LIBRARIES}
if (MSVC)
target_compile_options(onnx2trt PRIVATE /utf-8 /wd4127 /wd4244 /wd4251 /wd4267 /wd4996)
endif()
# --------------------------------
# API Tests
# --------------------------------
add_executable(getSupportedAPITest ${API_TESTS_SOURCES})
target_include_directories(getSupportedAPITest PUBLIC ${ONNX_INCLUDE_DIRS} ${CUDNN_INCLUDE_DIR})
target_link_libraries(getSupportedAPITest PUBLIC ${PROTOBUF_LIB} nvonnxparser_static ${CMAKE_THREAD_LIBS_INIT} ${CMAKE_DL_LIBS}) #${CUDA_LIBRARIES}
if (MSVC)
target_compile_options(getSupportedAPITest PRIVATE /utf-8 /wd4099 /wd4100 /wd4127 /wd4244 /wd4251 /wd4267 /wd4505 /wd4706 /wd4996)
endif()
if (MSVC)
if (POLICY CMP0091)
if (DEFINED MSVC_RUNTIME_LIBRARY)
set_target_properties(nvonnxparser PROPERTIES MSVC_RUNTIME_LIBRARY "${MSVC_RUNTIME_LIBRARY}")
set_target_properties(nvonnxparser_static PROPERTIES MSVC_RUNTIME_LIBRARY "${MSVC_RUNTIME_LIBRARY}")
set_target_properties(onnx2trt PROPERTIES MSVC_RUNTIME_LIBRARY "${MSVC_RUNTIME_LIBRARY}")
set_target_properties(getSupportedAPITest PROPERTIES MSVC_RUNTIME_LIBRARY "${MSVC_RUNTIME_LIBRARY}")
else()
message(SEND_ERROR "MSVC_RUNTIME_LIBRARY is not defined.")
endif()
else()
message(SEND_ERROR "POLICY CMP0091 is not set.")
endif()
endif()
# --------------------------------
# Installation
# --------------------------------
install(TARGETS
onnx2trt
nvonnxparser
nvonnxparser_static
RUNTIME DESTINATION bin
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
)
install(FILES ${HEADERS}
DESTINATION include
)
SET(CPACK_GENERATOR "DEB")
SET(CPACK_DEBIAN_PACKAGE_MAINTAINER "<NAME>") #required
SET(CPACK_PACKAGE_NAME "onnx-trt-dev")
SET(CPACK_PACKAGE_VERSION "0.5.9")
SET(CPACK_PACKAGE_VERSION_MAJOR "0")
SET(CPACK_PACKAGE_VERSION_MINOR "5")
SET(CPACK_PACKAGE_VERSION_PATCH "9")
INCLUDE(CPack)
<file_sep>/Changelog.md
# ONNX-TensorRT Changelog
## TensorRT 7.2.1 Release - 2020-10-20
### Added
- Added support for parsing large models with external data
- Added API for interfacing with TensorRT's refit feature
- Updated `onnx_tensorrt` backend to support dynamic shapes
- Added support for 3D instance normalizations [#515](https://github.com/onnx/onnx-tensorrt/pull/515)
- Improved clarity on the resize modes TRT supports [#512](https://github.com/onnx/onnx-tensorrt/pull/521)
- Added Changelog
### Changed
- Unified docker usage between ONNX-TensorRT and TensorRT.
## Removed
- Removed deprecated docker files.
- Removed deprecated `setup.py`.
<file_sep>/getSupportedAPITest.cpp
/*
* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <fstream>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
#include "win_getopt.h" // For ::getopt on windows
#else
#include <unistd.h> // For ::getopt on linux
#endif
#include <string>
#include "NvOnnxParser.h"
#include "NvInferPlugin.h"
#include "onnx_utils.hpp"
#include "common.hpp"
using std::cout;
using std::cerr;
using std::endl;
void print_usage() {
cout << "This program will determine whether or not an ONNX model is compatible with TensorRT. "
<< "If it isn't, a list of supported subgraphs and unsupported operations will be printed." << endl;
cout << "Usage: getSupportedAPITest -m onnx_model.pb" << endl;
cout << "Optional argument: -e TRT_engine" << endl;
}
void printSubGraphs(SubGraphCollection_t& subGraphs, ::ONNX_NAMESPACE::ModelProto onnx_model)
{
if (subGraphs.size() != 1)
{
cout << "The model contains unsupported Nodes. It has been partitioned to a set of supported subGraphs." << endl;
cout << "There are "<< subGraphs.size() << " supported subGraphs: " << endl;
cout << "NOTE: Due to some limitations with the parser, the support of specific subgraphs may not have been determined."
<< " Please refer to the printed subgraphs to see if they are truly supported or not." << endl;
}
else
{
cout << "The model is fully supported by TensorRT. Printing the parsed graph:" << endl;
}
for (auto subGraph: subGraphs)
{
cout << "\t{";
for (auto idx: subGraph.first) cout << "\t" << idx << "," <<onnx_model.graph().node(idx).op_type();
cout << "\t}\t - ";
if (subGraph.second)
{
cout << "Fully supported" << endl;
}
else
{
cout << "UNKNOWN whether this is fully supported." << endl;
}
}
}
int main(int argc, char* argv[]) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
std::string engine_filename;
std::string text_filename;
std::string full_text_filename;
std::string onnx_filename;
int c;
size_t max_batch_size = 32;
size_t max_workspace_size = 1 << 30;
int verbosity = (int)nvinfer1::ILogger::Severity::kWARNING;
while ((c = getopt (argc, argv, "m:e:")) != -1)
{
switch(c)
{
case 'm':
onnx_filename = optarg;
break;
case 'e':
engine_filename = optarg;
break;
}
}
if (onnx_filename.empty())
{
print_usage();
return -1;
}
common::TRT_Logger trt_logger((nvinfer1::ILogger::Severity)verbosity);
auto trt_builder = common::infer_object(nvinfer1::createInferBuilder(trt_logger));
auto trt_network = common::infer_object(trt_builder->createNetworkV2(1U << static_cast<uint32_t>(nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH)));
auto trt_parser = common::infer_object(nvonnxparser::createParser(*trt_network, trt_logger));
initLibNvInferPlugins(&trt_logger, "");
cout << "Parsing model: " << onnx_filename << endl;
std::ifstream onnx_file(onnx_filename.c_str(),
std::ios::binary | std::ios::ate);
std::streamsize file_size = onnx_file.tellg();
onnx_file.seekg(0, std::ios::beg);
std::vector<char> onnx_buf(file_size);
if( !onnx_file.read(onnx_buf.data(), onnx_buf.size()) ) {
cerr << "ERROR: Failed to read from file " << onnx_filename << endl;
return -1;
}
::ONNX_NAMESPACE::ModelProto onnx_model;
if (!common::ParseFromFile_WAR(&onnx_model, onnx_filename.c_str()))
{
cout << "Failure while parsing ONNX file" << endl;
return -1;
}
SubGraphCollection_t SubGraphCollection;
// supportsModel() parses the graph and returns a list of supported subgraphs.
if (!trt_parser->supportsModel(onnx_buf.data(), onnx_buf.size(), SubGraphCollection))
{
cout << "Model cannot be fully parsed by TensorRT!" << endl;
printSubGraphs(SubGraphCollection, onnx_model);
return -1;
}
printSubGraphs(SubGraphCollection, onnx_model);
// If -e was specified, create and save the TensorRT engine to disk.
// Note we do not call trt_parser->parse() here since it's already done above in parser->supportsModel()
if( !engine_filename.empty() ) {
trt_builder->setMaxBatchSize(max_batch_size);
trt_builder->setMaxWorkspaceSize(max_workspace_size);
cout << "input name: " << trt_network->getInput(0)->getName() << endl;
cout << "output name: " << trt_network->getOutput(0)->getName() << endl;
cout << "num layers: " << trt_network->getNbLayers() << endl;
cout << "outputs: " << trt_network->getNbOutputs() << endl;
auto trt_engine = common::infer_object(trt_builder->buildCudaEngine(*trt_network.get()));
if( verbosity >= (int)nvinfer1::ILogger::Severity::kWARNING ) {
cout << "Writing TensorRT engine to " << engine_filename << endl;
}
auto engine_plan = common::infer_object(trt_engine->serialize());
std::ofstream engine_file(engine_filename.c_str(), std::ios::binary);
engine_file.write(reinterpret_cast<const char*>(engine_plan->data()), engine_plan->size());
engine_file.close();
}
if( verbosity >= (int)nvinfer1::ILogger::Severity::kWARNING ) {
cout << "All done" << endl;
}
return 0;
}
<file_sep>/common/unistd.h
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif /* _UNISTD_H */<file_sep>/onnx_backend_test.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import unittest
import onnx.backend.test
import onnx_tensorrt.backend as trt
# This is a pytest magic variable to load extra plugins
pytest_plugins = 'onnx.backend.test.report',
backend_test = onnx.backend.test.BackendTest(trt, __name__)
# Include all of the nodes that we support.
# Onnx native node tests
backend_test.include(r'.*test_abs.*')
backend_test.include(r'.*test_acos.*')
backend_test.include(r'.*test_acosh.*')
backend_test.include(r'.*test_add.*')
backend_test.include(r'.*test_argmax.*')
backend_test.include(r'.*test_argmin.*')
backend_test.include(r'.*test_asin.*')
backend_test.include(r'.*test_asinh.*')
backend_test.include(r'.*test_atan.*')
backend_test.include(r'.*test_atanh.*')
backend_test.include(r'.*test_averagepool.*')
backend_test.include(r'.*test_AvgPool.*')
backend_test.include(r'.*test_BatchNorm.*eval.*')
backend_test.include(r'.*test_ceil.*')
backend_test.include(r'.*test_clip.*')
backend_test.include(r'.*test_concat.*')
backend_test.include(r'.*test_constant.*')
backend_test.include(r'.*test_Conv[1-3]d*')
backend_test.include(r'.*test_cos.*')
backend_test.include(r'.*test_cosh.*')
backend_test.include(r'.*test_depthtospace.*')
backend_test.include(r'.*test_div.*')
backend_test.include(r'.*test_dropout.*')
backend_test.include(r'.*test_ELU*')
backend_test.include(r'.*test_elu.*')
backend_test.include(r'.*test_equal.*')
backend_test.include(r'.*test_Embedding*')
backend_test.include(r'.*test_exp.*')
backend_test.include(r'.*test_flatten.*')
backend_test.include(r'.*test_floor.*')
backend_test.include(r'.*test_gather.*')
backend_test.include(r'.*test_gemm.*')
backend_test.include(r'.*test_globalaveragepool.*')
backend_test.include(r'.*test_globalmaxpool.*')
backend_test.include(r'.*test_greater.*')
backend_test.include(r'.*test_hardsigmoid.*')
backend_test.include(r'.*test_identity.*')
backend_test.include(r'.*test_LeakyReLU*')
backend_test.include(r'.*test_leakyrelu.*')
backend_test.include(r'.*test_less.*')
backend_test.include(r'.*test_Linear.*')
backend_test.include(r'.*test_log.*')
backend_test.include(r'.*test_logsoftmax.*')
backend_test.include(r'.*test_LogSoftmax.*')
backend_test.include(r'.*test_log_softmax.*')
backend_test.include(r'.*test_lrn.*')
backend_test.include(r'.*test_matmul.*')
backend_test.include(r'.*test_max.*')
backend_test.include(r'.*test_MaxPool[1-9]d.*')
backend_test.include(r'.*test_mean.*')
backend_test.include(r'.*test_min.*')
backend_test.include(r'.*test_mul.*')
backend_test.include(r'.*test_neg.*')
backend_test.include(r'.*test_not.*')
backend_test.include(r'.*test_operator_addmm.*')
backend_test.include(r'.*test_operator_basic.*')
backend_test.include(r'.*test_operator_chunk.*')
backend_test.include(r'.*test_operator_clip.*')
backend_test.include(r'.*test_operator_concat2.*')
backend_test.include(r'.*test_operator_conv_.*')
backend_test.include(r'.*test_operator_exp.*')
backend_test.include(r'.*test_operator_flatten.*')
backend_test.include(r'.*test_operator_index.*')
backend_test.include(r'.*test_operator_max_.*')
backend_test.include(r'.*test_operator_maxpool.*')
backend_test.include(r'.*test_operator_min.*')
backend_test.include(r'.*test_operator_mm.*')
backend_test.include(r'.*test_operator_non_float_params.*')
backend_test.include(r'.*test_operator_params.*')
backend_test.include(r'.*test_operator_permute2.*')
backend_test.include(r'.*test_operator_pow.*')
backend_test.include(r'.*test_operator_reduced_mean_.*')
backend_test.include(r'.*test_operator_reduced_mean_keepdim.*')
backend_test.include(r'.*test_operator_reduced_sum_.*')
backend_test.include(r'.*test_operator_reduced_sum_keepdim.*')
backend_test.include(r'.*test_operator_selu.*')
backend_test.include(r'.*test_operator_sqrt.*')
backend_test.include(r'.*test_operator_symbolic_override.*')
backend_test.include(r'.*test_operator_symbolic_override_nested.*')
backend_test.include(r'.*test_operator_view.*')
backend_test.include(r'.*test_pow.*')
backend_test.include(r'.*test_PoissonNLLLLoss_no_reduce*')
backend_test.include(r'.*test_reciprocal.*')
backend_test.include(r'.*test_reduce.*')
backend_test.include(r'.*test_ReLU*')
backend_test.include(r'.*test_relu.*')
backend_test.include(r'.*test_selu.*')
backend_test.include(r'.*test_shape.*')
backend_test.include(r'.*test_Sigmoid*')
backend_test.include(r'.*test_sigmoid.*')
backend_test.include(r'.*test_sin.*')
backend_test.include(r'.*test_sinh.*')
backend_test.include(r'.*test_size.*')
backend_test.include(r'.*test_Softmax*')
backend_test.include(r'.*test_softmax.*')
backend_test.include(r'.*test_Softmin*')
backend_test.include(r'.*test_Softplus*')
backend_test.include(r'.*test_softplus.*')
backend_test.include(r'.*test_softsign.*')
backend_test.include(r'.*test_sqrt.*')
backend_test.include(r'.*test_squeeze_cuda')
backend_test.include(r'.*test_sub.*')
backend_test.include(r'.*test_sum.*')
backend_test.include(r'.*test_tan.*')
backend_test.include(r'.*test_Tanh*')
backend_test.include(r'.*test_tanh.*')
backend_test.include(r'.*test_thresholdedrelu.*')
backend_test.include(r'.*test_transpose.*')
backend_test.include(r'.*test_unsqueeze.*')
backend_test.include(r'.*test_ZeroPad2d*')
# # Onnx native model tests
backend_test.include(r'.*test_bvlc_alexnet.*')
backend_test.include(r'.*test_densenet121.*')
backend_test.include(r'.*test_inception_v1.*')
backend_test.include(r'.*test_inception_v2.*')
backend_test.include(r'.*test_resnet50.*')
backend_test.include(r'.*test_shufflenet.*')
backend_test.include(r'.*test_squeezenet.*')
backend_test.include(r'.*test_vgg19.*')
backend_test.include(r'.*test_zfnet512.*')
#TRT custom tests
backend_test.include(r'.*test_basic_conv_.*custom.*')
backend_test.include(r'.*test_conv_.*custom.*')
backend_test.include(r'.*test_convtranspose.*custom.*')
backend_test.include(r'.*test_batchnorm.*custom.*')
backend_test.include(r'.*test_reshape.*custom.*')
backend_test.include(r'.*test_prelu.*custom.*')
backend_test.include(r'.*test_topk.*custom.*')
backend_test.include(r'.*test_upsample.*custom.*')
backend_test.include(r'.*test_constant_pad_custom.*')
backend_test.include(r'.*test_resize.*custom.*')
backend_test.include(r'.*test_split.*custom.*')
backend_test.include(r'.*test_instancenorm_.*_custom.*')
backend_test.include(r'.*test_slice.*custom.*')
# exclude unenabled ops get pulled in with wildcards
# test_constant_pad gets pulled in with the test_constant* wildcard. Explicitly disable padding tests for now.
backend_test.exclude(r'.*test_constant_pad.*')
backend_test.exclude(r'.*test_constantofshape.*')
backend_test.exclude(r'.*test_expand.*')
# Operator MATMULINTEGER is not supported by TRT
backend_test.exclude(r'.*test_matmulinteger.*')
backend_test.exclude(r'.*test_maxpool.*')
backend_test.exclude(r'.*test_maxunpool.*')
# Mismatch: 0.476%, relative diff is good.
# Absolute diff failed because
# numpy compares the difference between actual and desired to atol + rtol * abs(desired)
backend_test.exclude(r'.*test_convtranspose_3d_custom_cuda')
# dilations not supported in ConvTRanspose layer
backend_test.exclude(r'.*test_convtranspose_dilations_custom_cuda')
globals().update(backend_test
.enable_report()
.test_cases)
if __name__ == '__main__':
unittest.main()
<file_sep>/TensorOrWeights.hpp
/*
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "ShapedWeights.hpp"
#include <NvInfer.h>
#include <cassert>
namespace onnx2trt
{
class TensorOrWeights
{
union
{
nvinfer1::ITensor* _tensor;
ShapedWeights _weights;
};
enum
{
NODE_TENSOR,
NODE_WEIGHTS
} _variant;
public:
TensorOrWeights()
: _tensor(nullptr)
, _variant(NODE_TENSOR)
{
}
TensorOrWeights(nvinfer1::ITensor* tensor)
: _tensor(tensor)
, _variant(NODE_TENSOR)
{
}
TensorOrWeights(ShapedWeights const& weights)
: _weights(weights)
, _variant(NODE_WEIGHTS)
{
}
bool is_tensor() const
{
return _variant == NODE_TENSOR;
}
bool is_weights() const
{
return _variant == NODE_WEIGHTS;
}
bool isNullTensor() const
{
return is_tensor() && _tensor == nullptr;
}
nvinfer1::ITensor& tensor()
{
assert(!isNullTensor());
return *_tensor;
}
nvinfer1::ITensor const& tensor() const
{
assert(!isNullTensor());
return *_tensor;
}
ShapedWeights& weights()
{
assert(is_weights());
return _weights;
}
ShapedWeights const& weights() const
{
assert(is_weights());
return _weights;
}
nvinfer1::Dims shape() const
{
return is_tensor() ? _tensor->getDimensions() : _weights.shape;
}
explicit operator bool() const
{
return is_tensor() ? _tensor != nullptr : static_cast<bool>(_weights);
}
bool isInt32() const
{
return is_tensor() ? _tensor->getType() == nvinfer1::DataType::kINT32 : _weights.type == ::ONNX_NAMESPACE::TensorProto_DataType_INT32;
}
bool isBool() const
{
return is_tensor() ? _tensor->getType() == nvinfer1::DataType::kBOOL : _weights.type == ::ONNX_NAMESPACE::TensorProto_DataType_BOOL;
}
std::string getName() const
{
return is_tensor() ? _tensor->getName() : _weights.getName();
}
};
} // namespace onnx2trt
<file_sep>/README.md
# TensorRT backend for ONNX
Parses ONNX models for execution with [TensorRT](https://developer.nvidia.com/tensorrt).
See also the [TensorRT documentation](https://docs.nvidia.com/deeplearning/sdk/#inference).
For the list of recent changes, see the [changelog](Changelog.md).
## Supported TensorRT Versions
Development on the Master branch is for the latest version of [TensorRT 7.2.1](https://developer.nvidia.com/nvidia-tensorrt-download) with full-dimensions and dynamic shape support.
For previous versions of TensorRT, refer to their respective branches.
## Full Dimensions + Dynamic Shapes
Building INetwork objects in full dimensions mode with dynamic shape support requires calling the following API:
C++
const auto explicitBatch = 1U << static_cast<uint32_t>(nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH);
builder->createNetworkV2(explicitBatch)
Python
import tensorrt
explicit_batch = 1 << (int)(tensorrt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
builder.create_network(explicit_batch)
For examples of usage of these APIs see:
* [sampleONNXMNIST](https://github.com/NVIDIA/TensorRT/tree/master/samples/opensource/sampleOnnxMNIST)
* [sampleDynamicReshape](https://github.com/NVIDIA/TensorRT/tree/master/samples/opensource/sampleDynamicReshape)
## Supported Operators
Current supported ONNX operators are found in the [operator support matrix](operators.md).
# Installation
### Dependencies
- [Protobuf >= 3.0.x](https://github.com/google/protobuf/releases)
- [TensorRT 7.2.1](https://developer.nvidia.com/tensorrt)
- [TensorRT 7.2.1 open source libaries (master branch)](https://github.com/NVIDIA/TensorRT/)
### Building
For building within docker, we recommend using and setting up the docker containers as instructed in the main (TensorRT repository)[https://github.com/NVIDIA/TensorRT#setting-up-the-build-environment] to build the onnx-tensorrt library.
Once you have cloned the repository, you can build the parser libraries and executables by running:
cd onnx-tensorrt
mkdir build && cd build
cmake .. -DTENSORRT_ROOT=<path_to_trt> && make -j
// Ensure that you update your LD_LIBRARY_PATH to pick up the location of the newly built library:
export LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH
## Executable usage
ONNX models can be converted to serialized TensorRT engines using the `onnx2trt` executable:
onnx2trt my_model.onnx -o my_engine.trt
ONNX models can also be converted to human-readable text:
onnx2trt my_model.onnx -t my_model.onnx.txt
ONNX models can also be optimized by ONNX's optimization libraries (added by [dsandler](https://gitlab-master.nvidia.com/dsandler)).
To optimize an ONNX model and output a new one use `-m` to specify the output model name and `-O` to specify a semicolon-separated list of optimization passes to apply:
onnx2trt my_model.onnx -O "pass_1;pass_2;pass_3" -m my_model_optimized.onnx
See more all available optimization passes by running:
onnx2trt -p
See more usage information by running:
onnx2trt -h
### Python modules
Python bindings for the ONNX-TensorRT parser are packaged in the shipped `.whl` files. Install them with
pip install <tensorrt_install_dir>/python/tensorrt-7.x.x.x-cp<python_ver>-none-linux_x86_64.whl
TensorRT 7.2.1 supports ONNX release 1.6.0. Install it with:
pip install onnx==1.6.0
## ONNX Python backend usage
The TensorRT backend for ONNX can be used in Python as follows:
```python
import onnx
import onnx_tensorrt.backend as backend
import numpy as np
model = onnx.load("/path/to/model.onnx")
engine = backend.prepare(model, device='CUDA:1')
input_data = np.random.random(size=(32, 3, 224, 224)).astype(np.float32)
output_data = engine.run(input_data)[0]
print(output_data)
print(output_data.shape)
```
## C++ library usage
The model parser library, libnvonnxparser.so, has its C++ API declared in this header:
NvOnnxParser.h
### Tests
After installation (or inside the Docker container), ONNX backend tests can be run as follows:
Real model tests only:
python onnx_backend_test.py OnnxBackendRealModelTest
All tests:
python onnx_backend_test.py
You can use `-v` flag to make output more verbose.
## Pre-trained models
Pre-trained models in ONNX format can be found at the [ONNX Model Zoo](https://github.com/onnx/models)<file_sep>/ShapedWeights.cpp
/*
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "ShapedWeights.hpp"
#include "onnx2trt_utils.hpp"
#include "trt_utils.hpp"
#include <cstdint>
#include <cstring>
namespace onnx2trt
{
size_t ShapedWeights::count() const
{
if (this->values == nullptr && this->shape.nbDims <= 0)
{
return 0;
}
// TRT supports scalars, so 0D tensors should have a count of 1.
size_t c = 1;
for (int i = 0; i < this->shape.nbDims; ++i)
{
c *= this->shape.d[i];
}
return c;
}
ShapedWeights ShapedWeights::empty(DataType type)
{
return ShapedWeights(type, nullptr, nvinfer1::Dims{0});
}
ShapedWeights::ShapedWeights()
: values(nullptr)
, shape{0}
{
}
ShapedWeights::ShapedWeights(DataType type_, void* values_, nvinfer1::Dims shape_)
: type(type_)
, values(values_)
, shape(shape_)
{
// Note: this->shape.type[] is not used
}
size_t ShapedWeights::size_bytes() const
{
return this->count() * getDtypeSize(this->type);
}
const char* ShapedWeights::getName() const
{
return this->name;
}
void ShapedWeights::setName(const char* name)
{
this->name = name;
}
ShapedWeights::operator bool() const
{
return (bool) this->values;
}
ShapedWeights::operator nvinfer1::Weights() const
{
nvinfer1::Weights w{};
w.values = this->values;
bool supported_type = convertDtype(this->type, &w.type);
(void) supported_type;
assert(supported_type);
w.count = this->count();
return w;
}
template <typename DType>
void transpose2DWeights(ShapedWeights const& weights, nvinfer1::Dims const& new_shape, ShapedWeights* result)
{
DType const* src = reinterpret_cast<DType*>(weights.values);
DType* dst = reinterpret_cast<DType*>(result->values);
int src_stride = weights.shape.d[1];
int dst_stride = result->shape.d[1];
for (int i = 0; i < new_shape.d[0]; ++i)
{
for (int j = 0; j < new_shape.d[1]; ++j)
{
dst[i * dst_stride + j] = src[j * src_stride + i];
}
}
}
bool transposeWeights(ShapedWeights const& weights, nvinfer1::Permutation const& perm, ShapedWeights* result)
{
nvinfer1::Dims shape = weights.shape;
nvinfer1::Dims new_shape;
new_shape.nbDims = shape.nbDims;
for (int d = 0; d < shape.nbDims; ++d)
{
new_shape.d[d] = shape.d[perm.order[d]];
result->shape.d[d] = new_shape.d[d];
}
// TODO: Need to generalize this transpose implementation
assert(perm.order[0] == 1 && perm.order[1] == 0);
if (shape.nbDims == 2)
{
if (weights.type == ::ONNX_NAMESPACE::TensorProto::FLOAT)
{
transpose2DWeights<float>(weights, new_shape, result);
}
else if (weights.type == ::ONNX_NAMESPACE::TensorProto::FLOAT16)
{
transpose2DWeights<uint16_t>(weights, new_shape, result);
}
else
{
return false;
}
}
else
{
// TODO: Implement general transposes and multiple data types
// Unsupported weights transpose
return false;
}
return true;
}
} // namespace onnx2trt
<file_sep>/NvOnnxParser.h
/*
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef NV_ONNX_PARSER_H
#define NV_ONNX_PARSER_H
#include "NvInfer.h"
#include <stddef.h>
#include <vector>
//!
//! \file NvOnnxParser.h
//!
//! This is the API for the ONNX Parser
//!
#define NV_ONNX_PARSER_MAJOR 0
#define NV_ONNX_PARSER_MINOR 1
#define NV_ONNX_PARSER_PATCH 0
static const int NV_ONNX_PARSER_VERSION = ((NV_ONNX_PARSER_MAJOR * 10000) + (NV_ONNX_PARSER_MINOR * 100) + NV_ONNX_PARSER_PATCH);
//! \typedef SubGraph_t
//!
//! \brief The data structure containing the parsing capability of
//! a set of nodes in an ONNX graph.
//!
using SubGraph_t = std::pair<std::vector<size_t>, bool>;
//! \typedef SubGraphCollection_t
//!
//! \brief The data structure containing all SubGraph_t partitioned
//! out of an ONNX graph.
//!
using SubGraphCollection_t = std::vector<SubGraph_t>;
class onnxTensorDescriptorV1;
//!
//! \namespace nvonnxparser
//!
//! \brief The TensorRT ONNX parser API namespace
//!
namespace nvonnxparser
{
template <typename T>
inline int32_t EnumMax();
/** \enum ErrorCode
*
* \brief the type of parser error
*/
enum class ErrorCode : int
{
kSUCCESS = 0,
kINTERNAL_ERROR = 1,
kMEM_ALLOC_FAILED = 2,
kMODEL_DESERIALIZE_FAILED = 3,
kINVALID_VALUE = 4,
kINVALID_GRAPH = 5,
kINVALID_NODE = 6,
kUNSUPPORTED_GRAPH = 7,
kUNSUPPORTED_NODE = 8
};
template <>
inline int32_t EnumMax<ErrorCode>()
{
return 9;
}
/** \class IParserError
*
* \brief an object containing information about an error
*/
class IParserError
{
public:
/** \brief the error code
*/
virtual ErrorCode code() const = 0;
/** \brief description of the error
*/
virtual const char* desc() const = 0;
/** \brief source file in which the error occurred
*/
virtual const char* file() const = 0;
/** \brief source line at which the error occurred
*/
virtual int line() const = 0;
/** \brief source function in which the error occurred
*/
virtual const char* func() const = 0;
/** \brief index of the ONNX model node in which the error occurred
*/
virtual int node() const = 0;
protected:
virtual ~IParserError() {}
};
/** \class IParser
*
* \brief an object for parsing ONNX models into a TensorRT network definition
*/
class IParser
{
public:
/** \brief Parse a serialized ONNX model into the TensorRT network.
* This method has very limited diagnostic. If parsing the serialized model
* fails for any reason (e.g. unsupported IR version, unsupported opset, etc.)
* it the user responsibility to intercept and report the error.
* To obtain a better diagnostic, use the parseFromFile method below.
*
* \param serialized_onnx_model Pointer to the serialized ONNX model
* \param serialized_onnx_model_size Size of the serialized ONNX model
* in bytes
* \return true if the model was parsed successfully
* \see getNbErrors() getError()
*/
virtual bool parse(void const* serialized_onnx_model,
size_t serialized_onnx_model_size)
= 0;
/** \brief Parse an onnx model file, can be a binary protobuf or a text onnx model
* calls parse method inside.
*
* \param File name
* \param Verbosity Level
*
* \return true if the model was parsed successfully
*
*/
virtual bool parseFromFile(const char* onnxModelFile, int verbosity) = 0;
/** \brief Check whether TensorRT supports a particular ONNX model
*
* \param serialized_onnx_model Pointer to the serialized ONNX model
* \param serialized_onnx_model_size Size of the serialized ONNX model
* in bytes
* \param sub_graph_collection Container to hold supported subgraphs
* \return true if the model is supported
*/
virtual bool supportsModel(void const* serialized_onnx_model,
size_t serialized_onnx_model_size,
SubGraphCollection_t& sub_graph_collection)
= 0;
/** \brief Parse a serialized ONNX model into the TensorRT network
* with consideration of user provided weights
*
* \param serialized_onnx_model Pointer to the serialized ONNX model
* \param serialized_onnx_model_size Size of the serialized ONNX model
* in bytes
* \param weight_count number of user provided weights
* \param weight_descriptors pointer to user provided weight array
* \return true if the model was parsed successfully
* \see getNbErrors() getError()
*/
virtual bool parseWithWeightDescriptors(
void const* serialized_onnx_model, size_t serialized_onnx_model_size,
uint32_t weight_count,
onnxTensorDescriptorV1 const* weight_descriptors)
= 0;
/** \brief Returns whether the specified operator may be supported by the
* parser.
*
* Note that a result of true does not guarantee that the operator will be
* supported in all cases (i.e., this function may return false-positives).
*
* \param op_name The name of the ONNX operator to check for support
*/
virtual bool supportsOperator(const char* op_name) const = 0;
/** \brief destroy this object
*/
virtual void destroy() = 0;
/** \brief Get the number of errors that occurred during prior calls to
* \p parse
*
* \see getError() clearErrors() IParserError
*/
virtual int getNbErrors() const = 0;
/** \brief Get an error that occurred during prior calls to \p parse
*
* \see getNbErrors() clearErrors() IParserError
*/
virtual IParserError const* getError(int index) const = 0;
/** \brief Clear errors from prior calls to \p parse
*
* \see getNbErrors() getError() IParserError
*/
virtual void clearErrors() = 0;
/** \brief Get description of all ONNX weights that can be refitted.
*
* \param weightsNames Where to write the weight names to
* \param layerNames Where to write the layer names to
* \param roles Where to write the roles to
*
* \return The number of weights from the ONNX model that can be refitted
*
* If weightNames or layerNames != nullptr, each written pointer points to a string owned by
* the parser, and becomes invalid when the parser is destroyed
*
* If the same weight is used in multiple TRT layers it will be represented as a new
* entry in weightNames with name <weightName>_x, with x being the number of times the weight
* has been used before the current layer
*/
virtual int getRefitMap(const char** weightNames, const char** layerNames, nvinfer1::WeightsRole* roles) = 0;
protected:
virtual ~IParser() {}
};
} // namespace nvonnxparser
extern "C" TENSORRTAPI void* createNvOnnxParser_INTERNAL(void* network, void* logger, int version);
extern "C" TENSORRTAPI int getNvOnnxParserVersion();
namespace nvonnxparser
{
#ifdef SWIG
inline IParser* createParser(nvinfer1::INetworkDefinition* network,
nvinfer1::ILogger* logger)
{
return static_cast<IParser*>(
createNvOnnxParser_INTERNAL(network, logger, NV_ONNX_PARSER_VERSION));
}
#endif // SWIG
namespace
{
/** \brief Create a new parser object
*
* \param network The network definition that the parser will write to
* \param logger The logger to use
* \return a new parser object or NULL if an error occurred
* \see IParser
*/
#ifdef _MSC_VER
TENSORRTAPI IParser* createParser(nvinfer1::INetworkDefinition& network,
nvinfer1::ILogger& logger)
#else
inline IParser* createParser(nvinfer1::INetworkDefinition& network,
nvinfer1::ILogger& logger)
#endif
{
return static_cast<IParser*>(
createNvOnnxParser_INTERNAL(&network, &logger, NV_ONNX_PARSER_VERSION));
}
} // namespace
} // namespace nvonnxparser
#endif // NV_ONNX_PARSER_H
| 0411c2e605f62c43f80395484ec66b821afe8840 | [
"CMake",
"Markdown",
"Python",
"C",
"C++"
] | 14 | C++ | ttanzhiqiang/onnx-tensorrt_7.2.1 | 950b75ad4ecf478085365d1adbe6e96b5f472074 | eadffbb3d095a7d1b80a4ba3a8451a1174fef7dd |
refs/heads/master | <file_sep># -*- coding:utf-8 -*-
import pytz
def convert_timezone(time_in):
"""
用来将系统自动生成的datetime格式的utc时区时间转化为本地时间
:param time_in: datetime.datetime格式的utc时间
:return:输出仍旧是datetime.datetime格式,但已经转换为本地时间
"""
time_utc = time_in.replace(tzinfo=pytz.timezone('UTC'))
time_local = time_utc.astimezone(pytz.timezone('Asia/Shanghai'))
return time_local
def convert_local_timezone(time_in):
"""
用来将输入的datetime格式的本地时间转化为utc时区时间
:param time_in: datetime.datetime格式的本地时间
:return:输出仍旧是datetime.datetime格式,但已经转换为utc时间
"""
local = pytz.timezone('Asia/Shanghai')
local_dt = local.localize(time_in, is_dst=None)
time_utc = local_dt.astimezone(pytz.utc)
return time_utc
<file_sep>from .user import *
from .user_desc import *
from .org import *
from .depen_user import *
from .notice import *
<file_sep># -*- coding:utf-8 -*-
from fabric.api import run, env, cd, local
from fabric.colors import green
import config
env.hosts = config.evn['hosts']
env.password = config.evn['password']
git_host = config.evn['git_host']
inter_path = '/home/ubuntu/django_inter/bin/'
app_path = '/home/ubuntu/jiu_school_back_end/'
host = '0.0.0.0:8000'
def update(drop_data=None):
local('git push', capture=False, shell=None)
with cd(app_path):
try:
run('pkill python')
finally:
run('git pull ' + git_host)
if drop_data is not None:
run('mysql -u root')
run(inter_path + 'pip install' + ' -r requirement.txt')
run(inter_path + 'python ' + app_path + 'src/manage.py' + ' migrate')
run('nohup ' + inter_path + 'python ' + app_path + 'src/manage.py' +' runserver ' + host)
def init():
with cd(app_path + 'src'):
run(inter_path + 'python ' + app_path + 'src/manage.py' + ' test' + ' education/')
run(inter_path + 'python ' + app_path + 'src/manage.py' + ' test' + ' question/')<file_sep>from __future__ import unicode_literals
from django.shortcuts import render, Http404, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from question import models as question_models
from education import models as education_models
@login_required
def index(request):
return render(request, 'question/index.html', {'user': request.user})
@login_required
def select_subject(request, goto):
return render(request,
'question/select_subject.html',
{
'subjects': question_models.CodeSubject.objects.all(),
'goto': goto
})
@login_required
def select_charpter(request, subject_id, goto):
if request.method == 'GET':
if goto not in ['question', 'assignment']:
raise Http404
return render(request,
'question/select_charpter.html',
{
'subject_id': subject_id,
'goto': goto,
'nodes': question_models.Charpter.objects.filter(subject_id=subject_id),
})
if request.method == 'POST':
charpter_id = request.POST.get('charpter_id', None)
if charpter_id:
if goto == 'question':
return redirect(add_question, subject_id, charpter_id)
elif goto == 'assignment':
return redirect(add_assignment, subject_id, charpter_id)
else:
raise Http404
else:
return render(request,
'question/select_charpter.html',
{
'subject_id': subject_id,
'goto': goto,
'nodes': question_models.Charpter.objects.filter(subject_id=subject_id),
'next': True
})
@login_required
def add_question(request, subject_id, charpter_id):
data = {
'charpter': get_object_or_404(question_models.Charpter, pk=subject_id),
'subject': get_object_or_404(question_models.CodeSubject, pk=charpter_id),
'content_type': question_models.CodeQuesthionType.objects.all(),
'answer_type': question_models.CodeContextType.objects.all()
}
if request.method == 'GET':
return render(request, 'question/add_question.html', data)
elif request.method == 'POST':
content = request.POST.get('content', '')
question_type = get_object_or_404(
question_models.CodeQuesthionType, pk=request.POST.get('question_type', None))
answer_type = get_object_or_404(
question_models.CodeContextType, pk=request.POST.get('answer_type', None))
difficultly = int(request.POST.get('difficultly', 1))
solve = request.POST.get('solve', u'')
owner = education_models.UserOrg.objects.filter(
user=request.user)[0].org
library = question_models.Library.objects.filter(owner=owner)[0]
question = question_models.Question(
charpter=data['charpter'], content=content, type=question_type,
owner=owner, answer_type=answer_type, difficultly=difficultly,
solve=solve, created_by=request.user, edit_by=None, library=library)
question.save()
data['succeed'] = True
return render(request, 'question/add_question.html', data)
@login_required
def add_assignment(request, subject_id, charpter_id):
subject = get_object_or_404(question_models.CodeSubject, pk=subject_id)
charpter = get_object_or_404(question_models.Charpter, pk=charpter_id)
return render(request, 'question/add_assignment.html', {'charpter': charpter, 'subject': subject})
<file_sep># -*- coding:utf-8 -*-
from django.contrib.auth.models import User
from rest_framework import viewsets
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.response import Response
from education.models import Profile, Org, Notice, \
NoticeTo, UserOrg, Version, KeyTeacher, KeySchool
from education.api.serializers import UserSerializers, ProfileSerializers, \
OrgSerializers, NoticeSerializers, VersionSerializers, KeyTeacherSerializers, \
KeySchoolSerializers, UserOrgSerializers
from education.utils import convert_timezone
class UsersViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializers
def list(self, request, *args, **kwargs):
queryset = User.objects.all()
serializer = UserSerializers(queryset, many=True)
return Response(serializer.data)
class CreateToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
try:
token = Token.objects.get(user=user)
token.delete()
finally:
token = Token.objects.create(user=user)
return Response({'token': token.key,
'id': token.user_id})
class UsersProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
serializer_class = ProfileSerializers
class OrgViewSet(viewsets.ModelViewSet):
queryset = Org.objects.all()
serializer_class = OrgSerializers
class NoticeViewSet(viewsets.ModelViewSet):
queryset = Notice.objects.all()
serializer_class = NoticeSerializers
def list(self, request, *args, **kwargs):
user_notice = []
notices_to_org = []
notices_to_user = NoticeTo.objects.filter(user=request.user)
for i in notices_to_user:
user_notice.append(i.notice)
user_orgs = UserOrg.objects.filter(user=request.user)
for j in user_orgs:
tem = NoticeTo.objects.filter(org=j.org)
for t in tem:
notices_to_org.append(t.notice)
all_notice = user_notice + notices_to_org
for notice in all_notice:
notice.created_date = convert_timezone(notice.created_date)
serializer = NoticeSerializers(set(all_notice), many=True)
return Response(serializer.data)
class VersionViewSet(viewsets.ModelViewSet):
queryset = Version.objects.all()
serializer_class = VersionSerializers
def list(self, request, *args, **kwargs):
queryset = Version.objects.all().last()
serializer = VersionSerializers(queryset)
return Response(serializer.data)
class KeyTeacherViewSet(viewsets.ModelViewSet):
queryset = KeyTeacher.objects.all()
serializer_class = KeyTeacherSerializers
class KeySchoolViewSet(viewsets.ModelViewSet):
queryset = KeySchool.objects.all()
serializer_class = KeySchoolSerializers
class KlassesViewSet(viewsets.ReadOnlyModelViewSet):
queryset = UserOrg.objects.all()
serializer_class = UserOrgSerializers
def list(self, request, *args, **kwargs):
queryset = self.queryset.filter(user=request.user, is_admin=True)
serializer = self.serializer_class(queryset, many=True)
return Response(serializer.data)
<file_sep># -*- coding:utf-8 -*-
from django.test import TestCase
from django.contrib.auth.models import User
from question import models as question_models
from education import models as eduction_models
# 题库
library = question_models.Library(
library_name=u'初级题库', owner=eduction_models.Org.objects.get(pk=1))
library.save()
# 问题类型
questhion_types = (u'主观题', u'客观题')
for i in questhion_types:
questhion_type = question_models.CodeQuesthionType(questhion_type_name=i)
questhion_type.save()
# 回答类型
context_types = (u'文字', u'图片')
for i in context_types:
context_type = question_models.CodeContextType(context_type_name=i)
context_type.save()
# 科目
subjects = (u'语文',
u'数学',
u'英语',
u'物理',
u'化学',
u'生物',
u'历史',
u'地理',
u'政治')
for i in subjects:
subject = question_models.CodeSubject(subject_name=i)
subject.save()
# 章节
charpter = question_models.Charpter(title=u'第一章', subject=question_models.CodeSubject.objects.get(pk=1),
parent=None, owner=eduction_models.Org.objects.get(pk=1))
charpter.save()
# 知识点
knowege_point = question_models.KnowegePoint(title=u'三角函数', parent=None, created_by=User.objects.get(pk=1),
owner=eduction_models.Org.objects.get(pk=1))
knowege_point.save()
# 作业状态
assignment_status = [u'草稿', u'正式', u'作废']
for i in assignment_status:
assignment_statu = question_models.CodeAssignmentStatus(status_name=i)
assignment_statu.save()
# 作业类型
assignment_types = [u'日常作业', u'游学名校', u'寒假作业']
for i in assignment_types:
assignment_type = question_models.CodeAssignmentType(
assignment_type_name=i)
assignment_type.save()
# 作业提交状态
submit_status = (u'完成', u'草稿')
for i in submit_status:
submit_statu = question_models.CodeSubmitStatus(submit_status_name=i)
submit_statu.save()
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('education', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='CodeOrgType',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('org_type_name', models.CharField(max_length=10)),
],
),
migrations.AddField(
model_name='userorg',
name='is_admin',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='org',
name='type',
field=models.ForeignKey(db_column=b'type', verbose_name=b'\xe7\xbb\x84\xe7\xbb\x87\xe7\xb1\xbb\xe5\x9e\x8b', to='education.CodeOrgType'),
),
]
<file_sep># -*- coding:utf-8 -*-
from django.db.models import Model, ForeignKey, TextField, DateTimeField, \
SmallIntegerField, NullBooleanField, CharField
from django.contrib.auth.models import User
from .question_desc import Charpter, CodeQuesthionType, CodeContextType, Library
from education.models import Org
class Question(Model):
ref = ForeignKey('self', db_column='ref_id', blank=True,
null=True, related_name='distortion', verbose_name='原题')
charpter = ForeignKey(Charpter, db_column='charpter_id', related_name='questions', verbose_name='归属章节')
content = TextField(verbose_name='题目内容')
type = ForeignKey(CodeQuesthionType, db_column='type', related_name='questions', verbose_name='题目类型')
owner = ForeignKey(Org, db_column='owner', related_name='own_questions', verbose_name='所有人')
answer = TextField(blank=True, default='', verbose_name='回答')
answer_type = ForeignKey(CodeContextType, db_column='answer_type', verbose_name='答题类型')
difficultly = SmallIntegerField(default=1, verbose_name='难度')
solve = TextField(blank=True, default='', verbose_name='解析')
created_date = DateTimeField(auto_now_add=True)
created_by = ForeignKey(User, db_column='created_by', related_name='created_questions', verbose_name='创建者')
edit_by = ForeignKey(User, db_column='edit_by', related_name='edited_questions',
null=True, blank=True, verbose_name='编辑者')
status = SmallIntegerField(default=1, verbose_name='状态')
share = NullBooleanField(null=True, default=False, verbose_name='是否可以分享')
library = ForeignKey(Library, db_column='library_id', verbose_name='图书馆')
comments = CharField(max_length=500, blank=True, verbose_name='备注')
class Meta:
app_label = 'question'
db_table = 'questions'
verbose_name = '题目'
verbose_name_plural = '题目'
def __unicode__(self):
return u'{0}...'.format(self.content[:10])
class Material(Model):
ref = ForeignKey('self', db_column='ref_id', null=True, blank=True, verbose_name='原材料')
title = CharField(max_length=20, blank=True, verbose_name='标题')
content = TextField(verbose_name='正文')
created_by = ForeignKey(User, related_name='created_materials', db_column='created_by', verbose_name='创建者')
edit_by = ForeignKey(User, related_name='edited_materials', db_column='edit_by', null=True, verbose_name='编辑者')
created_date = DateTimeField(auto_now_add=True, verbose_name='创建日期')
comments = TextField(blank=True, verbose_name='备注')
class Meta:
app_label = 'question'
db_table = 'materials'
verbose_name = '材料'
verbose_name_plural = '材料'
def __unicode__(self):
return u'{0}'.format(self.title)
<file_sep>const example = {
url: "http://127.0.0.1:5000", // 请求地址
method: "GET", // 请求方式['GET', 'POST']
args: {
// GET请求时带的参数, POST 时即为 body
id: 1
},
response: {
// 后端返回值
ok: true,
error_code: 1024, // 1000至2000之间
error_desc: "密码不正确", // 错误说明
id: 1,
name: "语文"
}
}
//发送手机验证码
//注:手机验证码只生成不发送,随着接口带回
//备注:username即phone
//以下所有需要用到phone的地方全部用username代替
// var getVcode =
// {
// url:'',
// method:'',
// args:
// {
// phone:''
// },
// response:
// {
// ok:true,
// error_code:'',
// error_desc:'',
// vcode:''
// }
// }
获取 token
var getToken =
{
url:'http://192.168.3.11:8000/api/v1/get-token',
method:'post',
args:
{
username:'',
password:'' //普通的密码
},
response:
{
token: '<KEY>'
}
}
交互方式:
POST 账户密码到 getToken,获取到:
{
token: '<KEY>'
}
即为登录成功,其它都是登录失败,每成功一次后端 token 变化一次,旧 token 作废
取得 token 后
//伪代码如下:
header.set('Authorization') = 'Token ' + getToken.token //注意: Token 后面有一个空格
每次 get, post 都带上这个 header 即可
所有的 API 都在 'http://192.168.3.11:8000/api/v1/' 查看
原则上此文件应该不需要再更新
//用户注册
// var register =
// {
// url:'',
// method:'post',
// args:
// {
// username:'',
// password:'', //<PASSWORD>
// vcode:'' //手机验证码
// },
// response:
// {
// ok:true,
// error_code:'',
// error_desc:'',
// user:{}//user对象
// }
// }
//用户忘记密码
// var forgetpassword =
// {
// url:'',
// method:'post',
// args:
// {
// username:'',
// vcode:'' //手机验证码
// },
// response:
// {
// ok:true,
// error_code:'',
// error_desc:'',
// token: '' //本次重设密码的token
// }
// }
// //用户重设密码
// var resetpassword =
// {
// url:'',
// method:'post',
// args:
// {
// username:'',
// old_password:'',//<PASSWORD>
// new_password:'', //<PASSWORD>
// token:'' //用户忘记密码所带token,有时限
// },
// response:
// {
// ok:true,
// error_code:'',
// error_desc:'',
// }
// }
<file_sep># -*- coding:utf-8 -*-
from rest_framework import permissions
from education import models as education_models
from question import models as question_models
class HasHomeWork(permissions.BasePermission):
def has_permission(self, request, view):
user_orgs_relation = education_models.UserOrg.objects.filter(user=request.user)<file_sep># jiu_school_back_end
## API.json使用说明
**每次修改 API.json 都应该 commit 一次以方便彼此有些什么需求**
> **name** 字段可以没有
> **url** 字段由后端填写,**其它字段全部由前端填写**
> **method** 为 HTTP 方法
> **args** 为 GET 时带的参数或者 POST 时的 body
> **response** 为前端期待的返回值
<file_sep>django == 1.8.2
fabric == 1.11.1
djangorestframework == 3.3.3
MySQL-python == 1.2.5
pytz == 2016.6.1
django-bootstrap3 == 7.0.1
django-admin-bootstrapped == 2.5.7
django-mptt == 0.8.5
<file_sep>default_app_config = 'question.app_config.QuestionConfig'
<file_sep># -*- coding:utf-8 -*-
from django.db.models import Model, CharField
class CodeRole(Model):
# 用户角色表
role_name = CharField(max_length=20, blank=True, default=u'学生', verbose_name='身份')
comments = CharField(max_length=500, blank=True, verbose_name='备注')
class Meta:
app_label = 'education'
db_table = 'code_role'
verbose_name = '用户身份'
verbose_name_plural = '用户身份'
def __unicode__(self):
return u'{0}'.format(self.role_name)
class CodeAccountType(Model):
# 用户账户类型表
acc_type_name = CharField(max_length=20, default=u'手机号', verbose_name='帐号类型')
comments = CharField(max_length=500, blank=True, verbose_name='备注')
class Meta:
app_label = 'education'
db_table = 'code_account_type'
verbose_name = '用户账号类型'
verbose_name_plural = '用户账号类型'
def __unicode__(self):
return u'{0}'.format(self.acc_type_name)
class CodeUserStatus(Model):
# 账户状态表
user_state_name = CharField(max_length=20, default=u'在线', verbose_name='状态')
class Meta:
app_label = 'education'
db_table = 'code_user_status'
verbose_name = '用户帐号状态'
verbose_name_plural = '用户帐号状态'
def __unicode__(self):
return u'{0}'.format(self.user_state_name)
<file_sep>from django.contrib import admin
from .models import Profile, UserOrg, Version, KeyTeacher, CodeGrade
from .models.user_desc import CodeUserStatus, CodeAccountType, CodeRole
from .models.org import Org, Area, CodeEduPeriod, KeySchool
from .models.notice import Notice, NoticeTo
@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
pass
admin.site.register(CodeGrade)
admin.site.register(KeySchool)
admin.site.register(KeyTeacher)
admin.site.register(Version)
admin.site.register(UserOrg)
admin.site.register(CodeUserStatus)
admin.site.register(CodeAccountType)
admin.site.register(CodeRole)
admin.site.register(Org)
admin.site.register(Area)
admin.site.register(CodeEduPeriod)
admin.site.register(Notice)
admin.site.register(NoticeTo)
<file_sep># -*- coding:utf-8 -*-
from django.test import TestCase
from django.utils import timezone
from .models.user_desc import CodeRole, CodeAccountType, CodeUserStatus
from django.contrib.auth.models import User
from .models.user import Profile, UserOrg, KeyTeacher
from .models.org import Area, CodeEduPeriod, Org, KeySchool, CodeOrgType
from .models.notice import Notice, NoticeTo
# init Users
User.objects.create_superuser('root', '<EMAIL>', 'root')
User.objects.create_user('qzw', '<EMAIL>', 'root')
User.objects.create_user('teacher', '<EMAIL>', 'teacher')
User.objects.create_user('student', '<EMAIL>', 'student')
# init User 身份数据
roles = [u'教务', u'教师', u'学生']
for r in roles:
role = CodeRole(role_name=r)
role.save()
# init User 账户类型
account_type = CodeAccountType()
account_type.save()
# init User 账户现在的状态
user_status = CodeUserStatus()
user_status.save()
# init Area 数据
area = Area(parent=None, name=u'衡阳县', short_name=u'衡阳', )
area.save()
# init EduPeriod 学段数据
edu_period = CodeEduPeriod()
edu_period.save()
# init OrgType
types = [u'学校', u'班级', u'小组']
for i in types:
ty_pe = CodeOrgType(org_type_name=i)
ty_pe.save()
# init Org 组织数据
org = Org(parent=None, area=area, name=u'衡阳县第一中学',
edu_period=edu_period, type_id=1)
org.save()
# init Profile 用户配置文件
for i in [2, 3, 4]:
profile = Profile(user=User.objects.get(pk=i), account_id='13788740727', account_type=account_type,
role_id=i - 1, username='qzw', login_name='lxvc', md5passwdstr='md5',
status=user_status, email='<EMAIL>', phone='13788740727',
birthday=timezone.now(), idcardnum='...', address=u'中国湖南省衡阳市衡阳县渣江镇',
intro=u'成绩不错', qq='403381161', wechat='403381161', last_login_date=timezone.now(),
last_status_change_date=timezone.now(), head_pic_url='/static/avatar.png')
profile.save()
# init UserOrg 个人和组织的关系数据
user_org = UserOrg(user=User.objects.get(pk=2), org=org)
user_org.save()
# init Notice 通知数据
notice = Notice(title=u'十一放假通知', created_by=User.objects.get(pk=2), created_date=timezone.now(),
content=u'十月一号开始放假七天')
notice.save()
# init NoticeTo 通知和用户,组织多对多表
notice_to = NoticeTo(notice=notice, org=org)
notice_to.save()
# init Keyschool 名校数据
school = KeySchool(org=org)
school.save()
# init Keyteacher 名师数据
teacher = KeyTeacher(teacher=User.objects.get(pk=1), details=u'湖南特级教师')
teacher.save()
<file_sep># -*- coding:utf-8 -*-
from django.apps import AppConfig
class EducationConfig(AppConfig):
name = 'education'
verbose_name = u'用户配置'
<file_sep>from .question_desc import *
from .question import *
from .depen_questhion import *
from .assignment import *
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import mptt.fields
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('education', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Assignment',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField(max_length=30, verbose_name=b'\xe5\x90\x8d\xe7\xa7\xb0')),
('questhion_num', models.IntegerField(default=2, verbose_name=b'\xe9\xa2\x98\xe7\x9b\xae\xe6\x95\xb0\xe9\x87\x8f')),
('published_count', models.IntegerField(default=0, verbose_name=b'\xe5\x8f\x91\xe5\xb8\x83\xe6\x95\xb0')),
('created_date', models.DateTimeField(auto_now_add=True, verbose_name=b'\xe5\x88\x9b\xe5\xbb\xba\xe6\x97\xa5\xe6\x9c\x9f')),
('comments', models.CharField(max_length=500, verbose_name=b'\xe5\xa4\x87\xe6\xb3\xa8', blank=True)),
],
options={
'db_table': 'assignment',
'verbose_name': '\u4f5c\u4e1a',
'verbose_name_plural': '\u4f5c\u4e1a',
},
),
migrations.CreateModel(
name='AssignmentPublish',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('share', models.NullBooleanField(default=False, verbose_name=b'\xe6\x98\xaf\xe5\x90\xa6\xe5\x88\x86\xe4\xba\xab')),
('created_date', models.DateTimeField(auto_now_add=True, verbose_name=b'\xe5\x88\x9b\xe5\xbb\xba\xe6\x97\xb6\xe9\x97\xb4')),
('publish_date', models.DateTimeField(auto_now_add=True, verbose_name=b'\xe6\x8c\x87\xe5\xae\x9a\xe5\x8f\x91\xe5\xb8\x83\xe6\x97\xa5\xe6\x9c\x9f')),
('submit_date_start', models.DateTimeField(auto_now_add=True, verbose_name=b'\xe6\x9c\x80\xe6\x97\xa9\xe6\x8f\x90\xe4\xba\xa4\xe6\x97\xb6\xe9\x97\xb4')),
('submit_date_end', models.DateTimeField(verbose_name=b'\xe6\x9c\x80\xe6\x99\x9a\xe6\x8f\x90\xe4\xba\xa4\xe6\x97\xb6\xe9\x97\xb4')),
('comments', models.CharField(max_length=500, verbose_name=b'\xe5\xa4\x87\xe6\xb3\xa8', blank=True)),
('assignment', models.ForeignKey(db_column=b'assignment_id', verbose_name=b'\xe4\xbd\x9c\xe4\xb8\x9a', to='question.Assignment')),
('publisher', models.ForeignKey(db_column=b'publisher', verbose_name=b'\xe5\x8f\x91\xe5\xb8\x83\xe4\xba\xba', to=settings.AUTH_USER_MODEL)),
('reciver_org', models.ForeignKey(db_column=b'reciver_org', verbose_name=b'\xe6\x8e\xa5\xe6\x94\xb6\xe7\xbb\x84\xe7\xbb\x87', to='education.Org')),
],
options={
'db_table': 'assignment_publish',
'verbose_name': '\u4f5c\u4e1a\u53d1\u5e03\u60c5\u51b5',
'verbose_name_plural': '\u4f5c\u4e1a\u53d1\u5e03\u60c5\u51b5',
},
),
migrations.CreateModel(
name='AssignmentQuestions',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('score', models.FloatField()),
('extra', models.CharField(default=b'', max_length=500, blank=True)),
('assignment', models.ForeignKey(to='question.Assignment', db_column=b'assignment_id')),
],
options={
'db_table': 'assignment_questions',
'verbose_name': '\u4f5c\u4e1a\u4e0e\u9898\u76ee',
'verbose_name_plural': '\u4f5c\u4e1a\u4e0e\u9898\u76ee',
},
),
migrations.CreateModel(
name='AssignmentSubmit',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('context', models.TextField(verbose_name=b'\xe5\x9b\x9e\xe7\xad\x94\xe5\x86\x85\xe5\xae\xb9')),
('start_date', models.DateTimeField(verbose_name=b'\xe5\xbc\x80\xe5\xa7\x8b\xe6\x97\xb6\xe9\x97\xb4', blank=True)),
('submit_date', models.DateTimeField(verbose_name=b'\xe6\x8f\x90\xe4\xba\xa4\xe6\x97\xb6\xe9\x97\xb4', blank=True)),
('comment', models.CharField(max_length=500, verbose_name=b'\xe5\xa4\x87\xe6\xb3\xa8', blank=True)),
('assignment_publish', models.ForeignKey(db_column=b'assignment_publish_id', verbose_name=b'\xe5\x8f\x91\xe5\xb8\x83\xe7\x9a\x84\xe4\xbd\x9c\xe4\xb8\x9a', to='question.AssignmentPublish')),
],
options={
'db_table': 'assignment_submit',
'verbose_name': '\u63d0\u4ea4\u7684\u4f5c\u4e1a',
'verbose_name_plural': '\u63d0\u4ea4\u7684\u4f5c\u4e1a',
},
),
migrations.CreateModel(
name='AssignmentSubmitDetail',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('context', models.CharField(max_length=500, verbose_name=b'\xe7\xad\x94\xe9\xa2\x98\xe5\x86\x85\xe5\xae\xb9', blank=True)),
('checking_status', models.CharField(max_length=20, verbose_name=b'\xe6\x89\xb9\xe6\x94\xb9\xe7\x8a\xb6\xe6\x80\x81', blank=True)),
('checking_context', models.CharField(max_length=500, verbose_name=b'\xe6\x89\xb9\xe6\x94\xb9\xe5\x86\x85\xe5\xae\xb9', blank=True)),
('checking_date', models.DateTimeField(auto_now=True, verbose_name=b'\xe6\x89\xb9\xe6\x94\xb9\xe6\x97\xb6\xe9\x97\xb4')),
('checking_comments', models.CharField(max_length=500, verbose_name=b'\xe6\x89\xb9\xe6\x94\xb9\xe5\xa4\x87\xe6\xb3\xa8', blank=True)),
('status', models.CharField(max_length=20, verbose_name=b'\xe7\x8a\xb6\xe6\x80\x81', blank=True)),
('checking_by', models.ForeignKey(db_column=b'checking_by', verbose_name=b'\xe6\x89\xb9\xe6\x94\xb9\xe4\xba\xba', to=settings.AUTH_USER_MODEL)),
],
options={
'db_table': 'assignment_submit_detail',
'verbose_name': '\u63d0\u4ea4\u4f5c\u4e1a\u8be6\u60c5',
'verbose_name_plural': '\u63d0\u4ea4\u4f5c\u4e1a\u8be6\u60c5',
},
),
migrations.CreateModel(
name='Charpter',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField(max_length=200, verbose_name=b'\xe7\xab\xa0\xe8\x8a\x82')),
('comment', models.CharField(default=b'', max_length=500, verbose_name=b'\xe5\xa4\x87\xe6\xb3\xa8', blank=True)),
('lft', models.PositiveIntegerField(editable=False, db_index=True)),
('rght', models.PositiveIntegerField(editable=False, db_index=True)),
('tree_id', models.PositiveIntegerField(editable=False, db_index=True)),
('level', models.PositiveIntegerField(editable=False, db_index=True)),
('owner', models.ForeignKey(db_column=b'owner', verbose_name=b'\xe6\x8b\xa5\xe6\x9c\x89\xe8\x80\x85', to='education.Org')),
('parent', mptt.fields.TreeForeignKey(related_name='children', db_column=b'parent_id', blank=True, to='question.Charpter', null=True, verbose_name=b'\xe7\x88\xb6\xe7\xab\xa0\xe8\x8a\x82')),
],
options={
'db_table': 'charpter',
'verbose_name': '\u7ae0\u8282',
'verbose_name_plural': '\u7ae0\u8282',
},
),
migrations.CreateModel(
name='CodeAssignmentStatus',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('status_name', models.CharField(default=b'\xe8\x8d\x89\xe7\xa8\xbf', max_length=20, verbose_name=b'\xe7\x8a\xb6\xe6\x80\x81')),
],
options={
'db_table': 'code_assignment_status',
'verbose_name': '\u4f5c\u4e1a\u72b6\u6001',
'verbose_name_plural': '\u4f5c\u4e1a\u72b6\u6001',
},
),
migrations.CreateModel(
name='CodeAssignmentType',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('assignment_type_name', models.CharField(max_length=50, verbose_name=b'\xe7\xb1\xbb\xe5\x9e\x8b')),
],
options={
'db_table': 'code_assignment_type',
'verbose_name': '\u4f5c\u4e1a\u7c7b\u578b',
'verbose_name_plural': '\u4f5c\u4e1a\u7c7b\u578b',
},
),
migrations.CreateModel(
name='CodeContextType',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('context_type_name', models.CharField(max_length=20, verbose_name=b'\xe7\xad\x94\xe6\xa1\x88\xe7\xb1\xbb\xe5\x9e\x8b')),
],
options={
'db_table': 'code_context_type',
'verbose_name': '\u7b54\u6848\u7c7b\u578b',
'verbose_name_plural': '\u7b54\u6848\u7c7b\u578b',
},
),
migrations.CreateModel(
name='CodeQuesthionType',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('questhion_type_name', models.CharField(max_length=20, verbose_name=b'\xe9\xa2\x98\xe7\x9b\xae\xe7\xb1\xbb\xe5\x9e\x8b')),
],
options={
'db_table': 'code_questhion_type',
'verbose_name': '\u9898\u76ee\u7c7b\u578b',
'verbose_name_plural': '\u9898\u76ee\u7c7b\u578b',
},
),
migrations.CreateModel(
name='CodeSubject',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('subject_name', models.CharField(max_length=20, verbose_name=b'\xe7\xa7\x91\xe7\x9b\xae')),
],
options={
'db_table': 'code_subject',
'verbose_name': '\u79d1\u76ee',
'verbose_name_plural': '\u79d1\u76ee',
},
),
migrations.CreateModel(
name='CodeSubmitStatus',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('submit_status_name', models.CharField(max_length=20, verbose_name=b'\xe7\x8a\xb6\xe6\x80\x81')),
],
options={
'db_table': 'code_submit_status',
'verbose_name': '\u4f5c\u4e1a\u63d0\u4ea4\u72b6\u6001',
'verbose_name_plural': '\u4f5c\u4e1a\u63d0\u4ea4\u72b6\u6001',
},
),
migrations.CreateModel(
name='KnowegePoint',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField(max_length=100, verbose_name=b'\xe7\x9f\xa5\xe8\xaf\x86\xe7\x82\xb9\xe5\x90\x8d\xe5\xad\x97')),
('ref_count', models.IntegerField(default=0, verbose_name=b'\xe5\xbc\x95\xe7\x94\xa8\xe6\xac\xa1\xe6\x95\xb0')),
('created_date', models.DateTimeField(auto_now_add=True, verbose_name=b'\xe5\x88\x9b\xe5\xbb\xba\xe6\x97\xb6\xe9\x97\xb4')),
('lft', models.PositiveIntegerField(editable=False, db_index=True)),
('rght', models.PositiveIntegerField(editable=False, db_index=True)),
('tree_id', models.PositiveIntegerField(editable=False, db_index=True)),
('level', models.PositiveIntegerField(editable=False, db_index=True)),
('created_by', models.ForeignKey(related_name='created_knowege_points', db_column=b'created_by', verbose_name=b'\xe5\x88\x9b\xe5\xbb\xba\xe8\x80\x85', to=settings.AUTH_USER_MODEL)),
('owner', models.ForeignKey(related_name='own_knowege_points', db_column=b'owner', verbose_name=b'\xe6\x8b\xa5\xe6\x9c\x89\xe8\x80\x85', to='education.Org')),
('parent', mptt.fields.TreeForeignKey(related_name='children', db_column=b'parent_id', blank=True, to='question.KnowegePoint', null=True, verbose_name=b'\xe7\x88\xb6\xe7\x9f\xa5\xe8\xaf\x86\xe7\x82\xb9')),
],
options={
'db_table': 'knowege_point',
'verbose_name': '\u77e5\u8bc6\u70b9',
'verbose_name_plural': '\u77e5\u8bc6\u70b9',
},
),
migrations.CreateModel(
name='Library',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('library_name', models.CharField(max_length=100, verbose_name=b'\xe5\x90\x8d\xe5\xad\x97')),
('public', models.BooleanField(default=False, verbose_name=b'\xe6\x98\xaf\xe5\x90\xa6\xe5\x85\xac\xe5\xbc\x80')),
('owner', models.ForeignKey(related_name='owner_librarys', db_column=b'owner', verbose_name=b'\xe6\x8b\xa5\xe6\x9c\x89\xe8\x80\x85', to='education.Org')),
],
options={
'db_table': 'library',
'verbose_name': '\u9898\u5e93',
'verbose_name_plural': '\u9898\u5e93',
},
),
migrations.CreateModel(
name='Material',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField(max_length=20, verbose_name=b'\xe6\xa0\x87\xe9\xa2\x98', blank=True)),
('content', models.TextField(verbose_name=b'\xe6\xad\xa3\xe6\x96\x87')),
('created_date', models.DateTimeField(auto_now_add=True, verbose_name=b'\xe5\x88\x9b\xe5\xbb\xba\xe6\x97\xa5\xe6\x9c\x9f')),
('comments', models.TextField(verbose_name=b'\xe5\xa4\x87\xe6\xb3\xa8', blank=True)),
('created_by', models.ForeignKey(related_name='created_materials', db_column=b'created_by', verbose_name=b'\xe5\x88\x9b\xe5\xbb\xba\xe8\x80\x85', to=settings.AUTH_USER_MODEL)),
('edit_by', models.ForeignKey(related_name='edited_materials', db_column=b'edit_by', verbose_name=b'\xe7\xbc\x96\xe8\xbe\x91\xe8\x80\x85', to=settings.AUTH_USER_MODEL, null=True)),
('ref', models.ForeignKey(db_column=b'ref_id', blank=True, to='question.Material', null=True, verbose_name=b'\xe5\x8e\x9f\xe6\x9d\x90\xe6\x96\x99')),
],
options={
'db_table': 'materials',
'verbose_name': '\u6750\u6599',
'verbose_name_plural': '\u6750\u6599',
},
),
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('content', models.TextField(verbose_name=b'\xe9\xa2\x98\xe7\x9b\xae\xe5\x86\x85\xe5\xae\xb9')),
('answer', models.TextField(default=b'', verbose_name=b'\xe5\x9b\x9e\xe7\xad\x94', blank=True)),
('difficultly', models.SmallIntegerField(default=1, verbose_name=b'\xe9\x9a\xbe\xe5\xba\xa6')),
('solve', models.TextField(default=b'', verbose_name=b'\xe8\xa7\xa3\xe6\x9e\x90', blank=True)),
('created_date', models.DateTimeField(auto_now_add=True)),
('status', models.SmallIntegerField(default=1, verbose_name=b'\xe7\x8a\xb6\xe6\x80\x81')),
('share', models.NullBooleanField(default=False, verbose_name=b'\xe6\x98\xaf\xe5\x90\xa6\xe5\x8f\xaf\xe4\xbb\xa5\xe5\x88\x86\xe4\xba\xab')),
('comments', models.CharField(max_length=500, verbose_name=b'\xe5\xa4\x87\xe6\xb3\xa8', blank=True)),
('answer_type', models.ForeignKey(db_column=b'answer_type', verbose_name=b'\xe7\xad\x94\xe9\xa2\x98\xe7\xb1\xbb\xe5\x9e\x8b', to='question.CodeContextType')),
('charpter', models.ForeignKey(related_name='questions', db_column=b'charpter_id', verbose_name=b'\xe5\xbd\x92\xe5\xb1\x9e\xe7\xab\xa0\xe8\x8a\x82', to='question.Charpter')),
('created_by', models.ForeignKey(related_name='created_questions', db_column=b'created_by', verbose_name=b'\xe5\x88\x9b\xe5\xbb\xba\xe8\x80\x85', to=settings.AUTH_USER_MODEL)),
('edit_by', models.ForeignKey(related_name='edited_questions', db_column=b'edit_by', blank=True, to=settings.AUTH_USER_MODEL, null=True, verbose_name=b'\xe7\xbc\x96\xe8\xbe\x91\xe8\x80\x85')),
('library', models.ForeignKey(db_column=b'library_id', verbose_name=b'\xe5\x9b\xbe\xe4\xb9\xa6\xe9\xa6\x86', to='question.Library')),
('owner', models.ForeignKey(related_name='own_questions', db_column=b'owner', verbose_name=b'\xe6\x89\x80\xe6\x9c\x89\xe4\xba\xba', to='education.Org')),
('ref', models.ForeignKey(related_name='distortion', db_column=b'ref_id', blank=True, to='question.Question', null=True, verbose_name=b'\xe5\x8e\x9f\xe9\xa2\x98')),
('type', models.ForeignKey(related_name='questions', db_column=b'type', verbose_name=b'\xe9\xa2\x98\xe7\x9b\xae\xe7\xb1\xbb\xe5\x9e\x8b', to='question.CodeQuesthionType')),
],
options={
'db_table': 'questions',
'verbose_name': '\u9898\u76ee',
'verbose_name_plural': '\u9898\u76ee',
},
),
migrations.CreateModel(
name='QuestionKnowlegePoint',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('knowege_point', models.ForeignKey(db_column=b'knowege_point', verbose_name=b'\xe7\x9f\xa5\xe8\xaf\x86\xe7\x82\xb9', to='question.KnowegePoint')),
('questhion', models.ForeignKey(db_column=b'questhion_id', verbose_name=b'\xe9\xa2\x98\xe7\x9b\xae', to='question.Question')),
],
options={
'db_table': 'question_knowlege_point',
'verbose_name': '\u9898\u76ee\u548c\u77e5\u8bc6\u70b9\u5bf9\u5e94\u5173\u7cfb',
'verbose_name_plural': '\u9898\u76ee\u548c\u77e5\u8bc6\u70b9\u5bf9\u5e94\u5173\u7cfb',
},
),
migrations.CreateModel(
name='QuestionsDyndifficulty',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('diffcultty', models.IntegerField(default=0, verbose_name=b'\xe9\x9a\xbe\xe5\xba\xa6\xe7\xad\x89\xe7\xba\xa7')),
('calc_date', models.DateTimeField(auto_now_add=True, verbose_name=b'\xe5\x88\x9b\xe5\xbb\xba\xe6\x97\xb6\xe9\x97\xb4')),
('comments', models.CharField(max_length=500, verbose_name=b'\xe5\xa4\x87\xe6\xb3\xa8', blank=True)),
('question', models.ForeignKey(db_column=b'question_id', verbose_name=b'\xe9\xa2\x98\xe7\x9b\xae', to='question.Question')),
],
options={
'db_table': 'questions_dyndifficulty',
'verbose_name': '\u9898\u76ee\u96be\u5ea6',
'verbose_name_plural': '\u9898\u76ee\u96be\u5ea6',
},
),
migrations.CreateModel(
name='WeakPoint',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('created_date', models.DateTimeField(auto_now_add=True)),
('comments', models.CharField(default=b'', max_length=500, blank=True)),
('assignment_publish', models.ForeignKey(db_column=b'assignment_publish_id', verbose_name=b'\xe4\xbd\x9c\xe4\xb8\x9a', to='question.AssignmentPublish')),
('question', models.ForeignKey(db_column=b'question_id', verbose_name=b'\xe9\xa2\x98\xe7\x9b\xae', to='question.Question')),
('user', models.ForeignKey(db_column=b'user_id', verbose_name=b'\xe5\xad\xa6\xe7\x94\x9f', to=settings.AUTH_USER_MODEL)),
],
options={
'db_table': 'weak_point',
'verbose_name': '\u5b66\u751f\u7684\u8584\u5f31\u77e5\u8bc6',
'verbose_name_plural': '\u5b66\u751f\u7684\u8584\u5f31\u77e5\u8bc6',
},
),
migrations.AddField(
model_name='charpter',
name='subject',
field=models.ForeignKey(db_column=b'subject', verbose_name=b'\xe7\xa7\x91\xe7\x9b\xae', to='question.CodeSubject'),
),
migrations.AddField(
model_name='assignmentsubmitdetail',
name='question',
field=models.ForeignKey(db_column=b'question_id', verbose_name=b'\xe9\x97\xae\xe9\xa2\x98', to='question.Question'),
),
migrations.AddField(
model_name='assignmentsubmitdetail',
name='submit',
field=models.ForeignKey(db_column=b'submit_id', verbose_name=b'\xe6\x8f\x90\xe4\xba\xa4', to='question.AssignmentSubmit'),
),
migrations.AddField(
model_name='assignmentsubmit',
name='status',
field=models.ForeignKey(db_column=b'status', verbose_name=b'\xe6\x8f\x90\xe4\xba\xa4\xe7\x8a\xb6\xe6\x80\x81', to='question.CodeSubmitStatus'),
),
migrations.AddField(
model_name='assignmentsubmit',
name='submiter',
field=models.ForeignKey(db_column=b'submiter', verbose_name=b'\xe6\x8f\x90\xe4\xba\xa4\xe4\xba\xba', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='assignmentquestions',
name='question',
field=models.ForeignKey(to='question.Question', db_column=b'question_id'),
),
migrations.AddField(
model_name='assignment',
name='charpter',
field=models.ForeignKey(related_name='assignments', db_column=b'charpter_id', verbose_name=b'\xe6\x89\x80\xe5\xb1\x9e\xe7\xab\xa0\xe8\x8a\x82', to='question.Charpter'),
),
migrations.AddField(
model_name='assignment',
name='created_by',
field=models.ForeignKey(related_name='created_assignment', db_column=b'created_by', verbose_name=b'\xe5\x88\x9b\xe5\xbb\xba\xe8\x80\x85', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='assignment',
name='owner',
field=models.ForeignKey(related_name='own_assignments', db_column=b'owner', verbose_name=b'\xe6\x8b\xa5\xe6\x9c\x89\xe7\xbb\x84\xe7\xbb\x87', to='education.Org'),
),
migrations.AddField(
model_name='assignment',
name='status',
field=models.ForeignKey(db_column=b'status', verbose_name=b'\xe7\x8a\xb6\xe6\x80\x81', to='question.CodeAssignmentStatus'),
),
migrations.AddField(
model_name='assignment',
name='type',
field=models.ForeignKey(db_column=b'type', verbose_name=b'\xe4\xbd\x9c\xe4\xb8\x9a\xe7\xb1\xbb\xe5\x9e\x8b', to='question.CodeAssignmentType'),
),
]
<file_sep># -*- coding:utf-8 -*-
from django.db.models import Model, CharField, EmailField, ForeignKey, DateTimeField, OneToOneField
from .user import Profile
from .user_desc import CodeUserStatus
from django.contrib.auth.models import Permission, Group
class UserPermissions(Model):
# 用户权限表
user = ForeignKey(Profile, db_column='user_id', verbose_name='用户')
permission = ForeignKey(Permission, db_column='permission_id', default=1, verbose_name='权限')
class Meta:
app_label = 'education'
db_table = 'user_permissions'
verbose_name = '用户与权限'
verbose_name_plural = '用户与权限'
def __unicode__(self):
return u'{0}-{1}'.format(self.user.user.username, self.permission.codename)
class UserRelationInfo(Model):
# 用户亲属关系表
user = OneToOneField(Profile, primary_key=True, db_column='user_id', verbose_name='用户')
relation_type = CharField(max_length=10, default='父亲', blank=True, verbose_name='关系')
relation_name = CharField(max_length=50, default='李天一', blank=True, verbose_name='姓名')
relation_phone = CharField(max_length=32, default='13788740727', verbose_name='手机号')
relation_email = EmailField(blank=True, default='<EMAIL>', verbose_name='邮箱')
relation_address = CharField(max_length=200, default='湖南', verbose_name='家庭住址')
comments = CharField(max_length=500, blank=True, verbose_name='备注')
class Meta:
app_label = 'education'
db_table = 'user_relation_info'
verbose_name = '用户亲属关系'
verbose_name_plural = '用户亲属关系'
def __unicode__(self):
return u'{0}-{1}-{2}'.format(self.user.username, self.relation_type, self.relation_name)
class UserStatusChangeLog(Model):
# 用户状态变化表
user = ForeignKey(Profile, db_column='user_id', related_name='statusChange')
old_status = ForeignKey(CodeUserStatus, db_column='old_status', related_name='old')
new_status = ForeignKey(CodeUserStatus, db_column='new_status', related_name='new')
change_date = DateTimeField(blank=True)
resason = CharField(max_length=500, default='我喜欢')
oper = ForeignKey(Profile, db_column='oper', related_name='operator')
class Meta:
app_label = 'education'
db_table = 'user_status_change_log'
class UserGroup(Model):
# 用户权限组关系表
user = ForeignKey(Profile, db_column='user_id')
group = ForeignKey(Group, db_column='group_id')
class Meta:
app_label = 'education'
db_table = 'user_group'
<file_sep># -*- coding:utf-8 -*-
from django.db.models import Model, ForeignKey, CharField, \
IntegerField, DateTimeField, NullBooleanField, TextField, FloatField
from django.contrib.auth.models import User
from education.models import Org
from .question import Question
from .question_desc import Charpter
class CodeAssignmentStatus(Model):
status_name = CharField(max_length=20, default='草稿', verbose_name='状态')
class Meta:
app_label = 'question'
db_table = 'code_assignment_status'
verbose_name = '作业状态'
verbose_name_plural = '作业状态'
def __unicode__(self):
return u'{0}'.format(self.status_name)
class CodeAssignmentType(Model):
assignment_type_name = CharField(max_length=50, verbose_name='类型')
class Meta:
app_label = 'question'
db_table = 'code_assignment_type'
verbose_name = '作业类型'
verbose_name_plural = '作业类型'
def __unicode__(self):
return u'{0}'.format(self.assignment_type_name)
class Assignment(Model):
title = CharField(max_length=30, verbose_name='名称')
questhion_num = IntegerField(default=2, verbose_name='题目数量')
created_by = ForeignKey(User, db_column='created_by', related_name='created_assignment', verbose_name='创建者')
charpter = ForeignKey(Charpter, db_column='charpter_id', related_name='assignments', verbose_name='所属章节')
owner = ForeignKey(Org, db_column='owner', related_name='own_assignments', verbose_name='拥有组织')
status = ForeignKey(CodeAssignmentStatus, db_column='status', verbose_name='状态')
published_count = IntegerField(default=0, verbose_name='发布数')
created_date = DateTimeField(auto_now_add=True, verbose_name='创建日期')
type = ForeignKey(CodeAssignmentType, db_column='type', verbose_name='作业类型')
comments = CharField(max_length=500, blank=True, verbose_name='备注')
class Meta:
app_label = 'question'
db_table = 'assignment'
verbose_name = '作业'
verbose_name_plural = '作业'
def __unicode__(self):
return u'{0}'.format(self.title)
class AssignmentQuestions(Model):
assignment = ForeignKey(Assignment, db_column='assignment_id')
question = ForeignKey(Question, db_column='question_id')
score = FloatField()
extra = CharField(max_length=500, blank=True, default='')
class Meta:
app_label = 'question'
db_table = 'assignment_questions'
verbose_name = '作业与题目'
verbose_name_plural = '作业与题目'
def __unicode__(self):
return u'{0}-{1}'.format(self.assignment.title, self.question.content[:10])
class AssignmentPublish(Model):
assignment = ForeignKey(Assignment, db_column='assignment_id', verbose_name='作业')
publisher = ForeignKey(User, db_column='publisher', verbose_name='发布人')
reciver_org = ForeignKey(Org, db_column='reciver_org', verbose_name='接收组织')
share = NullBooleanField(default=False, verbose_name='是否分享')
created_date = DateTimeField(auto_now_add=True, verbose_name='创建时间')
publish_date = DateTimeField(auto_now_add=True, verbose_name='指定发布日期')
submit_date_start = DateTimeField(auto_now_add=True, verbose_name='最早提交时间')
submit_date_end = DateTimeField(verbose_name='最晚提交时间')
comments = CharField(max_length=500, blank=True, verbose_name='备注')
class Meta:
app_label = 'question'
db_table = 'assignment_publish'
verbose_name = '作业发布情况'
verbose_name_plural = '作业发布情况'
def __unicode__(self):
return u'{0}——{1}'.format(self.publisher.username, self.assignment.title)
class CodeSubmitStatus(Model):
submit_status_name = CharField(max_length=20, verbose_name='状态')
class Meta:
app_label = 'question'
db_table = 'code_submit_status'
verbose_name = '作业提交状态'
verbose_name_plural = '作业提交状态'
def __unicode__(self):
return u'{0}'.format(self.submit_status_name)
class AssignmentSubmit(Model):
assignment_publish = ForeignKey(AssignmentPublish, db_column='assignment_publish_id', verbose_name='发布的作业')
context = TextField(verbose_name='回答内容')
submiter = ForeignKey(User, db_column='submiter', verbose_name='提交人')
status = ForeignKey(CodeSubmitStatus, db_column='status', verbose_name='提交状态')
start_date = DateTimeField(blank=True, verbose_name='开始时间')
submit_date = DateTimeField(blank=True, verbose_name='提交时间')
comment = CharField(max_length=500, blank=True, verbose_name='备注')
class Meta:
app_label = 'question'
db_table = 'assignment_submit'
verbose_name = '提交的作业'
verbose_name_plural = '提交的作业'
def __unicode__(self):
return u'{0}'.format(self.context[:10])
class AssignmentSubmitDetail(Model):
submit = ForeignKey(AssignmentSubmit, db_column='submit_id', verbose_name='提交')
question = ForeignKey(Question, db_column='question_id', verbose_name='问题')
context = CharField(max_length=500, blank=True, verbose_name='答题内容')
checking_status = CharField(max_length=20, blank=True, verbose_name='批改状态')
checking_context = CharField(max_length=500, blank=True, verbose_name='批改内容')
checking_date = DateTimeField(auto_now=True, verbose_name='批改时间')
checking_by = ForeignKey(User, db_column='checking_by', verbose_name='批改人')
checking_comments = CharField(max_length=500, blank=True, verbose_name='批改备注')
status = CharField(max_length=20, blank=True, verbose_name='状态')
class Meta:
app_label = 'question'
db_table = 'assignment_submit_detail'
verbose_name = '提交作业详情'
verbose_name_plural = '提交作业详情'
def __unicode__(self):
return u'{0}--{1}--{2}'.format(self.submit.submiter.username, self.question.content[:10], self.context[:10])
class WeakPoint(Model):
user = ForeignKey(User, db_column='user_id', verbose_name='学生')
question = ForeignKey(Question, db_column='question_id', verbose_name='题目')
assignment_publish = ForeignKey(AssignmentPublish, db_column='assignment_publish_id', verbose_name='作业')
created_date = DateTimeField(auto_now_add=True)
comments = CharField(max_length=500, blank=True, default='')
class Meta:
app_label = 'question'
db_table = 'weak_point'
verbose_name = '学生的薄弱知识'
verbose_name_plural = '学生的薄弱知识'
def __unicode__(self):
return u'{0}——{1}'.format(self.user.username, self.question.content[:10])
<file_sep>from django.contrib import admin
from question import models
admin.site.register(models.Question)
admin.site.register(models.Material)
admin.site.register(models.Library)
# admin.site.register(models.CodeQuesthionType)
admin.site.register(models.CodeContextType)
admin.site.register(models.CodeSubject)
admin.site.register(models.Charpter)
admin.site.register(models.QuestionsDyndifficulty)
admin.site.register(models.KnowegePoint)
admin.site.register(models.QuestionKnowlegePoint)
admin.site.register(models.WeakPoint)
admin.site.register(models.CodeAssignmentStatus)
admin.site.register(models.CodeAssignmentType)
admin.site.register(models.Assignment)
admin.site.register(models.AssignmentPublish)
admin.site.register(models.CodeSubmitStatus)
admin.site.register(models.AssignmentSubmit)
admin.site.register(models.AssignmentQuestions)
admin.site.register(models.AssignmentSubmitDetail)
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import mptt.fields
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Area',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=50, verbose_name=b'\xe5\x90\x8d\xe7\xa7\xb0', blank=True)),
('short_name', models.CharField(max_length=50, verbose_name=b'\xe7\xae\x80\xe7\xa7\xb0', blank=True)),
('longitude', models.FloatField(default=1.1, null=True, verbose_name=b'\xe7\xbb\x8f\xe5\xba\xa6', blank=True)),
('latitude', models.FloatField(default=2.2, null=True, verbose_name=b'\xe7\xba\xac\xe5\xba\xa6', blank=True)),
('sort', models.IntegerField(default=1, blank=True)),
('status', models.SmallIntegerField(default=2, verbose_name=b'\xe7\x8a\xb6\xe6\x80\x81', blank=True)),
('lft', models.PositiveIntegerField(editable=False, db_index=True)),
('rght', models.PositiveIntegerField(editable=False, db_index=True)),
('tree_id', models.PositiveIntegerField(editable=False, db_index=True)),
('level', models.PositiveIntegerField(editable=False, db_index=True)),
('parent', mptt.fields.TreeForeignKey(related_name='children', db_column=b'parent_id', blank=True, to='education.Area', null=True, verbose_name=b'\xe4\xb8\x8a\xe7\xba\xa7')),
],
options={
'db_table': 'area',
'verbose_name': '\u5730\u533a',
'verbose_name_plural': '\u5730\u533a',
},
),
migrations.CreateModel(
name='CodeAccountType',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('acc_type_name', models.CharField(default='\u624b\u673a\u53f7', max_length=20, verbose_name=b'\xe5\xb8\x90\xe5\x8f\xb7\xe7\xb1\xbb\xe5\x9e\x8b')),
('comments', models.CharField(max_length=500, verbose_name=b'\xe5\xa4\x87\xe6\xb3\xa8', blank=True)),
],
options={
'db_table': 'code_account_type',
'verbose_name': '\u7528\u6237\u8d26\u53f7\u7c7b\u578b',
'verbose_name_plural': '\u7528\u6237\u8d26\u53f7\u7c7b\u578b',
},
),
migrations.CreateModel(
name='CodeEduPeriod',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('edu_period_name', models.CharField(default=b'\xe4\xb8\xad\xe5\xad\xa6', max_length=20, verbose_name=b'\xe5\xad\xa6\xe6\xae\xb5', blank=True)),
],
options={
'db_table': 'code_edu_period',
'verbose_name': '\u5b66\u6bb5',
'verbose_name_plural': '\u5b66\u6bb5',
},
),
migrations.CreateModel(
name='CodeGrade',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('grade_name', models.CharField(default=b'\xe5\x88\x9d\xe4\xb8\x80', max_length=10, verbose_name=b'\xe5\xb9\xb4\xe7\xba\xa7', blank=True)),
],
options={
'db_table': 'grades',
'verbose_name': '\u5e74\u7ea7',
'verbose_name_plural': '\u5e74\u7ea7',
},
),
migrations.CreateModel(
name='CodeRole',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('role_name', models.CharField(default='\u5b66\u751f', max_length=20, verbose_name=b'\xe8\xba\xab\xe4\xbb\xbd', blank=True)),
('comments', models.CharField(max_length=500, verbose_name=b'\xe5\xa4\x87\xe6\xb3\xa8', blank=True)),
],
options={
'db_table': 'code_role',
'verbose_name': '\u7528\u6237\u8eab\u4efd',
'verbose_name_plural': '\u7528\u6237\u8eab\u4efd',
},
),
migrations.CreateModel(
name='CodeUserStatus',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('user_state_name', models.CharField(default='\u5728\u7ebf', max_length=20, verbose_name=b'\xe7\x8a\xb6\xe6\x80\x81')),
],
options={
'db_table': 'code_user_status',
'verbose_name': '\u7528\u6237\u5e10\u53f7\u72b6\u6001',
'verbose_name_plural': '\u7528\u6237\u5e10\u53f7\u72b6\u6001',
},
),
migrations.CreateModel(
name='KeySchool',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('type', models.IntegerField(default=10, verbose_name=b'\xe7\xad\x89\xe7\xba\xa7', blank=True)),
],
options={
'db_table': 'keyschool',
'verbose_name': '\u540d\u724c\u5b66\u6821',
'verbose_name_plural': '\u540d\u724c\u5b66\u6821',
},
),
migrations.CreateModel(
name='KeyTeacher',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('type', models.IntegerField(default=10, verbose_name=b'\xe7\xad\x89\xe7\xba\xa7', blank=True)),
('details', models.CharField(default=b'', max_length=20, blank=True)),
],
options={
'db_table': 'keyteacher',
'verbose_name': '\u540d\u724c\u6559\u5e08',
'verbose_name_plural': '\u540d\u724c\u6559\u5e08',
},
),
migrations.CreateModel(
name='Notice',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField(max_length=20, verbose_name=b'\xe4\xb8\xbb\xe9\xa2\x98')),
('created_date', models.DateTimeField(auto_now_add=True, verbose_name=b'\xe5\x88\x9b\xe5\xbb\xba\xe6\x97\xa5\xe6\x9c\x9f')),
('content', models.TextField(verbose_name=b'\xe5\x86\x85\xe5\xae\xb9')),
],
options={
'db_table': 'notices',
'verbose_name': '\u516c\u544a',
'verbose_name_plural': '\u516c\u544a',
},
),
migrations.CreateModel(
name='NoticeTo',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('notice', models.ForeignKey(to='education.Notice', db_column=b'notice_id')),
],
options={
'db_table': 'notice_to',
'verbose_name': '\u516c\u544a\u63a5\u6536\u4eba\u6216\u8005\u7ec4\u7ec7',
'verbose_name_plural': '\u516c\u544a\u63a5\u6536\u4eba\u6216\u8005\u7ec4\u7ec7',
},
),
migrations.CreateModel(
name='Org',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(default=b'XX\xe4\xb8\xad\xe5\xad\xa6', max_length=50, verbose_name=b'\xe7\xbb\x84\xe7\xbb\x87\xe5\x90\x8d\xe7\xa7\xb0', blank=True)),
('size', models.IntegerField(default=1200, verbose_name=b'\xe6\x80\xbb\xe4\xba\xba\xe6\x95\xb0', blank=True)),
('type', models.CharField(default=b'\xe5\xad\xa6\xe6\xa0\xa1', max_length=10, verbose_name=b'\xe7\xbb\x84\xe7\xbb\x87\xe7\xb1\xbb\xe5\x9e\x8b')),
('sort', models.IntegerField(default=2, blank=True)),
('status', models.SmallIntegerField(default=0, verbose_name=b'\xe7\x8a\xb6\xe6\x80\x81', blank=2)),
('created_date', models.DateTimeField(auto_now_add=True, verbose_name=b'\xe5\x88\x9b\xe5\xbb\xba\xe6\x97\xa5\xe6\x9c\x9f')),
('comments', models.CharField(max_length=500, verbose_name=b'\xe5\xa4\x87\xe6\xb3\xa8', blank=True)),
('lft', models.PositiveIntegerField(editable=False, db_index=True)),
('rght', models.PositiveIntegerField(editable=False, db_index=True)),
('tree_id', models.PositiveIntegerField(editable=False, db_index=True)),
('level', models.PositiveIntegerField(editable=False, db_index=True)),
('area', models.ForeignKey(db_column=b'area_id', verbose_name=b'\xe5\x9c\xb0\xe5\x8c\xba', to='education.Area')),
('edu_period', models.ForeignKey(db_column=b'edu_period', verbose_name=b'\xe5\xad\xa6\xe6\xae\xb5', to='education.CodeEduPeriod')),
('grade', models.ForeignKey(db_column=b'grade', blank=True, to='education.CodeGrade', null=True, verbose_name=b'\xe5\xb9\xb4\xe7\xba\xa7')),
('parent', mptt.fields.TreeForeignKey(related_name='children', db_column=b'parent_id', blank=True, to='education.Org', null=True, verbose_name=b'\xe4\xb8\x8a\xe7\xba\xa7\xe7\xbb\x84\xe7\xbb\x87')),
],
options={
'db_table': 'org',
'verbose_name': '\u7ec4\u7ec7',
'verbose_name_plural': '\u7ec4\u7ec7',
},
),
migrations.CreateModel(
name='Profile',
fields=[
('user', models.OneToOneField(related_name='profile', primary_key=True, db_column=b'id', serialize=False, to=settings.AUTH_USER_MODEL, verbose_name=b'\xe7\x94\xa8\xe6\x88\xb7')),
('account_id', models.CharField(max_length=100, blank=True)),
('username', models.CharField(max_length=50, verbose_name=b'\xe7\x94\xa8\xe6\x88\xb7\xe5\xa7\x93\xe5\x90\x8d', blank=True)),
('login_name', models.CharField(max_length=50, verbose_name=b'\xe6\x98\xb5\xe7\xa7\xb0', blank=True)),
('md5passwdstr', models.CharField(max_length=300, blank=True)),
('gender', models.BooleanField(default=True, verbose_name=b'\xe6\x80\xa7\xe5\x88\xab')),
('email', models.EmailField(max_length=254, verbose_name=b'\xe9\x82\xae\xe7\xae\xb1', blank=True)),
('phone', models.CharField(max_length=30, verbose_name=b'\xe6\x89\x8b\xe6\x9c\xba\xe5\x8f\xb7', blank=True)),
('birthday', models.DateField(verbose_name=b'\xe7\x94\x9f\xe6\x97\xa5', blank=True)),
('idcardnum', models.CharField(max_length=30, verbose_name=b'', blank=True)),
('address', models.CharField(max_length=200, verbose_name=b'\xe5\xae\xb6\xe5\xba\xad\xe4\xbd\x8f\xe5\x9d\x80', blank=True)),
('intro', models.CharField(max_length=500, verbose_name=b'\xe4\xb8\xaa\xe4\xba\xba\xe7\xae\x80\xe4\xbb\x8b', blank=True)),
('qq', models.CharField(max_length=20, verbose_name=b'QQ', blank=True)),
('wechat', models.CharField(max_length=100, verbose_name=b'\xe5\xbe\xae\xe4\xbf\xa1', blank=True)),
('inschoolyears', models.IntegerField(default=2013, verbose_name=b'\xe5\x85\xa5\xe5\xad\xa6\xe5\xb9\xb4\xe4\xbb\xbd', blank=True)),
('create_date', models.DateTimeField(auto_now_add=True)),
('last_login_date', models.DateTimeField(blank=True)),
('last_status_change_date', models.DateTimeField(blank=True)),
('head_pic_url', models.CharField(max_length=1000, verbose_name=b'\xe5\xa4\xb4\xe5\x83\x8f\xe5\x9b\xbe\xe7\x89\x87', blank=True)),
('comments', models.CharField(max_length=500, verbose_name=b'\xe5\xa4\x87\xe6\xb3\xa8', blank=True)),
],
options={
'db_table': 'user',
'verbose_name': '\u7528\u6237\u4fe1\u606f',
'verbose_name_plural': '\u7528\u6237\u4fe1\u606f',
},
),
migrations.CreateModel(
name='UserGroup',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('group', models.ForeignKey(to='auth.Group', db_column=b'group_id')),
],
options={
'db_table': 'user_group',
},
),
migrations.CreateModel(
name='UserOrg',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('org', models.ForeignKey(db_column=b'org_id', verbose_name=b'\xe7\xbb\x84\xe7\xbb\x87', to='education.Org')),
('user', models.ForeignKey(db_column=b'user_id', verbose_name=b'\xe7\x94\xa8\xe6\x88\xb7', to=settings.AUTH_USER_MODEL)),
],
options={
'db_table': 'user_org',
'verbose_name': '\u7528\u6237\u548c\u7ec4\u7ec7\u7684\u5173\u7cfb',
'verbose_name_plural': '\u7528\u6237\u548c\u7ec4\u7ec7\u7684\u5173\u7cfb',
},
),
migrations.CreateModel(
name='UserPermissions',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('permission', models.ForeignKey(db_column=b'permission_id', default=1, verbose_name=b'\xe6\x9d\x83\xe9\x99\x90', to='auth.Permission')),
],
options={
'db_table': 'user_permissions',
'verbose_name': '\u7528\u6237\u4e0e\u6743\u9650',
'verbose_name_plural': '\u7528\u6237\u4e0e\u6743\u9650',
},
),
migrations.CreateModel(
name='UserStatusChangeLog',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('change_date', models.DateTimeField(blank=True)),
('resason', models.CharField(default=b'\xe6\x88\x91\xe5\x96\x9c\xe6\xac\xa2', max_length=500)),
('new_status', models.ForeignKey(related_name='new', db_column=b'new_status', to='education.CodeUserStatus')),
('old_status', models.ForeignKey(related_name='old', db_column=b'old_status', to='education.CodeUserStatus')),
],
options={
'db_table': 'user_status_change_log',
},
),
migrations.CreateModel(
name='Version',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('version', models.FloatField(verbose_name=b'\xe7\x89\x88\xe6\x9c\xac')),
('url', models.CharField(max_length=100, verbose_name=b'\xe4\xb8\x8b\xe8\xbd\xbd\xe5\x9c\xb0\xe5\x9d\x80')),
('comments', models.TextField(verbose_name=b'\xe6\x9b\xb4\xe6\x96\xb0\xe5\x86\x85\xe5\xae\xb9')),
('created_date', models.DateTimeField(auto_now_add=True, verbose_name=b'\xe6\x9b\xb4\xe6\x96\xb0\xe6\x97\xa5\xe6\x9c\x9f')),
],
options={
'db_table': 'version',
'verbose_name': 'APP \u7248\u672c',
'verbose_name_plural': 'APP \u7248\u672c',
},
),
migrations.CreateModel(
name='UserRelationInfo',
fields=[
('user', models.OneToOneField(primary_key=True, db_column=b'user_id', serialize=False, to='education.Profile', verbose_name=b'\xe7\x94\xa8\xe6\x88\xb7')),
('relation_type', models.CharField(default=b'\xe7\x88\xb6\xe4\xba\xb2', max_length=10, verbose_name=b'\xe5\x85\xb3\xe7\xb3\xbb', blank=True)),
('relation_name', models.CharField(default=b'\xe6\x9d\x8e\xe5\xa4\xa9\xe4\xb8\x80', max_length=50, verbose_name=b'\xe5\xa7\x93\xe5\x90\x8d', blank=True)),
('relation_phone', models.CharField(default=b'13788740727', max_length=32, verbose_name=b'\xe6\x89\x8b\xe6\x9c\xba\xe5\x8f\xb7')),
('relation_email', models.EmailField(default=b'<EMAIL>', max_length=254, verbose_name=b'\xe9\x82\xae\xe7\xae\xb1', blank=True)),
('relation_address', models.CharField(default=b'\xe6\xb9\x96\xe5\x8d\x97', max_length=200, verbose_name=b'\xe5\xae\xb6\xe5\xba\xad\xe4\xbd\x8f\xe5\x9d\x80')),
('comments', models.CharField(max_length=500, verbose_name=b'\xe5\xa4\x87\xe6\xb3\xa8', blank=True)),
],
options={
'db_table': 'user_relation_info',
'verbose_name': '\u7528\u6237\u4eb2\u5c5e\u5173\u7cfb',
'verbose_name_plural': '\u7528\u6237\u4eb2\u5c5e\u5173\u7cfb',
},
),
migrations.AddField(
model_name='userstatuschangelog',
name='oper',
field=models.ForeignKey(related_name='operator', db_column=b'oper', to='education.Profile'),
),
migrations.AddField(
model_name='userstatuschangelog',
name='user',
field=models.ForeignKey(related_name='statusChange', db_column=b'user_id', to='education.Profile'),
),
migrations.AddField(
model_name='userpermissions',
name='user',
field=models.ForeignKey(db_column=b'user_id', verbose_name=b'\xe7\x94\xa8\xe6\x88\xb7', to='education.Profile'),
),
migrations.AddField(
model_name='usergroup',
name='user',
field=models.ForeignKey(to='education.Profile', db_column=b'user_id'),
),
migrations.AddField(
model_name='profile',
name='account_type',
field=models.ForeignKey(db_column=b'account_type', verbose_name=b'\xe5\xb8\x90\xe5\x8f\xb7\xe7\xb1\xbb\xe5\x9e\x8b', to='education.CodeAccountType'),
),
migrations.AddField(
model_name='profile',
name='role',
field=models.ForeignKey(db_column=b'role', verbose_name=b'\xe7\x94\xa8\xe6\x88\xb7\xe8\xba\xab\xe4\xbb\xbd', to='education.CodeRole'),
),
migrations.AddField(
model_name='profile',
name='status',
field=models.ForeignKey(db_column=b'status', verbose_name=b'\xe5\xb8\x90\xe5\x8f\xb7\xe7\x8a\xb6\xe6\x80\x81', to='education.CodeUserStatus'),
),
migrations.AddField(
model_name='noticeto',
name='org',
field=models.ForeignKey(related_name='notices', db_column=b'org_id', blank=True, to='education.Org', null=True),
),
migrations.AddField(
model_name='noticeto',
name='user',
field=models.ForeignKey(related_name='notices', db_column=b'user_id', blank=True, to=settings.AUTH_USER_MODEL, null=True),
),
migrations.AddField(
model_name='notice',
name='created_by',
field=models.ForeignKey(related_name='created_notices', db_column=b'create_by', verbose_name=b'\xe5\x8f\x91\xe5\xb8\x83\xe4\xba\xba', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='keyteacher',
name='teacher',
field=models.ForeignKey(db_column=b'user_id', verbose_name=b'\xe6\x95\x99\xe5\xb8\x88', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='keyschool',
name='org',
field=models.ForeignKey(db_column=b'org_id', verbose_name=b'\xe5\xad\xa6\xe6\xa0\xa1', to='education.Org'),
),
]
<file_sep># -*- coding:utf-8 -*-
from django.db.models import Model, ForeignKey, CharField, IntegerField, DateTimeField, SmallIntegerField
from mptt.models import MPTTModel, TreeForeignKey
from django.contrib.auth.models import User
from education.models import Org
from .question import Question
class QuestionsDyndifficulty(Model):
question = ForeignKey(Question, db_column='question_id', verbose_name='题目')
diffcultty = IntegerField(default=0, verbose_name='难度等级')
calc_date = DateTimeField(auto_now_add=True, verbose_name='创建时间')
comments = CharField(max_length=500, blank=True, verbose_name='备注')
class Meta:
app_label = 'question'
db_table = 'questions_dyndifficulty'
verbose_name = '题目难度'
verbose_name_plural = '题目难度'
def __unicode__(self):
return u'{0}'.format(str(self.diffcultty))
class KnowegePoint(MPTTModel):
title = CharField(max_length=100, verbose_name='知识点名字')
parent = TreeForeignKey('self', db_column='parent_id', blank=True, null=True, related_name='children',
verbose_name='父知识点')
ref_count = IntegerField(default=0, verbose_name='引用次数')
created_by = ForeignKey(User, db_column='created_by', related_name='created_knowege_points', verbose_name='创建者')
owner = ForeignKey(Org, db_column='owner', related_name='own_knowege_points', verbose_name='拥有者')
created_date = DateTimeField(auto_now_add=True, verbose_name='创建时间')
class Meta:
app_label = 'question'
db_table = 'knowege_point'
verbose_name = '知识点'
verbose_name_plural = '知识点'
def __unicode__(self):
return u'{0}'.format(self.title)
class QuestionKnowlegePoint(Model):
questhion = ForeignKey(Question, db_column='questhion_id', verbose_name='题目')
knowege_point = ForeignKey(KnowegePoint, db_column='knowege_point', verbose_name='知识点')
class Meta:
app_label = 'question'
db_table = 'question_knowlege_point'
verbose_name = '题目和知识点对应关系'
verbose_name_plural = '题目和知识点对应关系'
def __unicode__(self):
return u'{0}...——{1}'.format(self.questhion.content[:5], self.index.title)
<file_sep># -*- coding:utf-8 -*-
from django.db.models import Model, CharField, IntegerField, ForeignKey, \
FloatField, SmallIntegerField, DateTimeField
from mptt.models import MPTTModel, TreeForeignKey
class Area(MPTTModel):
# 地区表
parent = TreeForeignKey('self', db_column='parent_id', null=True, blank=True, related_name='children',
verbose_name='上级')
# path = CharField(max_length=200, blank=True, verbose_name='具体位置')
# level = SmallIntegerField(blank=True, default=4, verbose_name='级别')
name = CharField(max_length=50, blank=True, verbose_name='名称')
short_name = CharField(max_length=50, blank=True, verbose_name='简称')
longitude = FloatField(blank=True, default=1.1, null=True, verbose_name='经度')
latitude = FloatField(blank=True, default=2.2, null=True, verbose_name='纬度')
sort = IntegerField(blank=True, default=1)
status = SmallIntegerField(blank=True, default=2, verbose_name='状态')
class Meta:
app_label = 'education'
db_table = 'area'
verbose_name = '地区'
verbose_name_plural = '地区'
def __unicode__(self):
return u'{0}'.format(self.name)
class CodeEduPeriod(Model):
# 学段类别表
edu_period_name = CharField(max_length=20, blank=True, default='中学', verbose_name='学段')
class Meta:
app_label = 'education'
db_table = 'code_edu_period'
verbose_name = '学段'
verbose_name_plural = '学段'
def __unicode__(self):
return u'{0}'.format(self.edu_period_name)
class CodeGrade(Model):
grade_name = CharField(max_length=10, verbose_name='年级', blank=True, default='初一')
class Meta:
app_label = 'education'
db_table = 'grades'
verbose_name = '年级'
verbose_name_plural = '年级'
def __unicode__(self):
return u'{0}'.format(self.grade_name)
class CodeOrgType(Model):
org_type_name = CharField(max_length=10)
def __unicode__(self):
return u'{0}'.format(self.org_type_name)
class Org(MPTTModel):
# 组织模型表
parent = TreeForeignKey('self', db_column='parent_id', null=True, blank=True, related_name='children',
verbose_name='上级组织')
area = ForeignKey(Area, db_column='area_id', verbose_name='地区')
name = CharField(max_length=50, blank=True, default='XX中学', verbose_name='组织名称')
edu_period = ForeignKey(CodeEduPeriod, db_column='edu_period', verbose_name='学段')
size = IntegerField(blank=True, default=1200, verbose_name='总人数')
type = ForeignKey(CodeOrgType, db_column='type',verbose_name='组织类型')
sort = IntegerField(blank=True, default=2)
status = SmallIntegerField(default=0, blank=2, verbose_name='状态')
created_date = DateTimeField(blank=True, auto_now_add=True, verbose_name='创建日期')
grade = ForeignKey(CodeGrade, db_column='grade', blank=True, null=True, verbose_name='年级')
comments = CharField(max_length=500, blank=True, verbose_name='备注')
class Meta:
app_label = 'education'
db_table = 'org'
verbose_name = '组织'
verbose_name_plural = '组织'
def __unicode__(self):
return u'{0}'.format(self.name)
class KeySchool(Model):
# 重点学校
org = ForeignKey(Org, db_column='org_id', verbose_name='学校')
type = IntegerField(blank=True, default=10, verbose_name='等级')
class Meta:
app_label = 'education'
db_table = 'keyschool'
verbose_name = '名牌学校'
verbose_name_plural = '名牌学校'
def __unicode__(self):
return u'{0}-{1}'.format(self.org.name, self.type)
<file_sep># -*- coding:utf-8 -*-
from django.db.models import Model, CharField, ForeignKey, DateTimeField, TextField, BooleanField
from django.contrib.auth.models import User
from .org import Org
class Notice(Model):
title = CharField(max_length=20, verbose_name='主题')
created_by = ForeignKey(User, db_column='create_by', related_name='created_notices', verbose_name='发布人')
created_date = DateTimeField(auto_now_add=True, verbose_name='创建日期')
content = TextField(verbose_name='内容')
class Meta:
app_label = 'education'
db_table = 'notices'
verbose_name = '公告'
verbose_name_plural = '公告'
def __unicode__(self):
return u'{0}'.format(self.title)
class NoticeTo(Model):
notice = ForeignKey(Notice, db_column='notice_id')
user = ForeignKey(User, db_column='user_id', null=True, related_name='notices', blank=True)
org = ForeignKey(Org, db_column='org_id', null=True, related_name='notices', blank=True)
class Meta:
app_label = 'education'
db_table = 'notice_to'
verbose_name = '公告接收人或者组织'
verbose_name_plural = '公告接收人或者组织'
def __unicode__(self):
to = self.user or self.org
if isinstance(to, User):
to = self.user.username
else:
to = self.org.name
return u'「{0}」To「{1}」'.format(self.notice.title, to)
<file_sep>default_app_config = 'education.app_config.EducationConfig'
<file_sep># -*- coding:utf-8 -*-
from rest_framework import serializers
from education.utils import convert_timezone
from question import models
class CharpterSerializers(serializers.ModelSerializer):
children_details = serializers.SerializerMethodField()
class Meta:
model = models.Charpter
fields = ('id', 'title', 'subject', 'parent', 'owner',
'comment', 'children', 'level', 'children_details')
def get_children_details(self, obj):
return obj.get_children_details()
class AssignmentSerializers(serializers.ModelSerializer):
class Meta:
model = models.Assignment
fields = ('id', 'title')
class AssignmentPublishSerializers(serializers.ModelSerializer):
assignment_name = serializers.ReadOnlyField(source='assignment.title')
assignment_id = serializers.ReadOnlyField(source='assignment.id')
publish_date = serializers.SerializerMethodField()
class Meta:
model = models.AssignmentPublish
fields = ('id', 'assignment_name', 'assignment_id', 'publish_date')
def get_publish_date(self, obj):
return convert_timezone(obj.publish_date)
class AssignmentDetailsSerializers(serializers.ModelSerializer):
assignment_id = serializers.ReadOnlyField(source='assignment.id')
question_id = serializers.ReadOnlyField(source='question.id')
question_content = serializers.ReadOnlyField(source='question.content')
class Meta:
model = models.AssignmentQuestions
fields = ('id', 'assignment_id', 'question_id', 'question_content')
<file_sep>"""web_site URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from education import api
from question import api as question_api
from question import views as question_view
from rest_framework import routers
from rest_framework.authtoken.models import Token
apiRouter = routers.DefaultRouter()
apiRouter.register(r'users', api.UsersViewSet, 'User')
apiRouter.register(r'profile', api.UsersProfileViewSet, 'Profile')
apiRouter.register(r'org', api.OrgViewSet, 'Org')
apiRouter.register(r'notices', api.NoticeViewSet, 'Notice')
apiRouter.register(r'version', api.VersionViewSet, 'Version')
apiRouter.register(r'keyteacher', api.KeyTeacherViewSet, 'Keyteacher')
apiRouter.register(r'keyschool', api.KeySchoolViewSet, 'KeySchool')
apiRouter.register(r'charters', question_api.CharpterViewSet, 'Charter')
apiRouter.register(r'published_assignments', question_api.AssignmentPublishedViewSet, 'PublishedAssignment')
apiRouter.register(r'assignments', question_api.AssignmentViewSet, 'Assignment')
apiRouter.register(r'klasses', api.KlassesViewSet, 'Klass')
admin.site.unregister(Token)
urlpatterns = [
url(r'^$', question_view.index),
url(r'^select_subject/(?P<goto>\w+)/$', question_view.select_subject),
url(r'^(?P<subject_id>\d+)/select_charter/(?P<goto>\w+)/$', question_view.select_charpter),
url(r'^(?P<subject_id>\d+)/(?P<charpter_id>\d+)/add_question/$', question_view.add_question),
url(r'^(?P<subject_id>\d+)/(?P<charpter_id>\d+)/add_assignment/$', question_view.add_assignment),
url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/v1/', include(admin.site.urls)),
url(r'^api/v1/auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api/v1/get-token/', api.CreateToken.as_view()),
url(r'^api/v1/', include(apiRouter.urls)),
]
<file_sep># -*- coding:utf-8 -*-
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from education import models
class UserSerializers(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email', 'password')
# write_only_fields = ('password',)
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email'],
)
user.set_password(validated_data['password'])
user.save()
return user
def update(self, instance, validated_data):
validated_data['password'] = <PASSWORD>(validated_data['password'])
return super(UserSerializers, self).update(instance, validated_data)
class ProfileSerializers(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source='user.pk')
class Meta:
model = models.Profile
fields = ('user', 'email')
class OrgSerializers(serializers.ModelSerializer):
class Meta:
model = models.Org
fields = ('pk', 'name',)
class NoticeSerializers(serializers.ModelSerializer):
created_by = serializers.ReadOnlyField(source='created_by.username')
class Meta:
model = models.Notice
fields = ('title', 'created_by', 'created_date', 'content')
class VersionSerializers(serializers.ModelSerializer):
class Meta:
model = models.Version
fields = ('version', 'url', 'comments', 'created_date')
read_only_fields = ('version', 'url', 'comments', 'created_date')
class KeyTeacherSerializers(serializers.ModelSerializer):
teacher_name = serializers.ReadOnlyField(source='teacher.username')
class Meta:
model = models.KeyTeacher
fields = ('teacher_name', 'details')
class KeySchoolSerializers(serializers.ModelSerializer):
school_name = serializers.ReadOnlyField(source='org.name')
class Meta:
model = models.KeySchool
fields = ('school_name', 'type')
class UserOrgSerializers(serializers.ModelSerializer):
org_name = serializers.ReadOnlyField(source='org.name')
org_id = serializers.ReadOnlyField(source='org.id')
class Meta:
model = models.UserOrg
fields = ('id', 'org_name', 'org_id')
<file_sep># -*- coding:utf-8 -*-
from django.db.models import Model, ForeignKey, CharField, BooleanField
from mptt.models import MPTTModel, TreeForeignKey
from education.models import Org
# from question.api import CharpterSerializers
class Library(Model):
library_name = CharField(max_length=100, verbose_name='名字')
public = BooleanField(default=False, verbose_name='是否公开')
owner = ForeignKey(Org, db_column='owner', related_name='owner_librarys', verbose_name='拥有者')
class Meta:
app_label = 'question'
db_table = 'library'
verbose_name = '题库'
verbose_name_plural = '题库'
def __unicode__(self):
return u'{0}'.format(self.library_name)
class CodeQuesthionType(Model):
questhion_type_name = CharField(max_length=20, verbose_name='题目类型')
class Meta:
app_label = 'question'
db_table = 'code_questhion_type'
verbose_name = '题目类型'
verbose_name_plural = '题目类型'
def __unicode__(self):
return u'{0}'.format(self.questhion_type_name)
class CodeContextType(Model):
context_type_name = CharField(max_length=20, verbose_name='答案类型')
class Meta:
app_label = 'question'
db_table = 'code_context_type'
verbose_name = '答案类型'
verbose_name_plural = '答案类型'
def __unicode__(self):
return u'{0}'.format(self.context_type_name)
class CodeSubject(Model):
subject_name = CharField(max_length=20, verbose_name='科目')
class Meta:
app_label = 'question'
db_table = 'code_subject'
verbose_name = '科目'
verbose_name_plural = '科目'
def __unicode__(self):
return u'{0}'.format(self.subject_name)
class Charpter(MPTTModel):
title = CharField(max_length=200, verbose_name='章节')
subject = ForeignKey(CodeSubject, db_column='subject', verbose_name='科目')
parent = TreeForeignKey('self', null=True, blank=True, db_column='parent_id', verbose_name='父章节',
related_name='children')
# path = CharField(max_length=200, verbose_name='位置')
# level = SmallIntegerField(default=0, verbose_name='级别')
owner = ForeignKey(Org, db_column='owner', verbose_name='拥有者')
comment = CharField(max_length=500, blank=True, default='', verbose_name='备注')
def get_children_details(self):
ret = []
if self.get_level() == 0:
family = self.get_family()
for i in family:
item = dict()
item['id'] = i.id
item['title'] = i.title
item['level'] = i.level
ret.append(item)
return ret
else:
return []
class Meta:
app_label = 'question'
db_table = 'charpter'
verbose_name = '章节'
verbose_name_plural = '章节'
def __unicode__(self):
return u'{0}'.format(self.title)
<file_sep># -*- coding:utf-8 -*-
from django.db.models import Model, CharField, IntegerField, TextField, \
BooleanField, EmailField, DateField, DateTimeField, ForeignKey, OneToOneField, FloatField
from django.contrib.auth.models import User
from .user_desc import CodeAccountType, CodeRole, CodeUserStatus
from .org import Org
class Profile(Model):
# 用户配置表
user = OneToOneField(User, db_column='id', primary_key=True, related_name='profile', verbose_name='用户')
account_id = CharField(max_length=100, blank=True)
account_type = ForeignKey(CodeAccountType, db_column='account_type', verbose_name='帐号类型')
role = ForeignKey(CodeRole, db_column='role', verbose_name='用户身份')
username = CharField(max_length=50, blank=True, verbose_name='用户姓名')
login_name = CharField(max_length=50, blank=True, verbose_name='昵称')
md5passwdstr = CharField(max_length=300, blank=True)
status = ForeignKey(CodeUserStatus, db_column="status", verbose_name='帐号状态')
gender = BooleanField(default=True, verbose_name='性别') # True 为男性
email = EmailField(blank=True, verbose_name='邮箱')
phone = CharField(max_length=30, blank=True, verbose_name='手机号')
birthday = DateField(blank=True, verbose_name='生日')
idcardnum = CharField(max_length=30, blank=True, verbose_name='')
address = CharField(max_length=200, blank=True, verbose_name='家庭住址')
intro = CharField(max_length=500, blank=True, verbose_name='个人简介')
qq = CharField(max_length=20, blank=True, verbose_name='QQ')
wechat = CharField(max_length=100, blank=True, verbose_name='微信')
inschoolyears = IntegerField(blank=True, default=2013, verbose_name='入学年份')
create_date = DateTimeField(auto_now_add=True)
last_login_date = DateTimeField(blank=True)
last_status_change_date = DateTimeField(blank=True)
head_pic_url = CharField(max_length=1000, blank=True, verbose_name='头像图片')
comments = CharField(max_length=500, blank=True, verbose_name='备注')
class Meta:
app_label = 'education'
db_table = 'user'
verbose_name = '用户信息'
verbose_name_plural = '用户信息'
def __unicode__(self):
return '{0}'.format(self.user.username)
class UserOrg(Model):
# 用户和组织多对多关系表
user = ForeignKey(User, db_column='user_id', verbose_name='用户')
org = ForeignKey(Org, db_column='org_id', verbose_name='组织')
is_admin = BooleanField(default=False)
class Meta:
app_label = 'education'
db_table = 'user_org'
verbose_name = '用户和组织的关系'
verbose_name_plural = '用户和组织的关系'
def __unicode__(self):
return u'{0}@{1}'.format(self.user.username, self.org.name)
class KeyTeacher(Model):
# 名师
teacher = ForeignKey(User, db_column='user_id', verbose_name='教师')
type = IntegerField(blank=True, default=10, verbose_name='等级')
details = CharField(max_length=20, blank=True, default='')
class Meta:
app_label = 'education'
db_table = 'keyteacher'
verbose_name = '名牌教师'
verbose_name_plural = '名牌教师'
def __unicode__(self):
return u'{0}'.format(self.teacher.username)
class Version(Model):
version = FloatField(verbose_name='版本')
url = CharField(max_length=100, verbose_name='下载地址')
comments = TextField(verbose_name='更新内容')
created_date = DateTimeField(auto_now_add=True, verbose_name='更新日期')
class Meta:
app_label = 'education'
db_table = 'version'
verbose_name = 'APP 版本'
verbose_name_plural = 'APP 版本'
def __unicode__(self):
return u'{0}版'.format(self.version)
<file_sep># -*- coding:utf-8 -*-
from rest_framework import viewsets
from rest_framework.response import Response
from .serializers import CharpterSerializers, AssignmentSerializers, \
AssignmentPublishSerializers, AssignmentDetailsSerializers
from education import models as education_models
from question import models as question_models
from django.shortcuts import get_list_or_404, Http404
Teacher_id = education_models.CodeRole.objects.get(role_name='教师').id
Student_id = education_models.CodeRole.objects.get(role_name='学生').id
class CharpterViewSet(viewsets.ReadOnlyModelViewSet):
queryset = question_models.Charpter.objects.filter(level=0)
serializer_class = CharpterSerializers
class AssignmentPublishedViewSet(viewsets.ModelViewSet):
# 已发布作业接口
queryset = question_models.AssignmentPublish.objects.all()
serializer_class = AssignmentPublishSerializers
details_queryset = question_models.AssignmentQuestions.objects.all()
details_class = AssignmentDetailsSerializers
def list(self, request, *args, **kwargs):
if request.user.profile.role_id == Student_id:
user_orgs_relation = education_models.UserOrg.objects.filter(user=request.user)
queryset = []
for i in user_orgs_relation:
queryset.extend(self.queryset.filter(reciver_org=i.org))
serializer = self.serializer_class(queryset, many=True)
return Response(serializer.data)
else:
queryset = self.queryset.filter(publisher=request.user)
serializer = self.serializer_class(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, *args, **kwargs):
if request.user.profile.role_id == Student_id:
assignment_publish_obj = self.get_object()
queryset = self.details_queryset.filter(assignment_id=assignment_publish_obj.assignment.id)
serializer = self.details_class(queryset, many=True)
for d in serializer.data:
d['assignment_publish_id'] = kwargs.get('pk', None)
return Response(serializer.data)
else:
assignment_id = kwargs.get('pk', None)
queryset = get_list_or_404(question_models.AssignmentQuestions, assignment_id=assignment_id)
serializer = AssignmentDetailsSerializers(queryset, many=True)
return Response(serializer.data)
class AssignmentViewSet(viewsets.ReadOnlyModelViewSet):
# 全部作业接口
queryset = question_models.Assignment.objects.all()
serializer_class = AssignmentSerializers
details_queryset = question_models.AssignmentQuestions.objects.all()
details_class = AssignmentDetailsSerializers
def list(self, request, *args, **kwargs):
if request.user.profile.role_id == Student_id:
raise Http404
else:
user_org = education_models.UserOrg.objects.get(user=request.user, org__type_id=1)
queryset = user_org.org.own_assignments.all()
serializer = self.serializer_class(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, *args, **kwargs):
if request.user.profile.role_id == Student_id:
raise Http404
else:
assignment_id = kwargs.get('pk', None)
queryset = get_list_or_404(question_models.AssignmentQuestions, assignment_id=assignment_id)
serializer = AssignmentDetailsSerializers(queryset, many=True)
return Response(serializer.data)
| a5a11ee9edaf7aa761fb107d9997002e2104ecd0 | [
"JavaScript",
"Python",
"Text",
"Markdown"
] | 33 | Python | LXVC/jiu_school_back_end | 57efb9ea12e5f16089686f806a4c027513b4c5c1 | d9de3e7ab018ea7958d424547297d7bf32d64854 |
refs/heads/master | <file_sep>package com.example.lastmileconnectivity.lastmileconnectivity.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.lastmileconnectivity.lastmileconnectivity.R;
import com.example.lastmileconnectivity.lastmileconnectivity.util.CustomUtil;
import com.kelltontech.ui.activity.BaseActivity;
import com.kelltontech.utils.ConnectivityUtils;
import com.kelltontech.utils.StringUtils;
public class SignUpActivity extends BaseActivity implements View.OnClickListener {
private View mViewRoot;
private EditText mEtUserId;
private EditText mEtUserPassword;
private View mViewSignUp;
private View mViewOption;
private boolean isUser=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
setUpToolBar();
//view inti
mViewRoot=findViewById(R.id.root_view);
mEtUserId=(EditText)findViewById(R.id.et_user_id);
mEtUserPassword=(EditText)findViewById(R.id.et_user_password);
mViewSignUp=findViewById(R.id.rl_sign_up);
mViewOption=findViewById(R.id.ll_option);
Button btnSignUp = (Button) findViewById(R.id.btn_proceed);
View ivDriver = findViewById(R.id.iv_driver);
View ivUser = findViewById(R.id.iv_user);
assert ivDriver != null;
ivDriver.setOnClickListener(this);
assert ivUser != null;
ivUser.setOnClickListener(this);
View viewRegister = findViewById(R.id.tv_register);
assert viewRegister != null;
viewRegister.setOnClickListener(this);
assert btnSignUp != null;
btnSignUp.setOnClickListener(this);
}
/**
* Initialize Toolbar and set in the action bar
*/
private void setUpToolBar() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
assert mToolbar != null;
TextView tv_title = (TextView) mToolbar.findViewById(R.id.tv_title);
TextView tv_register = (TextView) mToolbar.findViewById(R.id.tv_register);
tv_register.setVisibility(View.INVISIBLE);
assert tv_title != null;
tv_title.setText(R.string.sign_up);
setSupportActionBar(mToolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.back_arrow);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//back arrow event
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void getData(int actionID) {
}
@Override
public void updateUi(boolean status, int action, Object serviceResponse) {
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btn_proceed:
String username=mEtUserId.getText().toString();
String password=<PASSWORD>.<PASSWORD>().<PASSWORD>();
if (!ConnectivityUtils.isNetworkEnabled(SignUpActivity.this)) {
CustomUtil.showSnackBar(mViewRoot,getString(R.string.internet_check));
return;
}
if(checkValidation(username,password)){
Intent intent = new Intent(SignUpActivity.this, DriverHomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
break;
case R.id.iv_driver:
isUser=false;
mViewSignUp.setVisibility(View.VISIBLE);
mViewOption.setVisibility(View.GONE);
break;
case R.id.iv_user:
isUser=true;
isUser=false;
mViewSignUp.setVisibility(View.VISIBLE);
mViewOption.setVisibility(View.GONE);
break;
}
}
public boolean checkValidation(String username,String password){
if(StringUtils.isNullOrEmpty(username) && StringUtils.isNullOrEmpty(password)){
CustomUtil.showSnackBar(mViewRoot,"Please enter mobile number / email id and password");
return false;
}else if(StringUtils.isNullOrEmpty(username)){
CustomUtil.showSnackBar(mViewRoot,"Please enter mobile number / email id");
return false;
}else if(StringUtils.isNullOrEmpty(password)){
CustomUtil.showSnackBar(mViewRoot,"Please enter password");
return false;
}else{
return true;
}
}
}
<file_sep>package com.kelltontech.model;
/**
* Model class for Request and response Api.
* @author <NAME>
*/
public class EncryptionModel extends BaseModelCM{
public String str;
public EncryptionModel(String str) {
this.str = str;
}
}
<file_sep>package com.kelltontech.volley.ext;
import com.android.volley.VolleyError;
/**
* Custom volley error for club mahindra
*/
public class CmVolleyError extends VolleyError {
public int mStatus;
public int mResponseCode;
public String mResponseMessage;
public CmVolleyError(String responseMessage,int status,int responseCode) {
super(responseMessage);
mResponseMessage=responseMessage;
mStatus=status;
mResponseCode = responseCode;
}
}
<file_sep>/*
*
* Proprietary and confidential. Property of Kellton Tech Solutions Ltd. Do not disclose or distribute.
* You must have written permission from Kellton Tech Solutions Ltd. to use this code.
*
*/
package com.kelltontech.ui.activity;
import android.app.Application;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import com.kelltontech.BuildConfig;
import com.kelltontech.R;
import com.kelltontech.application.BaseApplication;
import com.kelltontech.ui.IScreen;
import com.kelltontech.utils.KeypadUtils;
/**
* This class is used as base-class for application-base-activity.
*/
public abstract class BaseActivity extends AppCompatActivity implements IScreen {
private String LOG_TAG = getClass().getSimpleName();
public static final String COMING_FROM_NOTIFICATION = "COMING_FROM_NOTIFICATION";
public static final String NOTIFICATION_TYPE_BROADCAST = "NOTIFICATION_TYPE_BROADCAST";
public static final String PUSH_MODEL = "PUSH_MODEL";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
if (bundle != null && bundle.containsKey(COMING_FROM_NOTIFICATION) && bundle.containsKey(NOTIFICATION_TYPE_BROADCAST)
&& bundle.containsKey(PUSH_MODEL)) {
Intent intent = new Intent("NOTIFICATION_CLICK_INTENT_FILTER");
bundle.putString(NOTIFICATION_TYPE_BROADCAST, bundle.getString(NOTIFICATION_TYPE_BROADCAST));
intent.putExtras(bundle);
sendBroadcast(intent);
}
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
super.setContentView(layoutResID);
}
@Override
protected void onResume() {
super.onResume();
if (BuildConfig.DEBUG) {
Log.i(LOG_TAG, "onResume()");
}
Application application = this.getApplication();
if (application instanceof BaseApplication) {
BaseApplication baseApplication = (BaseApplication) application;
if (baseApplication.isAppInBackground()) {
onAppResumeFromBackground();
}
baseApplication.onActivityResumed();
}
}
/**
* This callback will be called after onResume if application is being
* resumed from background. <br/>
* <p/>
* Subclasses can override this method to get this callback.
*/
protected void onAppResumeFromBackground() {
if (BuildConfig.DEBUG) {
Log.i(LOG_TAG, "onAppResumeFromBackground()");
}
}
/**
* This method should be called to force app assume itself not in
* background.
*/
public final void setAppNotInBackground() {
Application application = this.getApplication();
if (application instanceof BaseApplication) {
BaseApplication baseApplication = (BaseApplication) application;
baseApplication.setAppInBackground(false);
}
}
@Override
protected void onPause() {
super.onPause();
if (BuildConfig.DEBUG) {
Log.i(LOG_TAG, "onPause()");
}
Application application = this.getApplication();
if (application instanceof BaseApplication) {
BaseApplication baseApplication = (BaseApplication) application;
baseApplication.onActivityPaused();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (BuildConfig.DEBUG) {
Log.i(LOG_TAG, "onNewIntent()");
}
}
/**
* Subclass should over-ride this method to update the UI with response,
* this base class promises to call this method from UI thread.
*
* @param serviceResponse
*/
public abstract void updateUi(final boolean status, final int action, final Object serviceResponse);
// ////////////////////////////// show and hide ProgressDialog
// private ProgressDialog mProgressDialog;
//
// /**
// * Shows a simple native progress dialog<br/>
// * Subclass can override below two methods for custom dialogs- <br/>
// * 1. showProgressDialog <br/>
// * 2. removeProgressDialog
// *
// * @param bodyText
// */
// public void showProgressDialog(String bodyText) {
// if (isFinishing()) {
// return;
// }
// if (mProgressDialog == null) {
// mProgressDialog = new ProgressDialog(BaseActivity.this);
// mProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
// mProgressDialog.setCancelable(false);
// mProgressDialog.setOnKeyListener(new Dialog.OnKeyListener() {
// @Override
// public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
// if (keyCode == KeyEvent.KEYCODE_CAMERA || keyCode == KeyEvent.KEYCODE_SEARCH) {
// return true; //
// }
// return false;
// }
// });
// }
//
// mProgressDialog.setMessage(bodyText);
//
// if (!mProgressDialog.isShowing()) {
// mProgressDialog.show();
// }
// }
//
// /**
// * Removes the simple native progress dialog shown via showProgressDialog <br/>
// * Subclass can override below two methods for custom dialogs- <br/>
// * 1. showProgressDialog <br/>
// * 2. removeProgressDialog
// */
// public void removeProgressDialog() {
// try {
// if (mProgressDialog != null && mProgressDialog.isShowing()) {
// mProgressDialog.dismiss();
// }
// } catch (Exception e) {
//
// }
//
// }
//
//
//
// public void setProgressDialog(ProgressDialog dialog) {
// this.mProgressDialog = dialog;
// }
// ////////////////////////////// show and hide key-board
// private PopupWindow mPpoPopupWindow;
//
// private void popupProgressInit() {
// mPpoPopupWindow= OtherUtill.showProgressDialog(this);
// }
//
// public void showProgressDialog(String message) {
// if (isFinishing()) {
// return;
// }
// if (mPpoPopupWindow == null) {
// popupProgressInit();
// }
//
// if (!mPpoPopupWindow.isShowing()) {
// mPpoPopupWindow.showAtLocation(getWindow().getDecorView().getRootView(),Gravity.CENTER,0,0);
// }
// }
//
// /**
// * Removes the simple native progress dialog shown via showProgressDialog <br/>
// * Subclass can override below two methods for custom dialogs- <br/>
// * 1. showProgressDialog <br/>
// * 2. removeProgressDialog
// */
// public void removeProgressDialog() {
// try {
// if (mPpoPopupWindow != null && mPpoPopupWindow.isShowing()) {
// mPpoPopupWindow.dismiss();
// }
// } catch (Exception e) {
//
// }
//
// }
// @Override
// public void onBackPressed() {
// if(mPpoPopupWindow==null || !mPpoPopupWindow.isShowing()){
// super.onBackPressed();
// }
// }
ProgressDialog progressDialog;
public void showProgressDialog() {
try {
if (progressDialog == null) {
progressDialog = ProgressDialog.show(this, "", "Loading...");
} else {
progressDialog.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void removeProgressDialog() {
try {
if (progressDialog != null) {
progressDialog.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
try {
View v = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);
if (v instanceof EditText) {
View w = getCurrentFocus();
int scrcoords[] = new int[2];
w.getLocationOnScreen(scrcoords);
float x = event.getRawX() + w.getLeft() - scrcoords[0];
float y = event.getRawY() + w.getTop() - scrcoords[1];
if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom())) {
KeypadUtils.hideSoftKeypad(this);
}
}
return ret;
} catch (Exception e) {
e.printStackTrace();
return true;
}
}
}<file_sep>package com.example.lastmileconnectivity.lastmileconnectivity.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import com.example.lastmileconnectivity.lastmileconnectivity.R;
import com.example.lastmileconnectivity.lastmileconnectivity.constant.IAppConstant;
import com.example.lastmileconnectivity.lastmileconnectivity.constant.SharePref;
import com.example.lastmileconnectivity.lastmileconnectivity.util.CustomUtil;
import com.kelltontech.ui.activity.BaseActivity;
import com.kelltontech.utils.ConnectivityUtils;
public class SplashActivity extends BaseActivity implements Animation.AnimationListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Animation animZoomIn = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom_in);
animZoomIn.setAnimationListener(this);
View view=findViewById(R.id.image);
assert view != null;
view.startAnimation(animZoomIn);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if(SharePref.getIsUserLoggedIn(SplashActivity.this)){
if(SharePref.getIsDriver(SplashActivity.this)){
if (ConnectivityUtils.isNetworkEnabled(SplashActivity.this)) {
startActivity(new Intent(SplashActivity.this, DriverHomeActivity.class));
}else{
startActivity(new Intent(SplashActivity.this, DriverOfflineActivity.class));
}
}else{
startActivity(new Intent(SplashActivity.this, UserHomeActivity.class));
}
}else{
startActivity(new Intent(SplashActivity.this, LoginActivity.class));
}
finish();
}
}, IAppConstant.SPLASH_TIME_OUT);
}
@Override
public void updateUi(boolean status, int action, Object serviceResponse) {
//no use
}
@Override
public void getData(int actionID) {
//no use
}
@Override
public void onAnimationStart(Animation animation) {
//no use
}
@Override
public void onAnimationEnd(Animation animation) {
//no use
}
@Override
public void onAnimationRepeat(Animation animation) {
//no use
}
}
<file_sep>/*
*
* Proprietary and confidential. Property of Kellton Tech Solutions Ltd. Do not disclose or distribute.
* You must have written permission from Kellton Tech Solutions Ltd. to use this code.
*
*/
package com.kelltontech.ui;
/**
* @author sachin.gupta
*/
public interface IScreen {
void getData(final int actionID);
/**
* Subclass should over-ride this method to update the UI with response. <br/>
* Subclass should note that it might being called from non-UI thread.
*
* @param serviceResponse
*/
void updateUi(final boolean status, final int actionID, final Object serviceResponse);
}
<file_sep>package com.example.lastmileconnectivity.lastmileconnectivity.util;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;
/**
* <h1><font color="orange">BaseLineTextView</font></h1>
* Custom ImageView with Aspect Ratio
*
* @author <NAME>
*/
public class AspectRatioImageView extends ImageView {
private final String TAG=AspectRatioImageView.class.getSimpleName();
public AspectRatioImageView(Context context) {
super(context);
Log.v(TAG, "AspectRatioImageView");
}
public AspectRatioImageView(Context context, AttributeSet attrs) {
super(context, attrs);
Log.v(TAG, "AspectRatioImageView");
}
public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
Log.v(TAG, "AspectRatioImageView");
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.v(TAG, "onMeasure");
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
setMeasuredDimension(width, height);
}
}<file_sep>package com.example.lastmileconnectivity.lastmileconnectivity.util;
import android.support.design.widget.Snackbar;
import android.view.View;
/**
* Created by faisal.khan on 3/18/2017.
*/
public class CustomUtil {
public static void showSnackBar(View view,String text){
Snackbar.make(view,text,Snackbar.LENGTH_LONG).show();
}
}
<file_sep>package com.example.lastmileconnectivity.lastmileconnectivity.fragment;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import com.example.lastmileconnectivity.lastmileconnectivity.R;
import com.example.lastmileconnectivity.lastmileconnectivity.util.CustomUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.kelltontech.ui.fragment.BaseFragment;
import com.kelltontech.utils.StringUtils;
import java.lang.reflect.Array;
public class UserHomeFragment extends BaseFragment {
private MapView mMapView;
private GoogleMap googleMap;
private String mSelectedPaymentOption;
private String[] mSelectedPaymentOptionArray;
private IUserHomeFragmentCallBack iUserHomeFragmentCallBack;
private EditText mEtSource;
private EditText mEtDestination;
private View mRootView;
public UserHomeFragment() {
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
iUserHomeFragmentCallBack=(IUserHomeFragmentCallBack)context;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
iUserHomeFragmentCallBack=(IUserHomeFragmentCallBack)activity;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_user_home, container, false);
mRootView=rootView.findViewById(R.id.root_view);
mEtSource=(EditText)rootView.findViewById(R.id.et_source);
mEtDestination=(EditText)rootView.findViewById(R.id.et_destination);
mSelectedPaymentOptionArray=getResources().getStringArray(R.array.payment_option);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
// For showing a move to my location button
googleMap.setMyLocationEnabled(true);
View myLocationButton = mMapView.findViewWithTag("GoogleMapMyLocationButton");
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) myLocationButton.getLayoutParams();
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
LatLng sydney = new LatLng(28.490982, 77.076140);
googleMap.addMarker(new MarkerOptions().position(sydney).title("<NAME>").snippet("Available near you "));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(13).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
Button btnBook = (Button) rootView.findViewById(R.id.btn_book);
Spinner payment_option = (Spinner) rootView.findViewById(R.id.payment_option);
btnBook.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String source=mEtSource.getText().toString();
String destination=mEtDestination.getText().toString();
if(!StringUtils.isNullOrEmpty(source) && !StringUtils.isNullOrEmpty(destination)){
iUserHomeFragmentCallBack.sendData(source,destination,mSelectedPaymentOption);
}else{
CustomUtil.showSnackBar(mRootView,"Please enter source ad destination");
}
}
});
payment_option.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mSelectedPaymentOption=mSelectedPaymentOptionArray[position];
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
@Override
public void getData(int actionID) {
}
@Override
public void updateUi(boolean status, int actionID, Object serviceResponse) {
}
public interface IUserHomeFragmentCallBack{
void sendData(String source,String destination,String paymentOption);
}
}<file_sep>ENABLE_STRICK_MODE=true
ARTIFACT_ID=androidframework
GROUP_ID=com.kelltontech
VERSION_NAME=1.0
VERSION_CODE=1
<file_sep>apply plugin: 'com.android.library'
dependencies {
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.jakewharton:disklrucache:2.0.2'
compile 'com.google.android.gms:play-services:6.5.87'
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:support-v4:22.2.1'
}
// Android build configuration
android {
compileSdkVersion 22 // Same as Target SDK.
buildToolsVersion '22.0.1'
lintOptions {
abortOnError false
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets', 'src/main/assets', 'src/main/assets/']
debug.setRoot('build-types/debug')
release.setRoot('build-types/release')
}
}
defaultConfig {
minSdkVersion 14
targetSdkVersion 23
}
productFlavors {
}
}
| 4ae07790aa77b9038ef7492cf5806b8ae8e1f4b6 | [
"Java",
"INI",
"Gradle"
] | 11 | Java | faisalkhan1690/LastMileConnectivity | 704168d216eebd052581d9b0611425baad88ba4b | 6f0fc723cf45d3ffa698fe8298a8293988e40ec0 |
refs/heads/master | <repo_name>cryptoguru1012/pressdalpha<file_sep>/app/models/company_selected_category_attribute.rb
class CompanySelectedCategoryAttribute < ApplicationRecord
belongs_to :company_selected_category,:inverse_of => :companycatatt
private
end
<file_sep>/app/models/coupon_reference.rb
class CouponReference < ActiveRecord::Base
private
end
<file_sep>/app/controllers/api/v1/create_job_controller.rb
class Api::V1::CreateJobController < Api::V1::ApplicationController
before_action :authenticate_user!
respond_to :json
def createjob
propertytext_param = eval(params[:propertytext])
properties_param = eval(params[:properties])
@task = Task.new(user_id: params[:user_id], company_id: params[:company_id], booking_date: params[:booking_date], booking_time: params[:booking_time], category_id: params[:category_id], properties: properties_param, propertytext: propertytext_param, address1: params[:address1], address2: params[:address2], city: params[:city], zipcode: params[:zipcode])
if @task.save
@job = Job.new(user_id: params[:user_id], task_id: @task.id, company_id: params[:company_id], booking_date: params[:booking_date], booking_time: params[:booking_time], price: params[:price], category_id: params[:category_id], properties: properties_param, propertytext: propertytext_param, recurring: params[:recurring], recurring_type: params[:recurring_type], recurring_weeks: params[:recurring_weeks], address1: params[:address1], address2: params[:address2], city: params[:city], zipcode: params[:zipcode], status: 'booking_made')
else
render json: { success: false, errorcode: 422, message: 'Parameters incorrect - submission failed.' }, status: 422
end
if @job.save
render json: {
status: 200,
message: 'Job submitted succesfully.',
job: @job.id
}.to_json
else
render json: { success: false, errorcode: 422, message: 'Parameters incorrect - submission failed.' }, status: 422
end
if params[:recurring] == 'true'
@subscription = Subscription.new(recurring_type: params[:recurring_type], first_job_id: @job.id, recurring_weeks_in_month: params[:recurring_weeks], recurring_months: params[:recurring_months], date_of_first_booking: params[:booking_date], recurring_price: params[:price], user_id: params[:user_id], partner_id: params[:partner_id], company_id: params[:company_id], category_id: params[:category_id])
end
if @subscription && @subscription.save
@job.update(subscription_id: @subscription.id)
end
end
protected
def job_params
params.permit(:user_id, :task_id, :recurring_months, :company_id, :booking_date, :booking_time, :price, :status, :category_id, :properties, :zipcode, :address1, :address2, :city, :country, :propertytext, :recurring, :recurring_type, :recurring_weeks, :subscription_id)
end
end
<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
before_action :set_user, only: %i[show edit update destroy myaccount]
before_action :authenticate_customer!, except: [:index]
before_action :set_user_type
# GET /users
# GET /users.json
def index
@users = User.all
end
# GET /users/1
# GET /users/1.json
def show; end
# GET /users/new
def new
@user = User.new
end
# GET /users/1/edit
def edit; end
def list
if current_customer
@user = User.find(current_customer.id)
else
redirect_to action: 'index', alert: 'Sorry you donot have permission to access.'
end
@tasks = Job.where(user_id: current_customer.id)
end
def transaction
if current_customer
@user = User.find(current_customer.id)
else
redirect_to action: 'index', alert: 'Sorry you donot have permission to access.'
end
@task = Transaction.where(customer_id: current_customer.id)
end
def step55
@task = Task.find(params[:id])
@id = params[:cid]
@category = Category.find(params[:cid])
@subcategories = Category.where(category_id: @id)
@compQuotations = CompanySelectedCategory.where(category_id: params[:cid], service_type: 'Quotation')
@compDirect = CompanySelectedCategory.where.not(service_type: 'Quotation').where(category_id: params[:cid])
@company = Company.where(is_active: true)
end
# GET /customers/task_details
def task_details
@task = Job.find(params[:id])
@id = params[:cid]
@category = Category.find(@task.category_id)
@subcategories = Category.where(category_id: @task.category_id)
@text = @task.task.propertytext
if current_customer
@user = User.find(current_customer.id)
else
redirect_to action: 'index', alert: 'Sorry you donot have permission to access.'
end
end
# GET /users/my_account
def my_account
if current_customer
@user = User.find(current_customer.id)
else
redirect_to action: 'index', alert: 'Sorry you donot have permission to access.'
end
end
def updateaccount
@customer = User.find(current_customer.id)
respond_to do |format|
if @customer.update(user_params)
format.html { redirect_to users_myaccount_url, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :my_account }
format.json { render json: @customer.errors, status: :unprocessable_entity }
end
end
end
# POST /users
# POST /users.json
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
def job_detail
@task = Job.find(params[:id])
end
private
def set_user_type
@user_type = user_type
end
def user_type
User.user_types.include?(params[:type]) ? params[:type] : 'Customer'
end
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = if params[:id]
User.find(params[:id])
else
User.find(current_user.id)
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(user_type.underscore.to_sym).permit(:first_name, :last_name, :email, :is_active, :is_admin, :date, :user_type, :phone, :about_me, :image, :password, :<PASSWORD>_<PASSWORD>, :address, :address1, :address2, :city, :country, :zipcode)
end
end
<file_sep>/app/models/packagedetail.rb
class Packagedetail < ApplicationRecord
belongs_to :company
private
end
<file_sep>/app/models/customer.rb
class Customer < User
has_many :jobs
private
end
<file_sep>/app/controllers/tasks_controller.rb
class TasksController < ApplicationController
before_action :store_user_location!, if: :storable_location?
before_action :set_task, only: [:show, :edit, :update, :destroy]
before_action :authenticate_customer!, :only => [:step6]
# GET /tasks
# GET /tasks.json
def index
@tasks = Task.all
end
def step1
@task = Task.new
end
def step2
# @categories = Category.where(category_id: 0).order("id DESC")
@task = Task.find(params[:id])
@postcode = @task.zipcode
# fetch company ids based on postcode
company_ids = CompaniesPostcode.joins(:postcode).where("postcodes.name = ?", @postcode[0...4]).pluck(:company_id)
categorieslookup = Category.joins(:company_selected_category).where("company_selected_categories.company_id in (?)", company_ids).pluck(:category_id)
@categories = Category.where("category_id in (?)", categorieslookup).where(:is_active => true).select("categories.id, categories.name, categories.image_file_name")
end
def step3
@task = Task.find(params[:id])
@postcode = @task.zipcode
@id = params[:cid]
@category = Category.find(params[:cid])
@subcategories = Category.includes(:questions).where(category_id: @id)
end
def step3update
@task = Task.find(params[:id])
respond_to do |format|
#task_params[:propertytext] = task_params[:propertytext].to_hash
if @task.update(task_params)
@tassk = Task.find(params[:id])
@prop = @tassk.properties
@prop.to_a
@text = Hash.new
puts "A fruit of type: #{@prop}"
sub_cat_id = []
sub_cat_att_id = []
@prop.each do |k,v|
#puts "Id: #{k} and V: #{v}"
# @cat = Category.find(k)
#@text.push(@cat.name)
#@text = @text+'<p><i class="fa-icon-ok text-contrast"></i> <span>Supplement Questions</span></p>'
# v.to_a
a = Hash.new
sub_cat_id << k
# v.each do |smk,smv|
# sub_cat_att_id << smk
# #puts "--smk: #{smk} and smv: #{smv}"
# smk1 = smk.to_i
# smk = smk.to_i unless smk.match(/[^[:digit:]]+/)
# #puts "Check number #{smk1} --- #{smk} "
# if smk.is_a? Integer
# @attr = CategoryAttribute.find(smk)
# if !@attr.blank?
# #puts "a == #{a}"
# if @attr.field_type == 'check_box'
# if smv=='1'
# @opt = 'Yes'
# else
# @opt = 'No'
# end
# a[@attr.name] = @opt
# elsif (@attr.field_type == 'text_field')
# a[@attr.name] = smv
# elsif (@attr.field_type == 'number_field')
# a[@attr.name] = smv
# elsif (@attr.field_type == 'radio')
# #a[@attr.name] = smv
# end
# end
#
# else
# puts "--smk: #{smk} and smv: #{smv}"
# @attr = CategoryAttribute.find(smv)
# if !@attr.blank?
# #puts "a == #{a}"
# a[@attr.group_name] = @attr.name
#
# end
# end
# # @text[@cat.name] = a
# end
end
@text = @text.to_hash
puts "task test #{@text}"
Task.where(id: @tassk.id).update(propertytext: @text)
format.html { redirect_to tasks_step4_path(id: @task, cid: params[:cid])}
format.json { render :step4, status: :ok, location: @task }
else
format.html { render :step3 }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
def step4
@task = Task.find(params[:id])
@prop = @task.properties
@prop.to_a
@text = Hash.new
puts "A fruit of type: #{@prop}"
sub_cat_id = []
sub_cat_att_id = []
answered_values = []
@total_hours = 0
@prop.each do |k,v|
p "----------",k
p "----------",v
if k == "category_id"
@cat = Category.find(v)
end
v.to_a
a = Hash.new
sub_cat_id << k
v.each do |smk,smv|
sub_cat_att_id << smk
#puts "--smk: #{smk} and smv: #{smv}"
smk1 = smk.to_i
smk = smk.to_i unless smk.match(/[^[:digit:]]+/)
#puts "Check number #{smk1} --- #{smk} "
if smk.is_a? Integer
@attr = CategoryAttribute.find(smk)
if !@attr.blank?
#puts "a == #{a}"
if @attr.field_type == 'check_box'
if smv=='1'
@total_hours += @attr.hour_per_item.to_i
@opt = 'Yes'
answered_values << true
else
@opt = 'No'
answered_values << false
end
a[@attr.name] = @opt
elsif (@attr.field_type == 'text_field')
@total_hours += @attr.hour_per_item.to_i
a[@attr.name] = smv
elsif (@attr.field_type == 'number_field')
@total_hours += @attr.hour_per_item.to_i
a[@attr.name] = smv
elsif (@attr.field_type == 'radio')
@total_hours += @attr.hour_per_item.to_i
#a[@attr.name] = smv
end
end
else
puts "--smk: #{smk} and smv: #{smv}"
@attr = CategoryAttribute.find(smv)
if !@attr.blank?
#puts "a == #{a}"
a[@attr.<EMAIL>] = @attr.name
end
end
if @cat.present?
@text[@cat.name] = a
end
end
end
selected_attr = CompanySelectedCategoryAttribute.where(category_id: sub_cat_id)
@company_ids = selected_attr.pluck(:company_id).uniq
# @companies = Company.where(id: company_ids).map{ |company| company.time_slots.group_by(&:user_slotable_id) }
@companies = CompanySelectedCategoryAttribute.where(company_id: @company_ids).group_by(&:company_id)
@green_companies = []
@orange_companies = []
@companies.each do |comp, values|
if values.pluck(:is_company_support) == answered_values
@green_companies << comp
elsif values.pluck(:is_company_support).include?(true)
@orange_companies << comp
end
end
@days = Company.where(id: @companies.values.flatten.pluck(:company_id)).map{|company| company.time_slots.map{|ts| ts if (ts.ending_time.hour - ts.starting_time.hour) >= @total_hours}.reject{|ele| ele.nil?}.group_by(&:user_slotable_id)}.reject{|day| day.blank?}
# @time_slots = Company.where(id: @company_ids).map{|company| company.time_slots.group(:id, :user_slotable_id).map{|company| company.week_day.day_name}}.flatten.uniq
puts "time slots #{@time_slots}"
@text = @task.propertytext
@id = params[:cid]
@category = Category.find(params[:cid])
@subcategories = Category.where(category_id: @id)
end
def step4update
@task = Task.find(params[:id])
respond_to do |format|
if @task.update(task_params)
format.html { redirect_to tasks_step5_path(id: @task, cid: params[:cid])}
format.json { render :step4, status: :ok, location: @task }
else
format.html { render :step3 }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
def step5
@task = Task.find(params[:id])
@text = @task.propertytext
@id = params[:cid]
@category = Category.find(@id)
@subcategories = Category.where(category_id: @id)
@compQuotations = CompanySelectedCategory.where(category_id: @id, service_type: 'Quotation')
@compDirect = CompanySelectedCategory.where.not(service_type: 'Quotation').where(category_id: @id)
@company = Company.where(is_active: true)
end
def step5update
@task = Task.find(params[:id])
respond_to do |format|
if @task.update(task_params)
format.html { redirect_to tasks_step6_path(id: @task, cid: params[:cid])}
format.json { render :step4, status: :ok, location: @task }
else
format.html { render :step3 }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
def step6
@task = Task.find(params[:id])
@id = params[:cid]
@user = User.find(current_customer.id)
@category = Category.find(@id)
@subcategories = Category.where(category_id: @id)
@compQuotations = CompanySelectedCategory.where(category_id: @id,service_type: 'Quotation')
@compDirect = CompanySelectedCategory.where.not(service_type: 'Quotation').where(category_id: @id)
@company = Company.where(is_active: true)
end
def step6update
@task = Task.find(params[:id])
respond_to do |format|
if @task.update(task_params)
customer = Stripe::Customer.create({
email: current_customer.email,
source: params[:stripeToken],
})
current_customer.update(stripe_id: customer.id, card_type: customer["sources"]["data"][0]["brand"], card_exp_year: customer["sources"]["data"][0]["exp_year"], card_exp_month: customer["sources"]["data"][0]["exp_month"], card_last4: customer["sources"]["data"][0]["last4"])
format.html { redirect_to jobs_save_path(id: @task, cid: params[:cid])}
format.json { render :step4, status: :ok, location: @task }
else
format.html { render :step3 }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
# GET /tasks/1
# GET /tasks/1.json
def show
end
# GET /tasks/new
def new
@task = Task.new
end
# GET /tasks/1/edit
def edit
end
# POST /tasks
# POST /tasks.json
def create
@task = Task.new(task_params)
@zipcode = params[:task][:zipcode][0...4]
company_ids = CompaniesPostcode.joins(:postcode).where("postcodes.name = ?", @zipcode[0...4]).pluck(:company_id)
@selected_categories = CompanySelectedCategory.joins(:category).\
where("company_id in (?)", company_ids).select("categories.id, categories.name, categories.image_file_name")
respond_to do |format|
if @selected_categories.size > 0
if @task.save(task_params)
format.html { redirect_to tasks_step2_url(id: @task)}
format.json { render :step2, status: :ok, location: @task }
else
format.html { render :step1 }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
else
format.html { redirect_to tasks_step1_url, notice: 'No result.' }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /tasks/1
# PATCH/PUT /tasks/1.json
def update
respond_to do |format|
if @task.update(task_params)
format.html { redirect_to @task, notice: 'Task was successfully updated.' }
format.json { render :show, status: :ok, location: @task }
else
format.html { render :edit }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tasks/1
# DELETE /tasks/1.json
def destroy
@task.destroy
respond_to do |format|
format.html { redirect_to tasks_url, notice: 'Task was successfully destroyed.' }
format.json { head :no_content }
end
end
def get_time_slots
@company = Company.find(params[:c_id])
@time_slots = @company.time_slots.where(week_day_id: params[:day].to_i+1)
@business_hours = @company.partner.available_slots
@business_hours = @business_hours[0].map{ |hour| hour if hour[:dow][0].to_i == params[:day].to_i }.reject{|hour| hour.nil?}
end
private
# Use callbacks to share common setup or constraints between actions.
def set_task
@task = Task.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def task_params
params.require(:task).permit(:user_id, :category_id, :zipcode, :is_active, :booking_date, :booking_time, :latitude, :longitude, :address, :company_id, :task_type, :address1, :address2, :city, :country, :freq, :properties=>{}, :propertytext=>{})
end
def integer?
[ # In descending order of likeliness:
/^[-+]?[1-9]([0-9]*)?$/, # decimal
/^0[0-7]+$/, # octal
/^0x[0-9A-Fa-f]+$/, # hexadecimal
/^0b[01]+$/ # binary
].each do |match_pattern|
return true if self =~ match_pattern
end
return false
end
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
include OrderBy
has_many :messages
has_many :jobs
has_many :subscriptions
has_many :conversations, foreign_key: :sender_id
has_many :notifications, foreign_key: :recipient_id
has_many :company_ratings
has_one :partner
has_one :customer
has_one :staff
def overall_rating
company_ratings.sum(:score) / company_ratings.size
end
self.inheritance_column = :user_type
# will subclass the User model
scope :partners, -> { where(user_type: 'Partner') }
scope :customers, -> { where(user_type: 'Customer') }
scope :staffs, -> { where(user_type: 'Staff') }
has_one :companylocation, :inverse_of => :user
accepts_nested_attributes_for :companylocation
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_attached_file :image, styles: {
small: '150x150>',
thumb: '50x50',
search: '248x200',
detail: '300x300',
listing: '200x200>'
}
validates_attachment :image, content_type: { content_type: [ "image/jpg", "image/jpeg", "image/png" ] }
class << self
def user_types
%w(Staff Customer Partner)
end
end
def image_url_thumb
image.url(:small)
end
def fullname
[first_name, last_name].join(" ")
end
def available_slots
data_arr = self.company.time_slots.pluck(:week_day_id, :starting_time, :ending_time)
business_hours = []
restricted_hours = []
data_arr.each do |arr_ele|
available_hours_hash = {dow: [arr_ele[0]-1], start: arr_ele[1].strftime("%H:%M"), end: arr_ele[2].strftime("%H:%M")}
business_hours << available_hours_hash
restricted_hours_hash = {start: arr_ele[1].strftime("%H:%M"), end: arr_ele[2].strftime("%H:%M")}
restricted_hours << restricted_hours_hash
end
return business_hours, restricted_hours
end
def reset_password!(password)
self.id = id
self.reset_password_token = nil
self.password = <PASSWORD>
save
end
private
end
<file_sep>/app/models/companies_postcode.rb
class CompaniesPostcode < ApplicationRecord
belongs_to :company
belongs_to :postcode
private
end
<file_sep>/app/models/company.rb
class Company < ActiveRecord::Base
# belongs_to :user,:inverse_of => :company
belongs_to :partner, class_name: 'User', foreign_key: 'user_id', optional: true
accepts_nested_attributes_for :partner # , update_only: true
has_and_belongs_to_many :postcode
has_many :time_slots, as: :user_slotable
has_many :packagedetails
has_many :company_ratings
has_many :jobs
has_many :messages
has_many :conversations, foreign_key: :recipient_id
def average_rating
company_ratings.sum(:score) / company_ratings.size
end
def cancellation_rate
cancellation_amount.to_f / partner.company.jobs.count.to_f
end
# TODO: Update user to partner in view for nested form
# accepts_nested_attributes_for :partner#, update_only: true
has_many :company_selected_category, dependent: :destroy
# has_many :time_slots
has_many :partner_opening_times
has_many :staffs, -> { where(user_type: 'Staff') }, class_name: 'User', foreign_key: 'company_id'
has_attached_file :image, styles: {
small: '150x150>',
thumb: '50x50',
search: '248x200',
detail: '300x300',
listing: '200x200>'
}
validates_attachment :image, content_type: { content_type: ['image/jpg', 'image/jpeg', 'image/png'] }
def image_url_thumb
image.url(:small)
end
def as_json(_options = {})
super(
only: %i[
id
company_name
location
preferred_partner
instant_book
], methods: %i[image_url_thumb average_rating]
)
end
#
# #Def to get orange and green companies
#
def self.get_companies_data(zipcode, properties, p_total_hours)
company_ids = CompaniesPostcode.joins(:postcode).where('postcodes.name = ?', zipcode[0...4]).pluck(:company_id)
companies = Company.all
prop = eval(properties)
prop.to_a
text = {}
sub_cat_id = []
sub_cat_att_id = []
answered_values = []
total_hours = 0
prop.each do |k, v|
@cat = Category.find(k)
v.to_a
a = {}
sub_cat_id << k
v.each do |smk, smv|
sub_cat_att_id << smk
smk1 = smk.to_i
smk = smk.to_i unless smk =~ /[^[:digit:]]+/
if smk.is_a? Integer
@attr = CategoryAttribute.find(smk)
unless @attr.blank?
if @attr.field_type == 'check_box'
if smv == '1'
total_hours += @attr.hour_per_item.to_i
@opt = 'Yes'
answered_values << true
else
@opt = 'No'
answered_values << false
end
a[@attr.name] = @opt
elsif @attr.field_type == 'text_field'
total_hours += @attr.hour_per_item.to_i
a[@attr.name] = smv
elsif @attr.field_type == 'number_field'
total_hours += @attr.hour_per_item.to_i
a[@attr.<EMAIL>] = smv
elsif @attr.field_type == 'radio'
total_hours += @attr.hour_per_item.to_i
end
end
else
@attr = CategoryAttribute.find(smv)
a[@attr.<EMAIL>] = @attr.name unless @attr.blank?
end
text[@cat.name] = a
end
end
selected_attr = CompanySelectedCategoryAttribute.where(category_id: sub_cat_id)
company_ids = selected_attr.pluck(:company_id).uniq
companies = CompanySelectedCategoryAttribute.where(company_id: company_ids).group_by(&:company_id)
green_companies = []
orange_companies = []
companies.each do |comp, values|
if values.pluck(:is_company_support) == answered_values
green_companies << comp
elsif values.pluck(:is_company_support).include?(true)
orange_companies << comp
end
end
days = Company.where(id: companies.values.flatten.pluck(:company_id)).map { |company| company.time_slots.map { |ts| ts if (ts.ending_time.hour - ts.starting_time.hour) >= p_total_hours.to_i }.reject(&:nil?).group_by(&:user_slotable_id) }.reject(&:blank?)
companies_with_green = Company.where(id: green_companies)
companies_with_orange = Company.where(id: orange_companies)
[companies_with_green, companies_with_orange]
end
private
end
<file_sep>/app/models/job.rb
class Job < ApplicationRecord
before_create :set_access_token
include OrderBy
serialize :properties, Hash
serialize :propertytext, Hash
belongs_to :company, foreign_key: "company_id", required: false
belongs_to :category, foreign_key: "category_id", required: false
belongs_to :user, foreign_key: "user_id", required: false
belongs_to :customer, foreign_key: "user_id", required: false
belongs_to :staff, foreign_key: "staff_id", required: false
belongs_to :task
scope :automatic_assign, -> { where(is_manual_booking: false) }
scope :pending_jobs, -> (company_id) { automatic_assign.where(company_id: company_id, status: 'booking_made') }
scope :assigned_jobs, -> (company_id) { automatic_assign.where(company_id: company_id, status: ['booking_confirmed', 'staff_enroute', 'booking_inprogress', 'dispute' ]) }
scope :completed_jobs, -> (company_id) { automatic_assign.where(company_id: company_id, status: 'booking_complete') }
scope :jobs_created_last_week, ->() {
where('created_at >= ?', 1.week.ago).count}
scope :jobs_last_week, ->() {
where('booking_date >= ?', 1.week.ago)}
scope :jobs_completed_last_week, ->() {
where('booking_date >= ?', 1.week.ago).where(status: ['booking_complete'])}
private
def set_access_token
self.view_job_id = generate_token
end
def generate_token
loop do
token = SecureRandom.hex(4)
break token unless User.where(id: token).exists?
end
end
end
<file_sep>/app/models/company_rating.rb
class CompanyRating < ApplicationRecord
belongs_to :company, foreign_key: "company_id", required: false
belongs_to :user, foreign_key: "user_id", required: false
belongs_to :customer, foreign_key: "user_id", required: false
belongs_to :job, foreign_key: "job_id", required: false
private
end
<file_sep>/app/controllers/staff/reports_controller.rb
class Staff::ReportsController < Staff::BaseStaffController
def index
@transactions= Transaction.all
end
def show
render template: "reports/#{params[:page]}"
end
def bookings_complete_last_week_json
render json: Job.where('booking_date >= ?', 1.week.ago).where(status: ['booking_complete']).where("staff_id = ?", current_staff.id)
end
end
<file_sep>/app/models/coupon.rb
class Coupon < ActiveRecord::Base
validates_uniqueness_of :originator, if: :referral?
def referral?
coupon_type == "referral"
end
private
end
<file_sep>/app/controllers/api/v1/company_list_controller.rb
class Api::V1::CompanyListController < Api::V1::ApplicationController
skip_before_action :authenticate_user!, raise: false
respond_to :json
def getcompanies
if (params[:zipcode].present? && params[:properties].present? && params[:total_hours].present? && params[:start_date].present? && params[:end_date].present?)
@companies_with_green, @companies_with_orange = Company.get_companies_data(params[:zipcode][0...4],params[:properties], params[:total_hours])
start_date = Date.parse(params[:start_date]).wday+1
end_date = Date.parse(params[:end_date]).wday+1
wdays = [start_date,end_date].sort
wday_range = Range.new(wdays[0], wdays[1])
@green_company = @companies_with_green.includes(:time_slots).where(
{
time_slots:{
week_day_id: wday_range
}
}
).order('companies.id ASC').as_json()
@orange_company = @companies_with_orange.includes(:time_slots).where(
{
time_slots:{
week_day_id: wday_range
}
}
).order('companies.id ASC').as_json()
render json:{
# green_companies: green_company,
# orange_companies: orange_company,
green_companies: @green_company.to_json(:only => [:id, :company_name, :location, :preferred_partner, :instant_book], :methods=> [:image_url_thumb, :average_rating]),
orange_companies: @orange_company.to_json(:only => [:id, :company_name, :location, :preferred_partner, :instant_book], :methods=> [:image_url_thumb, :average_rating]),
status: 200,
messages: "OK"
}
else
render json:{
status: 404,
messages: "Please provide all the following parameters 'zipcode, properties, start_date, end_date, total_hours', one of these is missing."
}
end
end
protected
end
<file_sep>/app/models/time_slot.rb
class TimeSlot < ApplicationRecord
belongs_to :week_day
belongs_to :added_by, foreign_key: "added_by_id", class_name: "Partner", optional: true
belongs_to :user_slotable, polymorphic: true
private
end
<file_sep>/app/models/manual_customer.rb
class ManualCustomer < ApplicationRecord
belongs_to :company, foreign_key: "company_id", required: false
belongs_to :partner, foreign_key: "partner_id", required: false
belongs_to :jobs
has_many :jobs
def formatted_name
"#{first_name} #{last_name} | #{email} | #{zipcode}"
end
private
end
<file_sep>/app/helpers/messages_helper.rb
module MessagesHelper
def self_or_other(message)
if current_customer.present?
message.user_id == current_customer.id ? "self" : "other"
elsif current_partner.present?
message.user == current_partner ? "self" : "other"
elsif current_staff.present?
message.user == current_staff ? "self" : "other"
end
end
def message_interlocutor(message)
message.user == message.conversation.sender ? message.conversation.sender : message.conversation.recipient
end
end
<file_sep>/app/models/content.rb
class Content < ApplicationRecord
private
end
<file_sep>/app/models/message.rb
class Message < ApplicationRecord
belongs_to :conversation
belongs_to :user, class_name: "User", foreign_key: "user_id"
belongs_to :recipient, class_name: "Company", foreign_key: "recipient_id"
has_attached_file :image, styles: {
small: '150x150>',
thumb: '50x50',
search: '248x200',
detail: '750x283',
listing: '298x198>'
}
validates_attachment_content_type :image, content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"]
def updated_date
message = Message.find(id)
date = message.updated_at.time.to_date.strftime("%d/%m/%Y")
end
def updated_time
message = Message.find(id)
date = message.updated_at.strftime("%H:%M")
end
def image_url_thumb
image.url(:small)
end
validates :body, presence: true
private
end
<file_sep>/app/models/partnerpreference.rb
class Partnerpreference < ApplicationRecord
private
end
<file_sep>/app/models/postcode.rb
class Postcode < ApplicationRecord
has_and_belongs_to_many :company
private
end
<file_sep>/app/models/transaction.rb
class Transaction < ApplicationRecord
belongs_to :company, foreign_key: "company_id", required: false
belongs_to :customer, foreign_key: "customer_id", required: false
belongs_to :partner, foreign_key: "trainer_id", required: false
belongs_to :job, foreign_key: "job_id", required: false
scope :transaction_revenue_last_week, ->() {
where('date >= ?', 1.week.ago).sum(:company_amount)}
scope :transaction_revenue_admin_last_week, ->() {
where('date >= ?', 1.week.ago).sum(:total_amount)}
private
def generate_random_id
self.id = SecureRandom.uuid
end
end
<file_sep>/app/models/video.rb
class Video < ApplicationRecord
private
end
<file_sep>/app/models/partner_opening_time.rb
class PartnerOpeningTime < ApplicationRecord
belongs_to :company
private
end
<file_sep>/app/models/concerns/order_by.rb
module OrderBy
extend ActiveSupport::Concern
included do
scope :default_order, -> { order 'id' }
scope :reverse_order, -> { order 'id desc' }
end
end
<file_sep>/app/controllers/api/v1/cancel_job_controller.rb
class Api::V1::CancelJobController < Api::V1::ApplicationController
before_action :authenticate_user!
before_action :ensure_params_exist
respond_to :json
def canceljob
userfind = User.find_by(:id => params[:user_id])
@job = Job.find_by(:id => params[:job_id])
@job.update_attributes(:status => "booking_cancelled")
if @job.update(:status => "booking_cancelled")
render json: {
status: 200,
message: 'The job has been cancelled.',
}.to_json, status: 200
else
render :json => { :success => false, :errorcode => 401, :message => "Error cancelling job" }, :status => 401
end
end
protected
def ensure_params_exist
if params[:user_id].present? && params[:job_id].present?
return
else
render :json => { :success => false, :errorcode => 422, :message => "missing user_id or job_id parameter" }, :status => 422
end
end
def job_params
params.permit(:user_id, :id)
end
end
<file_sep>/app/controllers/partner/jobs_controller.rb
class Partner::JobsController < Partner::BasePartnerController
before_action :set_job, only: [:show, :edit, :update, :destroy, :add_staff]
before_action :set_company, only: [:new, :list, :list_manual, :add_staff, :jobs_update]
# GET /jobs
# GET /jobs.json
def index
@jobs = Job.all
end
def save
@task = Task.find(params[:id])
@id = params[:cid]
@job = Job.new(:company_id => @task.company_id, :user_id => @task.user_id, :task_id => @task.id, :booking_date => @task.booking_date, :booking_time => @task.booking_time, :status => 'Pending', :price => '30.00', :post_date => Time.now, :category_id => @task.category_id, :latitude => @task.latitude, :longitude => @task.longitude, :address => @task.address, :properties => @task.properties, :zipcode => @task.zipcode)
respond_to do |format|
if @job.save
@string = "JOB0000"
@jobId = @string + @job.id.to_s
@job.update(:id=>@job.id, :view_job_id=>@jobId)
format.html { redirect_to users_list_path}
format.json { render :json => @job, status => "success" }
else
format.json { render :json => @job, status => "error" }
end
end
end
def list
@tasks = Job.all
@taskspending = Job.pending_jobs(@company.id).reverse_order
@tasksassigned = Job.assigned_jobs(@company.id).reverse_order
@taskscompleted = Job.completed_jobs(@company.id).reverse_order
end
def list_manual
@taskspending = Job.pending_jobs(@company.id).reverse_order
@tasksassigned = Job.assigned_jobs(@company.id).reverse_order
@taskscompleted = Job.completed_jobs(@company.id).reverse_order
end
# GET /customers/task_details
def details
@task = Job.find(params[:id])
@id = params[:cid]
@category = Category.find(@task.category_id)
@subcategories = Category.where(category_id: @task.category_id)
@text = @task.propertytext
respond_to do |format|
format.html
format.js
end
end
def manualdetails
@task = Job.find(params[:id])
@id = params[:cid]
@category = Category.find(@task.category_id)
@subcategories = Category.where(category_id: @task.category_id)
@manual_customer = ManualCustomer.find(@task.manual_customers_id)
@text = @task.propertytext
respond_to do |format|
format.html
format.js
end
end
def add_staff
@jobs = Job.find(params[:id])
@users = @company.staffs.reverse_order
@users = @users.map{|s| s if (s.time_slots.where(working_date: @jobs.booking_date).present? && Job.where(booking_date: @jobs.booking_date).where.not(staff_id: s.id).or(Job.where(booking_date: @jobs.booking_date).where(staff_id: nil)).present?)}.compact
respond_to do |format|
format.html
format.js
end
end
def jobs_update
@jobs = Job.find(params[:id])
@jobs.update(job_params)
respond_to do |format|
if @jobs.update(job_params)
format.html { redirect_to partner_jobs_list_path
flash[:success] = 'Job was successfully updated'
}
format.js
format.json { render :show, status: :ok, location: @job }
else
format.html { render :edit }
format.json { render json: @job.errors, status: :unprocessable_entity }
end
end
end
def staff_enroute
@job = Job.find(params[:id])
@job.update_attributes(:status => "staff_enroute")
respond_to do |format|
if @job.update(job_params)
format.html { redirect_to partner_jobs_list_path
flash[:success] = 'Job updated to En-Route'
}
format.js
format.json { render :show, status: :ok, location: @job }
end
end
end
def booking_inprogress
@job = Job.find(params[:id])
@job.update_attributes(:status => "booking_inprogress")
respond_to do |format|
if @job.update(job_params)
format.html { redirect_to partner_jobs_list_path
flash[:success] = 'Job updated to In Progress'
}
format.js
format.json { render :show, status: :ok, location: @job }
end
end
end
def booking_complete
@job = Job.find(params[:id])
@job.update_attributes(:status => "booking_complete")
respond_to do |format|
if @job.update(job_params)
format.html { redirect_to partner_jobs_list_path
flash[:success] = 'Job completed.'
}
format.js
format.json { render :show, status: :ok, location: @job }
end
end
end
def booking_rejected
@job = Job.find(params[:id])
@job.update_attributes(:status => "booking_rejected")
respond_to do |format|
if @job.update(job_params)
format.html { redirect_to partner_jobs_list_path
flash[:warning] = 'Job Rejected.'
}
format.js
format.json { render :show, status: :ok, location: @job }
end
end
end
# GET /jobs/1
# GET /jobs/1.json
def show
end
# GET /jobs/new
def new
@manual_customers = ManualCustomer.all
@job = Job.new
respond_to do |format|
format.html
format.js
end
end
# GET /jobs/1/edit
def edit
end
# POST /jobs
# POST /jobs.json
def create
@job = Job.new(job_params)
respond_to do |format|
if @job.save
format.html { redirect_to partner_jobs_list_manual_path, notice: 'Job was successfully created.' }
format.json { render :show, status: :created, location: @job }
format.js { redirect_to partner_jobs_list_manual_path, notice: 'Job was successfully created.' }
else
format.html { redirect_to partner_jobs_list_manual_path, notice: 'Job failed.' }
format.json { render json: @job.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /jobs/1
# PATCH/PUT /jobs/1.json
def update
@jobs = Job.find(params[:id])
@jobs.update(job_params)
respond_to do |format|
if @job.update(job_params)
format.html { redirect_to partner_jobs_list_path, notice: 'Job was successfully updated.' }
format.json { render :show, status: :ok, location: @job }
else
format.html { render :edit }
format.json { render json: @job.errors, status: :unprocessable_entity }
end
end
end
# DELETE /jobs/1
# DELETE /jobs/1.json
def destroy
@job.destroy
respond_to do |format|
format.html { redirect_to jobs_url, notice: 'Job was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_job
@job = Job.find(params[:id])
end
def set_company
@company = current_partner.company
end
# Never trust parameters from the scary internet, only allow the white list through.
def job_params
params.permit(:job, :user_id, :task_id, :company_id, :booking_date, :booking_time, :price, :manual_customers_id, :is_manual_booking, :status, :view_job_id, :post_date, :category_id, :address1, :city, :country, :latitude, :longitude, :address, :properties, :zipcode, :staff_id)
end
def task_params
params.require(:task).permit(:user_id, :category_id, :zipcode, :is_active, :is_manual_booking, :booking_date, :booking_time, :latitude, :longitude, :address, :company_id, :task_type, :address1, :address2, :city, :country, :freq, :properties=>{}, :propertytext=>{})
end
end
<file_sep>/app/controllers/api/v1/category_attributes_controller.rb
class Api::V1::CategoryAttributesController < Api::V1::ApplicationController
skip_before_action :authenticate_user!, raise: false
before_action :ensure_params_exist
respond_to :json
def index
@category = Category.where(:category_id => params[:category_id])
@subcategories = @category.includes(:questions).where(:category_id => params[:category_id])
render json: {
status: 200,
message: 'Below is a list of questions for this category',
render: @subcategories.as_json(:include => { :questions => {:include => { :category_attribute_options => {:only => [:id, :options, :option_hours, :option_price] } }, :only => [:id, :name, :information, :field_type, :hour_per_item, :material_cost, :required] } }, :only => [:id, :name])
}.to_json, status: 200
end
protected
def ensure_params_exist
return unless params[:category_id].blank?
render json: {
status: 406,
message: 'The category_id parameter is missing'
}.to_json, status: 406
end
def category_attributes_params
params.permit(:name, :category_id, :information)
end
end
<file_sep>/app/controllers/charges_controller.rb
class ChargesController < ApplicationController
before_action :authenticate_customer!, except: [:new]
before_action :redirect_to_signup, only: [:new]
def show
end
def new
end
def create
customer = if current_customer.stripe_id?
Stripe::Customer.retrieve(current_customer.stripe_id)
else
Stripe::Customer.create(email: current_customer.email)
end
options = {
stripe_id: customer.id,
}
# Only update the card on file if we're adding a new one
options.merge!(
card_last4: params[:card_last4],
card_exp_month: params[:card_exp_month],
card_exp_year: params[:card_exp_year],
card_type: params[:card_brand]
) if params[:card_last4]
current_customer.update(options)
redirect_to root_path
end
def destroy
customer = Stripe::Customer.retrieve(current_customer.stripe_id)
customer.subscriptions.retrieve(current_customer.stripe_subscription_id).delete
current_customer.update(stripe_subscription_id: nil)
redirect_to root_path, notice: "Your subscription has been canceled."
end
private
def redirect_to_signup
if !customer_signed_in?
session["customer_return_to"] = new_charge_path
redirect_to new_customer_registration_path
end
end
end
| 1852adcada504d1c11c1e072b89ed48b0b9d34d3 | [
"Ruby"
] | 30 | Ruby | cryptoguru1012/pressdalpha | fa1cac24872a53694f60b9f26b3ed12fc85b96c5 | b38e499d06049664618f3270cdcc4a8e179e4239 |
refs/heads/master | <repo_name>maruu987654321/ruta<file_sep>/README.md
## Run with virtualenv
- Create a virtualenv folder `virtualenv -p python3 venv`
- Activate `source venv/bin/activate`
- Install the requirements `pip install -r requirements.txt`
- Run gunicorn `gunicorn app:app --bind 0.0.0.0:5000 --reload`
## Run with Docker
- Build the image with `docker build -t project_dep .`
- Run the container with `docker run -d -p 5000:5000 -e PORT=5000 --name project-server project_dep`
- Check that the container is running
- Go to `localhost:5000`. Ready!!!! )
gcloud app deploy app.yaml - deploy on google cloud
<file_sep>/requirements.txt
Click==7.0
gunicorn==19.7.1
Flask==1.0.2
itsdangerous==1.1.0
Jinja2==2.10
Pillow==5.3.0
MarkupSafe==1.1.0
pytesseract==0.2.5
Werkzeug==0.14.1
<file_sep>/main.py
from flask import Flask, jsonify
import pytesseract
import os
try:
import Image
except ImportError:
from PIL import Image
app = Flask(__name__)
@app.route('/')
def homepage():
# Basic OCR
return(pytesseract.image_to_string(Image.open('1.jpg')).encode('utf-8'))
if __name__ == '__main__':
# This is used when running locally only. When deploying to Google App
# Engine, a webserver process such as Gunicorn will serve the app. This
# can be configured by adding an `entrypoint` to app.yaml.
| 5802ce83f37bd5347ff2dd915e49bf9f15d63597 | [
"Markdown",
"Python",
"Text"
] | 3 | Markdown | maruu987654321/ruta | 0ab48b864ebf56858ab336c27673d732a0641fe1 | e16d23fa8477bbeabb9918c4dec49e4e38e925d9 |
refs/heads/master | <file_sep>#include<stdio.h>
#include<conio.h>
#include<dos.h>
#define max 5
int top=-1; /* Global varible */
int stack[max]; /* Global varible */
int push(int top,int data) /* Push_Data */
{
if(top==(max-1))
{
printf("Stack is full");
sleep(2);
}
else
{
top++;
stack[top]=data;
}
return top;
}
/* POP stack data */
int pop()
{
int i;
if(top==-1)
{
printf("Stack is empty");
sleep(2);
}
else
{
i=stack[top--];
printf("popped data=%d",i);
sleep(2);
}
return top;
}
/* Display stack data */
void display(int top)
{
int i;
if(top==-1)
{
printf("Stack is empty");
sleep(2);
}
else
{
for(i=top;i>=0;i--)
{
printf("%3d",stack[i]);
}
sleep(2);
}
}
/* Main Function Definition */
void main()
{
int ch,data;
while(1)
{
clrscr();
printf("Stack menu\n");
printf("1.push\n");
printf("2.pop\n");
printf("3.Display\n");
printf("0.exit\n");
printf("Enter your choice=");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter data=");
scanf("%d",&data);
top=push(top,data);break;
case 2:
top=pop();
break;
case 3:
display(top);break;
case 0:exit(0);
default:printf("invalid input plz try again");sleep(3);
}
}
}
| 127476ee6ecb59d2f9270993adda6a726384a84b | [
"C"
] | 1 | C | durgeshkumargupta/Stack_Rule_1 | 9e79a069d4e1f05668801f72f8a4a6d067baa707 | c495de5f72b389d590c7de21b50c5dc5d55d7f5d |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CityInformationApp
{
public partial class CityInfoUI : Form
{
City aCity = new City();
private bool isUpdateMode = false;
private int cityId = 0;
public CityInfoUI()
{
InitializeComponent();
ShowCityInfoInListView();
}
private void saveButton_Click(object sender, EventArgs e)
{
aCity.name = cityNameTextBox.Text;
aCity.about = aboutTextBox.Text;
aCity.country = countryTextBox.Text;
if (isUpdateMode)
{
string msg = aCity.UpdateCity(aCity,cityId);
MessageBox.Show(msg);
ShowCityInfoInListView();
saveButton.Text = "Save";
cityId = 0;
isUpdateMode = false;
cityNameTextBox.Enabled = true;
}
else
{
string message = aCity.SaveCityInfornamtion(aCity);
MessageBox.Show(message);
ShowCityInfoInListView();
cityNameTextBox.Clear();
aboutTextBox.Clear();
countryTextBox.Clear();
}
}
private void ShowCityInfoInListView()
{
double serialNo = 1;
showCityListView.Items.Clear();
List<City> cities = aCity.GetAllCityInformation();
foreach (var city in cities)
{
ListViewItem item = new ListViewItem(serialNo.ToString());
item.SubItems.Add(city.name);
item.SubItems.Add(city.about);
item.SubItems.Add(city.country);
showCityListView.Items.Add(item);
serialNo++;
}
}
private void searchButton_Click(object sender, EventArgs e)
{
string searchText = searchTextBox.Text;
if (searchByCityRadioButton.Checked)
{
ShowSearchByCityInListView(searchText);
}
else if(searchByCountryRadioButton.Checked)
{
ShowSearchByCountryItemInListView(searchText);
}
}
private void ShowSearchByCityInListView(string searchText)
{
double serialNo = 1;
showCityListView.Items.Clear();
List<City> cities = aCity.GetAllSearechInformationByCity(searchText);
foreach (var city in cities)
{
ListViewItem item = new ListViewItem(serialNo.ToString());
item.SubItems.Add(city.name);
item.SubItems.Add(city.about);
item.SubItems.Add(city.country);
showCityListView.Items.Add(item);
serialNo++;
}
}
private void ShowSearchByCountryItemInListView(string searchText)
{
double serialNo = 1;
showCityListView.Items.Clear();
List<City> cities = aCity.GetAllSearechInformationByCountry(searchText);
foreach (var city in cities)
{
ListViewItem item = new ListViewItem(serialNo.ToString());
item.SubItems.Add(city.name);
item.SubItems.Add(city.about);
item.SubItems.Add(city.country);
showCityListView.Items.Add(item);
serialNo++;
}
}
private void showCityListView_DoubleClick(object sender, EventArgs e)
{
ListViewItem item = showCityListView.SelectedItems[0];
int id = int.Parse(item.Text.ToString());
City city = aCity.GetCityById(id);
if (city != null)
{
isUpdateMode = true;
saveButton.Text = "Update";
cityId = city.id;
cityNameTextBox.Enabled = false;
cityNameTextBox.Text = city.name;
aboutTextBox.Text = city.about;
countryTextBox.Text = city.country;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CityInformationApp
{
class City
{
public int id;
public string name;
public string about;
public string country;
SqlConnection aConnection = new SqlConnection();
string connectionString = ConfigurationManager.ConnectionStrings["CityInfoDBConnectionString"].ConnectionString;
public string SaveCityInfornamtion(City aCity)
{
if (aCity.name.Length>=4)
{
if (HasthisCityAlreadyinSystem(aCity.name))
{
return "This City Already in System!!! Try another one";
}
else
{
aConnection.ConnectionString = connectionString;
aConnection.Open();
string query = string.Format("INSERT INTO t_city VALUES('{0}','{1}','{2}')", aCity.name, aCity.about, aCity.country);
SqlCommand aCommand = new SqlCommand(query, aConnection);
int rowAffected = aCommand.ExecuteNonQuery();
aConnection.Close();
if (rowAffected > 0)
{
return "Save Successful";
}
else
{
return "Failed";
}
}
}
else
{
return "City Name Must be at least 4 Characters Long";
}
}
private bool HasthisCityAlreadyinSystem(string name)
{
aConnection.ConnectionString = connectionString;
aConnection.Open();
string query = string.Format("SELECT * FROM t_city WHERE name='{0}'", name);
SqlCommand aCommand = new SqlCommand(query, aConnection);
SqlDataReader aReader = aCommand.ExecuteReader();
bool message = aReader.HasRows;
aConnection.Close();
return message;
}
public List<City> GetAllCityInformation()
{
aConnection.ConnectionString = connectionString;
aConnection.Open();
string query = string.Format("SELECT * FROM t_city");
SqlCommand aCommand = new SqlCommand(query, aConnection);
SqlDataReader aReader = aCommand.ExecuteReader();
List<City> cities = new List<City>();
if (aReader.HasRows)
{
while (aReader.Read())
{
City aCity = new City();
aCity.id = Convert.ToInt32(aReader[0].ToString());
aCity.name= aReader[1].ToString();
aCity.about= aReader[2].ToString();
aCity.country = aReader[3].ToString();
cities.Add(aCity);
}
}
aConnection.Close();
return cities;
}
public City GetCityById(int id)
{
aConnection.ConnectionString = connectionString;
aConnection.Open();
string query = string.Format("SELECT * FROM t_city WHERE id='{0}'", id);
SqlCommand aCommand = new SqlCommand(query, aConnection);
SqlDataReader aReader = aCommand.ExecuteReader();
City aCity = new City();
while (aReader.Read())
{
aCity.id = (int)aReader[0];
aCity.name = aReader[1].ToString();
aCity.about = aReader[2].ToString();
aCity.country = aReader[3].ToString();
}
aReader.Close();
aConnection.Close();
return aCity;
}
public string UpdateCity(City aCity, int cityId)
{
aConnection.ConnectionString = connectionString;
aConnection.Open();
string query = string.Format("UPDATE t_city SET about='{0}',country='{1}' WHERE id ={2}", aCity.about, aCity.country, cityId);
SqlCommand aCommand = new SqlCommand(query, aConnection);
int rowAffected = aCommand.ExecuteNonQuery();
aConnection.Close();
if (rowAffected > 0)
{
return "Update Successful";
}
else
{
return "Update Failed";
}
}
public List<City> GetAllSearechInformationByCountry(string searchText)
{
aConnection.ConnectionString = connectionString;
aConnection.Open();
string query = string.Format("SELECT * FROM t_city WHERE country='{0}' ", searchText);
SqlCommand aCommand = new SqlCommand(query, aConnection);
SqlDataReader aReader = aCommand.ExecuteReader();
List<City> cities = new List<City>();
if (aReader.HasRows)
{
while (aReader.Read())
{
City aCity = new City();
aCity.id = Convert.ToInt32(aReader[0].ToString());
aCity.name = aReader[1].ToString();
aCity.about = aReader[2].ToString();
aCity.country = aReader[3].ToString();
cities.Add(aCity);
}
}
aConnection.Close();
return cities;
}
public List<City> GetAllSearechInformationByCity(string searchText)
{
aConnection.ConnectionString = connectionString;
aConnection.Open();
string query = string.Format("SELECT * FROM t_city WHERE name='{0}' ", searchText);
SqlCommand aCommand = new SqlCommand(query, aConnection);
SqlDataReader aReader = aCommand.ExecuteReader();
List<City> cities = new List<City>();
if (aReader.HasRows)
{
while (aReader.Read())
{
City aCity = new City();
aCity.id = Convert.ToInt32(aReader[0].ToString());
aCity.name = aReader[1].ToString();
aCity.about = aReader[2].ToString();
aCity.country = aReader[3].ToString();
cities.Add(aCity);
}
}
aConnection.Close();
return cities;
}
}
}
| e91340d58964043cb54006515e9c2cb441e7da2c | [
"C#"
] | 2 | C# | arrobin/CityInformationApp | ba2b423d721f716476ca6f70ca2a5fa4cb4962b0 | 0cf7267e0ee2078d554fa637bb1d3e53657881de |
refs/heads/master | <repo_name>IDgtl/Pacman<file_sep>/Pacman/Dot.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pacman
{
public class Dot : IDrawable
{
public SizeF Size { get; private set; }
public PointF Location { get; private set; }
public bool isEaten;
private Color color;
private Pen pen;
private List<Direction> directions;
public Dot(PointF loc)
{
Size = new SizeF(10, 10);
Location = loc;
isEaten = false;
color = Color.White;
pen = new Pen(color);
directions = new List<Direction>();
this.checkDirections();
}
public void Draw(Graphics g)
{
if (!isEaten)
{
g.FillEllipse(pen.Brush, Location.X + 10, Location.Y + 10, 10, 10);
}
}
private void checkDirections()
{
if (canMove(new PointF(Location.X + 30, Location.Y)))
{
directions.Add(Direction.Right);
}
if (canMove(new PointF(Location.X - 30, Location.Y)))
{
directions.Add(Direction.Left);
}
if (canMove(new PointF(Location.X, Location.Y + 30)))
{
directions.Add(Direction.Down);
}
if (canMove(new PointF(Location.X, Location.Y - 30)))
{
directions.Add(Direction.Up);
}
}
private bool canMove(PointF newLocation)
{
foreach (var wall in BattleField.Walls)
{
if (overlapsWall(wall, newLocation))
{
return false;
}
}
return true;
}
private bool overlapsWall(Wall wall, PointF possibleLocation)
{
if ((possibleLocation.X >= wall.Location.X) && (possibleLocation.Y >= wall.Location.Y))
{
if ((possibleLocation.X < (wall.Location.X + wall.Size.Width)) && (possibleLocation.Y < (wall.Location.Y + wall.Size.Height))) return true;
}
else if ((possibleLocation.X <= wall.Location.X) && (possibleLocation.Y >= wall.Location.Y))
{
if (((possibleLocation.X + Size.Width) > wall.Location.X) && (possibleLocation.Y < (wall.Location.Y + wall.Size.Height))) return true;
}
else if ((possibleLocation.X <= wall.Location.X) && (possibleLocation.Y <= wall.Location.Y))
{
if (((possibleLocation.X + Size.Width) > wall.Location.X) && ((possibleLocation.Y + Size.Height) > wall.Location.Y)) return true;
}
else if ((possibleLocation.X >= wall.Location.X) && (possibleLocation.Y <= wall.Location.Y))
{
if ((possibleLocation.X < (wall.Location.X + wall.Size.Width)) && ((possibleLocation.Y + Size.Height) > wall.Location.Y)) return true;
}
return false;
}
}
}
<file_sep>/Pacman/CharacterBase.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pacman
{
public abstract class CharacterBase : IDrawable
{
protected SizeF size;
protected PointF location;
protected Color color;
protected Pen pen;
protected Direction direction;
protected Direction newDirection;
protected int speed;
public CharacterBase()
{
size = new SizeF(30.0F, 30.0F);
direction = Direction.Stopped;
newDirection = Direction.Stopped;
speed = (int)200.0F / GameWindow.FPS;
}
public CharacterBase(PointF loc, Color col) : this()
{
location = loc;
color = col;
pen = new Pen(color);
}
public abstract void Draw(Graphics g);
}
}
<file_sep>/Pacman/Wall.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pacman
{
public class Wall : IDrawable
{
public SizeF Size { get; private set; }
public PointF Location { get; private set; }
private Color color;
private Pen pen;
public Wall(float X, float Y, float width, float height)
{
Location = new PointF(X, Y);
Size = new SizeF(width, height);
color = Color.Blue;
pen = new Pen(color);
}
public void Draw(Graphics g)
{
g.FillRectangle(pen.Brush, Location.X, Location.Y, Size.Width, Size.Height);
}
}
}
<file_sep>/Pacman/BattleField.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace Pacman
{
public enum Direction
{
Up,
Down,
Left,
Right,
Stopped
}
public class BattleField
{
public static Bitmap Background { get; private set; }
private Pacman pacman;
private Ghost pinky;
public static List<Wall> Walls { get; private set; }
public static List<Dot> Dots { get; private set; }
public BattleField(Bitmap background)
{
Background = background;
pacman = new Pacman(new PointF(210, 210));
pinky = new Ghost(new PointF(30, 30), Color.Pink);
Walls = new List<Wall>();
Dots = new List<Dot>();
CreateInterior();
CreateDots();
//System.Windows.Forms.MessageBox.Show(Dots.Count.ToString());
}
public void DrawGraphic()
{
using (var g = Graphics.FromImage(Background))
{
this.DrawBackGround(g);
this.DrawInterior(g);
this.DrawDots(g);
pacman.Draw(g);
pinky.Draw(g);
}
}
private void DrawBackGround(Graphics g)
{
g.Clear(Color.Black);
}
public void ChangePacmanDirection(Direction d)
{
pacman.ChangeDirection(d);
}
private void DrawInterior(Graphics g)
{
foreach(var wall in Walls)
{
wall.Draw(g);
}
}
private void CreateInterior()
{
Walls.Add(new Wall(30, 0, 390, 30));
Walls.Add(new Wall(90, 60, 60, 30));
Walls.Add(new Wall(180, 60, 90, 30));
Walls.Add(new Wall(300, 60, 60, 30));
Walls.Add(new Wall(120, 120, 90, 30));
Walls.Add(new Wall(240, 120, 90, 30));
Walls.Add(new Wall(30, 180, 60, 30));
Walls.Add(new Wall(150, 180, 60, 30));
Walls.Add(new Wall(240, 180, 60, 30));
Walls.Add(new Wall(360, 180, 60, 30));
Walls.Add(new Wall(30, 240, 60, 30));
Walls.Add(new Wall(150, 240, 150, 30));
Walls.Add(new Wall(360, 240, 60, 30));
Walls.Add(new Wall(120, 300, 90, 30));
Walls.Add(new Wall(240, 300, 90, 30));
Walls.Add(new Wall(90, 360, 60, 30));
Walls.Add(new Wall(180, 360, 90, 30));
Walls.Add(new Wall(300, 360, 60, 30));
Walls.Add(new Wall(30, 420, 390, 30));
Walls.Add(new Wall(0, 0, 30, 210));
Walls.Add(new Wall(0, 240, 30, 210));
Walls.Add(new Wall(60, 60, 30, 90));
Walls.Add(new Wall(60, 300, 30, 90));
Walls.Add(new Wall(120, 180, 30, 90));
Walls.Add(new Wall(300, 180, 30, 90));
Walls.Add(new Wall(360, 60, 30, 90));
Walls.Add(new Wall(360, 300, 30, 90));
Walls.Add(new Wall(420, 0, 30, 210));
Walls.Add(new Wall(420, 240, 30, 210));
}
private void DrawDots(Graphics g)
{
foreach(var dot in Dots)
{
dot.Draw(g);
}
}
private void CreateDots()
{
for (int i = 0; i <= Background.Width - 30; )
{
for (int j = 0; j <= Background.Height - 30; )
{
PointF newLocation = new PointF(i, j);
bool canCreate = true;
foreach (var wall in Walls)
{
if (overlapsWall(wall, newLocation))
{
canCreate = false;
break;
}
}
if (canCreate)
{
Dots.Add(new Dot(newLocation));
}
j += 30;
}
i += 30;
}
}
private bool overlapsWall(Wall wall, PointF possibleLocation)
{
if ((possibleLocation.X >= wall.Location.X) && (possibleLocation.Y >= wall.Location.Y))
{
if ((possibleLocation.X < (wall.Location.X + wall.Size.Width)) && (possibleLocation.Y < (wall.Location.Y + wall.Size.Height))) return true;
}
else if ((possibleLocation.X <= wall.Location.X) && (possibleLocation.Y >= wall.Location.Y))
{
if (((possibleLocation.X + 30) > wall.Location.X) && (possibleLocation.Y < (wall.Location.Y + wall.Size.Height))) return true;
}
else if ((possibleLocation.X <= wall.Location.X) && (possibleLocation.Y <= wall.Location.Y))
{
if (((possibleLocation.X + 30) > wall.Location.X) && ((possibleLocation.Y + 30) > wall.Location.Y)) return true;
}
else if ((possibleLocation.X >= wall.Location.X) && (possibleLocation.Y <= wall.Location.Y))
{
if ((possibleLocation.X < (wall.Location.X + wall.Size.Width)) && ((possibleLocation.Y + 30) > wall.Location.Y)) return true;
}
return false;
}
}
}
<file_sep>/Pacman/Ghost.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pacman
{
class Ghost : CharacterBase
{
System.Drawing.Drawing2D.GraphicsPath gp;
public Ghost(PointF loc, Color col) : base(loc, col)
{
this.CreateBody();
}
public override void Draw(Graphics g)
{
this.DrawBody(g);
}
private void CreateBody()
{
gp = new System.Drawing.Drawing2D.GraphicsPath();
gp.AddArc(location.X, location.Y, 30.0F, 30.0F, 180, 180);
gp.AddLine(new PointF(location.X + 30.0F, location.Y + 15.0F), new PointF(location.X + 30.0F, location.Y + 30.0F));
gp.AddLine(new PointF(location.X + 30.0F, location.Y + 30.0F), new PointF(location.X + 28.5F, location.Y + 30.0F));
gp.AddArc(location.X + 16.5F, location.Y + 17.0F, 12.0F, 26.0F, 180, 180);
gp.AddLine(new PointF(location.X + 16.5F, location.Y + 30.0F), new PointF(location.X + 13.5F, location.Y + 30.0F));
gp.AddArc(location.X + 1.5F, location.Y + 17.0F, 12.0F, 26.0F, 180, 180);
gp.AddLine(new PointF(location.X + 1.5F, location.Y + 30.0F), new PointF(location.X, location.Y + 30.0F));
//gp.AddLine(new PointF(location.X, location.Y + 30.0F), new PointF(location.X, location.Y + 15.0F));
}
private void DrawBody(Graphics g)
{
g.FillPath(pen.Brush, gp);
g.FillEllipse(Brushes.White, location.X + 6, location.Y + 3, 6, 10);
g.FillEllipse(Brushes.Red, location.X + 7, location.Y + 6, 4, 4);
g.FillEllipse(Brushes.White, location.X + 18, location.Y + 3, 6, 10);
g.FillEllipse(Brushes.Red, location.X + 19, location.Y + 6, 4, 4);
}
}
}
<file_sep>/Pacman/GameWindow.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Pacman
{
public partial class GameWindow : Form
{
private Bitmap background;
private BattleField bf;
public static int FPS = 50;
public GameWindow()
{
InitializeComponent();
GameInit();
}
private void GameInit()
{
System.Timers.Timer drawTimer = new System.Timers.Timer(1000/FPS);
this.Load += GameWindow_Load;
this.Paint += GameWindow_Paint;
drawTimer.Elapsed += DrawTimer_Elapsed;
this.KeyDown += GameWindow_KeyDown;
drawTimer.Start();
}
private void GameWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Right)
{
bf.ChangePacmanDirection(Direction.Right);
}
else if (e.KeyCode == Keys.Left)
{
bf.ChangePacmanDirection(Direction.Left);
}
else if (e.KeyCode == Keys.Up)
{
bf.ChangePacmanDirection(Direction.Up);
}
else if (e.KeyCode == Keys.Down)
{
bf.ChangePacmanDirection(Direction.Down);
}
}
private void DrawTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
bf.DrawGraphic();
Invalidate();
}
private void GameWindow_Paint(object sender, PaintEventArgs e)
{
if (background != null)
{
e.Graphics.DrawImageUnscaled(background, Point.Empty);
}
}
private void GameWindow_Load(object sender, EventArgs e)
{
if (background == null)
{
background = new Bitmap(ClientSize.Width, ClientSize.Height);
}
bf = new BattleField(background);
}
}
}
<file_sep>/Pacman/Pacman.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace Pacman
{
public class Pacman : CharacterBase
{
private float mouthDisplacement = 0.0F;
private float displacementPerFrame = 250.0F / GameWindow.FPS;
private float startAngle = 45.0F;
private bool mouthClosing = true;
public Pacman(PointF loc) : base(loc, Color.Yellow) { }
public void ChangeDirection(Direction d)
{
this.newDirection = d;
}
public override void Draw(Graphics g)
{
if (this.location.X < 0)
{
if (this.location.X > (-1) * this.size.Width)
{
g.FillPie(this.pen.Brush, this.location.X + BattleField.Background.Width, this.location.Y, this.size.Width, this.size.Height, this.startAngle - this.mouthDisplacement, 270 + 2 * this.mouthDisplacement);
}
else
{
this.location = new PointF((BattleField.Background.Width - this.size.Width), location.Y);
}
}
if ((this.location.X + this.size.Width) > BattleField.Background.Width)
{
if ((this.location.X + this.size.Width) < (BattleField.Background.Width + this.size.Width))
{
g.FillPie(this.pen.Brush, this.location.X - BattleField.Background.Width, this.location.Y, this.size.Width, this.size.Height, this.startAngle - this.mouthDisplacement, 270 + 2 * this.mouthDisplacement);
}
else
{
this.location = new PointF(0.0F, location.Y);
}
}
g.FillPie(this.pen.Brush, this.location.X, this.location.Y, this.size.Width, this.size.Height, this.startAngle - this.mouthDisplacement, 270 + 2 * this.mouthDisplacement);
this.TryToMove();
if (this.mouthClosing && this.mouthDisplacement < 45.0F)
{
this.mouthDisplacement += this.displacementPerFrame;
if (this.mouthDisplacement >= 45.0F)
{
this.mouthClosing = false;
}
}
else
{
this.mouthDisplacement -= this.displacementPerFrame;
if (this.mouthDisplacement <= 0.0F)
{
this.mouthClosing = true;
}
}
}
private void TryToMove()
{
if (!hasBarrier(newDirection, speed))
{
direction = newDirection;
this.Move(speed);
}
else
{
for (int i = speed - 1; i > 0; i--)
{
if (!hasBarrier(newDirection, i))
{
this.Move(i);
direction = newDirection;
return;
}
}
if (!hasBarrier(direction, speed))
{
this.Move(speed);
}
else
{
for (int i = speed - 1; i > 0; i--)
{
if (!hasBarrier(direction, i))
{
this.Move(i);
direction = newDirection;
return;
}
}
direction = Direction.Stopped;
}
}
//Log(location.X.ToString() + " " + location.Y.ToString());
}
private void Move(int distance)
{
if (this.direction == Direction.Right)
{
this.startAngle = 45.0F;
this.location = new PointF(this.location.X + distance, this.location.Y);
}
else if (this.direction == Direction.Left)
{
this.startAngle = 225.0F;
this.location = new PointF(this.location.X - distance, this.location.Y);
}
else if (this.direction == Direction.Up)
{
this.startAngle = 315.0F;
this.location = new PointF(this.location.X, this.location.Y - distance);
}
else if (this.direction == Direction.Down)
{
this.startAngle = 135.0F;
this.location = new PointF(this.location.X, this.location.Y + distance);
}
//if (this.direction == Direction.Right)
//{
// if ((this.location.X + this.size.Width) >= BattleField.Background.Width || hasBarrier(direction, this.location))
// {
// this.direction = Direction.Stopped;
// return;
// }
// this.startAngle = 45.0F;
// this.location = new PointF(this.location.X + this.speed, this.location.Y);
//}
//else if (this.direction == Direction.Left)
//{
// if (this.location.X <= 0.0F || hasBarrier(direction, this.location))
// {
// this.direction = Direction.Stopped;
// return;
// }
// this.startAngle = 225.0F;
// this.location = new PointF(this.location.X - this.speed, this.location.Y);
//}
//else if (this.direction == Direction.Up)
//{
// if (this.location.Y <= 0.0F || hasBarrier(direction, this.location))
// {
// this.direction = Direction.Stopped;
// return;
// }
// this.startAngle = 315.0F;
// this.location = new PointF(this.location.X, this.location.Y - this.speed);
//}
//else if (this.direction == Direction.Down)
//{
// if ((this.location.Y + this.size.Height) >= BattleField.Background.Height || hasBarrier(direction, this.location))
// {
// this.direction = Direction.Stopped;
// return;
// }
// this.startAngle = 135.0F;
// this.location = new PointF(this.location.X, this.location.Y + this.speed);
//}
}
private bool hasBarrier(Direction d, int dist)
{
foreach (var wall in BattleField.Walls)
{
switch (d)
{
case Direction.Right:
if (overlapsWall(wall, new PointF(location.X + dist, location.Y))) return true;
break;
case Direction.Left:
if (overlapsWall(wall, new PointF(location.X - dist, location.Y))) return true;
break;
case Direction.Up:
if (overlapsWall(wall, new PointF(location.X, location.Y - dist))) return true;
break;
case Direction.Down:
if (overlapsWall(wall, new PointF(location.X, location.Y + dist))) return true;
break;
}
}
return false;
}
private bool overlapsWall(Wall wall, PointF possibleLocation)
{
if ((possibleLocation.X >= wall.Location.X) && (possibleLocation.Y >= wall.Location.Y))
{
if ((possibleLocation.X < (wall.Location.X + wall.Size.Width)) && (possibleLocation.Y < (wall.Location.Y + wall.Size.Height))) return true;
}
else if ((possibleLocation.X <= wall.Location.X) && (possibleLocation.Y >= wall.Location.Y))
{
if (((possibleLocation.X + size.Width) > wall.Location.X) && (possibleLocation.Y < (wall.Location.Y + wall.Size.Height))) return true;
}
else if ((possibleLocation.X <= wall.Location.X) && (possibleLocation.Y <= wall.Location.Y))
{
if (((possibleLocation.X + size.Width) > wall.Location.X) && ((possibleLocation.Y + size.Height) > wall.Location.Y)) return true;
}
else if ((possibleLocation.X >= wall.Location.X) && (possibleLocation.Y <= wall.Location.Y))
{
if ((possibleLocation.X < (wall.Location.X + wall.Size.Width)) && ((possibleLocation.Y + size.Height) > wall.Location.Y)) return true;
}
return false;
}
private void Log(string line)
{
using (System.IO.StreamWriter wr = System.IO.File.AppendText("Log.txt"))
{
wr.WriteLine(line);
}
}
}
}
| a648045acfc1d7190c3a3e61267dd841a0a1c630 | [
"C#"
] | 7 | C# | IDgtl/Pacman | da091a24c2bbce3b5771565ff1d0a20a01dd5eb0 | 0196564149c6889501c7b891644f95114248bfea |
refs/heads/master | <repo_name>johnLitoBardinas/buck<file_sep>/functions.php
<?php
/**
* Twenty Nineteen functions and definitions
*
* @link https://developer.wordpress.org/themes/basics/theme-functions/
*
* @package WordPress
* @subpackage Twenty_Nineteen
* @since 1.0.0
*/
// Disable admin bar
show_admin_bar( false );
// deregister JQuery
wp_deregister_script( 'jquery' );
function buckstreet_assets() {
// Load the main stylesheet.
wp_enqueue_style(
'main-stylesheet',
get_theme_file_uri( ) . '/assets/css/style.css',
null,
true,
'all'
);
// Load the main script file.
wp_enqueue_script(
'main-script',
get_theme_file_uri( ) . '/assets/js/script.js',
[ 'jquery' ],
'1.1.0',
true
);
}
add_action( 'wp_enqueue_scripts', 'buckstreet_assets' );
wp_deregister_script( 'jquery' );
add_filter('wpcf7_form_elements', function($content) {
$content = preg_replace('/<(span).*?class="\s*(?:.*\s)?wpcf7-form-control-wrap(?:\s[^"]+)?\s*"[^\>]*>(.*)<\/\1>/i', '\2', $content);
return $content;
});<file_sep>/footer.php
<?php
/**
* The template for displaying the footer
*
* Contains the closing of the #content div and all content after.
*
* @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
*
* @package WordPress
* @subpackage Twenty_Nineteen
* @since 1.0.0
*/
?>
</div><!-- #content -->
</div><!-- #page -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<?php wp_footer(); ?>
</body>
</html>
<file_sep>/assets/js/script.js
$(function() {
var $cloud_layer = $("#cloud__layer");
var $house_layer = $("#houses__layer");
var $coming_soon_container = $("#coming-soon__container");
var $content_layer = $("#content__layer");
var $info_btn_container = $("#info__button-container");
var $subsribe_container = $("#subscribe__container");
var $thank_you_container = $("#thank-you__container");
function isMobile() {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}
// is less than screen width
function isLessThan( width ) {
return $(window).width() < width;
}
setTimeout(function() {
$cloud_layer.addClass("intro");
$house_layer.addClass("intro");
$coming_soon_container.removeAttr("style").css({ "visibility":"visible", "display":"block" });
var timer = isMobile() ? 2000 : 5000;
setTimeout(function() {
$house_layer.removeClass("intro").addClass("down");
var comingSoon = isMobile() ? 2000 : 1000 ;
setTimeout(function(){
$content_layer.removeClass("hd").addClass("up");
$coming_soon_container.addClass("down");
}, comingSoon);
}, timer);
}, 2000);
// be the first
$("#info__button").on("click", function(e){
e.preventDefault();
if( isMobile() && isLessThan( 500 ) ) {
$("#info__text-icon").addClass("down");
$info_btn_container.addClass("down").css("min-height", "156px");
setTimeout(function() {
$subsribe_container.removeClass("hd");
}, 300);
setTimeout(function(){
$("left-container").addClass("hd");
}, 3000);
}else{
$subsribe_container.removeClass("hd");
$info_btn_container.fadeOut(100);
}
setTimeout(function() {
$subsribe_container.removeClass("up down").addClass("up");
}, isMobile() ? 350 : 0);
if ( $subsribe_container.hasClass("up") || $subsribe_container.hasClass("down")) {
$cloud_layer.removeClass("up down").addClass("up");
$house_layer.removeClass("up down").addClass("up");
}else{
$cloud_layer.removeClass("intro").addClass("up");
$house_layer.removeClass("intro").addClass("down");
}
});
// contactform7
var wpcf7Elm = document.querySelector( '.wpcf7' );
var subscribe_btn = $("#subscribe__button");
wpcf7Elm.addEventListener( 'wpcf7submit', function(e) {
var status = e.detail.apiResponse.status;
subscribe_btn.attr("disabled");
switch ( status ) {
case 'validation_failed' :
subscribe_btn.removeAttr("disabled");
break;
case 'mail_sent' :
subscribe_btn.removeAttr("disabled");
$subsribe_container.addClass("down");
$cloud_layer.removeClass("up").addClass("down");
$house_layer.removeClass("down").addClass("up");
setTimeout(function() {
$thank_you_container.hide();
if( isMobile() && isLessThan( 500 ) ) {
$("#info__text-icon").removeClass("hd").removeAttr("style");
// $content_layer.removeClass("up").addClass("up");
$("#info__text-icon").removeClass("down");
$info_btn_container.removeClass("down");
$subsribe_container.removeClass("up down").addClass("hd");
}
$info_btn_container.removeAttr("style");
}, 2000);
// fadeIn Thank You
$thank_you_container.show();
break;
};
});
});<file_sep>/index.php
<?php
/**
* The main template file
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/
*
* @package WordPress
* @subpackage Twenty_Nineteen
* @since 1.0.0
*/
get_header();
?>
<div class="logo_container" id="logo_container">
<!-- FIXED LOGO -->
<a href="<?php echo site_url();?>">
<div class="logo"> </div>
</a>
</div>
<!-- INSERT CLOUD WITH REPEEAT -->
<div class="cloud__layer" id="cloud__layer">
</div>
<div class="coming-soon__container" id="coming-soon__container" style="display:none;">
</div>
<!-- MAIN CONTAINER -->
<div class="content__layer hd" id="content__layer">
<div class="body__info" id="body__info">
<div class="left-container" id="left-container">
<div class="info__text-icon" id="info__text-icon">
<h1>SHOP. DWELL. DINE.</h1>
<p>Buck Street Market is a brand new Camden destination. Bringing together flagship dining concepts, ethical and sustainable retail as well as boutique makers and market stalls. Buck Street Market will provide the perfect space for emerging designers, artists and chefs from London and beyond. <h1 class="info__text-emphasize">Opening January 2020.</h1></p>
<ul class="cta__social-media" id="cta__social-media">
<li class="facebook">
<a href="<?php echo esc_url('https://www.facebook.com/BuckStreetMarket/?modal=admin_todo_tour'); ?>"></a>
</li>
<li class="twitter">
<a href="<?php echo esc_url('https://twitter.com/buckstreetmkt?lang=en'); ?>"></a>
</li>
<li class="instagram">
<a href="<?php echo esc_url('https://www.instagram.com/buckstreetmarket/'); ?>"></a>
</li>
</ul>
</div>
<!-- #info__text-icon -->
</div>
<div class="right-container">
<div class="info__button-container" id="info__button-container">
<button class="info__button" id="info__button">Be the first to know</button>
</div>
<!-- #info__button-container -->
<div class="subscribe__container hd" id="subscribe__container">
<?php echo do_shortcode('[contact-form-7 id="6" title="Subscribe v2"]'); ?>
</div>
<!-- #subscribe__container -->
<div class="thank-you__container hd" id="thank-you__container">
<img src="<?php echo esc_url( bloginfo('template_url'). '/assets/img/thanks.png' ); ?>" alt="Thank you message!">
</div>
<!-- #thank-you__container -->
</div>
</div>
</div>
<!-- HOUSES -->
<div class="houses__layer" id="houses__layer"></div>
<?php
get_footer();
| 14889984f69041222a57da1d3236950443660b83 | [
"JavaScript",
"PHP"
] | 4 | PHP | johnLitoBardinas/buck | 9840b338654eb3537444b7307b3faf3f23431862 | 1da6e2f462267fd4b028377f744011e4e38192da |
refs/heads/master | <file_sep><?php
$var='Primer commit';
echo $var;
?> | 519045beef4b9904f693844f5f5b798ec7c725b2 | [
"PHP"
] | 1 | PHP | cmoyag/tutorial | 7a87d06647e339ac1829780fdd66c66183cc6e6b | f52634323f4247b694068b0668b2a6a03b947db1 |
refs/heads/master | <file_sep><?xml version="1.0" encoding="UTF-8"?>
<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>
<artifactId>dockerspringbooth2</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Docker SpringBoot H2</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<swagger.version>2.7.0</swagger.version>
<feign.version>8.18.0</feign.version>
<docker-maven-plugin.version>1.0.0</docker-maven-plugin.version>
<skipTests>false</skipTests>
<skipDocker>false</skipDocker>
</properties>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
<addResources>true</addResources>
</configuration>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>${docker-maven-plugin.version}</version>
<executions>
<execution>
<id>clean-local</id>
<phase>clean</phase>
<goals>
<goal>removeImage</goal>
</goals>
<configuration>
<imageName>${project.artifactId}:latest</imageName>
<skipDocker>${skipDocker}</skipDocker>
</configuration>
</execution>
<execution>
<id>build-docker-image</id>
<phase>package</phase>
<goals>
<goal>build</goal>
</goals>
<configuration>
<skipDocker>${skipDocker}</skipDocker>
</configuration>
</execution>
</executions>
<configuration>
<imageName>${project.artifactId}</imageName>
<dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
<imageTags>
<imageTag>latest</imageTag>
</imageTags>
<skipDocker>${skipDocker}</skipDocker>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Spring Boot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- H2 Database-->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- ThymeLeaf -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-conditionalcomments</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.16</version>
</dependency>
</dependencies>
<groupId>com.iqmsoft.docker</groupId>
</project><file_sep># DockerSpringBootH2
Docker Spring Boot H2
<file_sep>package com.iqmsoft.docker.shoppinglist;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.thymeleaf.extras.conditionalcomments.dialect.ConditionalCommentsDialect;
import com.iqmsoft.docker.shoppinglist.dto.ItemDto;
import com.iqmsoft.docker.shoppinglist.dto.ItemsListDto;
import com.iqmsoft.docker.shoppinglist.services.ItemService;
import com.iqmsoft.docker.shoppinglist.services.ItemsListService;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static java.util.Arrays.asList;
@SpringBootApplication
@EnableSwagger2
public class Application {
public static final String API_BASE_URL = "/v1/api";
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner runner(ItemsListService itemsListService, ItemService itemService) {
return args -> {
asList("Shopping list 1", "Shopping list 2", "Shopping list 3")
.forEach(name -> itemsListService.addItemsList(new ItemsListDto(name)));
asList("Oranges 1kg", "Item2", "Item3", "Item1")
.forEach(name -> itemService.addItem(new ItemDto(1, name)));
asList("Milk", "Apples 2kg", "Bread")
.forEach(name -> itemService.addItem(new ItemDto(2, name)));
asList("Meat 2kg", "Item2")
.forEach(name -> itemService.addItem(new ItemDto(3, name)));
};
}
@Bean
public ConditionalCommentsDialect conditionalCommentDialect() {
return new ConditionalCommentsDialect();
}
@Bean
protected Docket swaggerApiV1() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.iqmsoft.docker.shoppinglist.controllers.rest"))
.paths(PathSelectors.ant(API_BASE_URL + "/**"))
.build();
}
}
<file_sep>package com.iqmsoft.docker.shoppinglist.entities;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
@Entity
@Getter
@Setter
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Item {
@Id
@GeneratedValue
private long id;
private String name;
private String comment;
private boolean isBought;
@ManyToOne
@JoinColumn
private ItemsList itemsList;
public Item() {
}
public Item(String name, ItemsList itemsList) {
this.name = name;
this.itemsList = itemsList;
}
}
<file_sep>package com.iqmsoft.docker.shoppinglist;
public final class Utils {
private Utils() {
}
public static String redirectToUrl(String url) {
return "redirect:" + url;
}
}
<file_sep>package com.iqmsoft.docker.shoppinglist.controllers.rest;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.iqmsoft.docker.shoppinglist.dto.ItemsListDto;
import com.iqmsoft.docker.shoppinglist.entities.ItemsList;
import com.iqmsoft.docker.shoppinglist.services.ItemsListService;
import javax.validation.Valid;
import static com.iqmsoft.docker.shoppinglist.Application.API_BASE_URL;
import static com.iqmsoft.docker.shoppinglist.controllers.ItemsListController.ITEMS_LIST_BASE_PATH;
import java.util.List;
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping(API_BASE_URL)
public class ItemsListRestController {
private final ItemsListService itemsListService;
@ApiOperation("Get all lists")
@GetMapping
public List<ItemsList> getAllLists() {
return itemsListService.findAllLists();
}
@ApiOperation("Get list")
@GetMapping(value = ITEMS_LIST_BASE_PATH + "/{id}")
public ItemsList getItemsList(@PathVariable final long id) {
return itemsListService.getItemsListById(id);
}
@ApiOperation("Add list")
@PostMapping(ITEMS_LIST_BASE_PATH)
public ResponseEntity<ItemsListDto> saveItemsList(@Valid @RequestBody ItemsListDto itemsListDto) {
itemsListService.addItemsList(itemsListDto);
return new ResponseEntity<>(itemsListDto, HttpStatus.CREATED);
}
@ApiOperation("Update list")
@PutMapping(ITEMS_LIST_BASE_PATH)
public ResponseEntity editItemsList(@Valid @RequestBody ItemsListDto itemsListDto) {
if (itemsListService.getItemsListById(itemsListDto.getId()) == null) {
log.error("List with id '" + itemsListDto.getId() + "' not found");
return ResponseEntity.notFound().build();
}
itemsListService.updateItemsList(itemsListDto);
return ResponseEntity.ok(itemsListDto);
}
@ApiOperation("Delete list")
@DeleteMapping(ITEMS_LIST_BASE_PATH + "/{id}")
public ResponseEntity deleteItemsList(@PathVariable final long id) {
if (itemsListService.getItemsListById(id) == null) {
log.error("List with id '" + id + "' not found");
return ResponseEntity.notFound().build();
}
itemsListService.deleteItemsList(id);
return ResponseEntity.noContent().build();
}
}
<file_sep>management.context-path=/admin
management.port=9000
server.port=8000
spring.data.rest.base-path=/v2/api
spring.output.ansi.enabled=ALWAYS
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
logging.file=shoppingList.log
<file_sep>package com.iqmsoft.docker.shoppinglist.services;
import com.iqmsoft.docker.shoppinglist.dto.ItemDto;
import com.iqmsoft.docker.shoppinglist.entities.Item;
public interface ItemService {
void addItem(ItemDto itemDto);
void updateItem(ItemDto itemDto);
void deleteItem(long id);
Item getItemById(long id);
void toggleBoughtStatus(long id);
}
<file_sep>version: "2.0"
services:
shoppingListApp:
image: dockerspringbooth2:latest
ports:
- 8000:8000 | d8d96e76be14e9ed78e1375866c5563fe5ed4815 | [
"YAML",
"Markdown",
"Maven POM",
"INI",
"Java"
] | 9 | Maven POM | Murugar/DockerSpringBootH2 | ed33fea8c892a16547c8e830178575675904bc9f | 9ad35ed756868884b7e7f7591f4f284063bc27d7 |
refs/heads/master | <repo_name>boskakke/special<file_sep>/lib/custom.php
<?php
// //Adding the Open Graph in the Language Attributes
// function add_opengraph_doctype( $output ) {
// return $output . ' xmlns:og="http://opengraphprotocol.org/schema/" xmlns:fb="http://www.facebook.com/2008/fbml"';
// }
// add_filter('language_attributes', 'add_opengraph_doctype');
//Lets add Open Graph Meta Info
// function insert_fb_in_head() {
// global $post;
// if ( !is_singular()) //if it is not a post or a page
// return;
// echo '<meta property="og:title" content="' . get_the_title() . '"/>';
// echo '<meta property="og:type" content="article"/>';
// echo '<meta property="og:url" content="' . get_permalink() . '"/>';
// echo '<meta property="og:site_name" content="Berlingske Media"/>';
// if(!has_post_thumbnail( $post->ID )) {
// $blog_url = "http://www.berlingskemedia.dk";
// $default_image = $blog_url . "/media/bem-logo.png";
// echo '<meta property="og:image" content="'. $default_image . '"/>';
// }
// else{
// $thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
// echo '<meta property="og:image" content="' . esc_attr( $thumbnail_src[0] ) . '"/>';
// }
// echo "
// ";
// }
// add_action( 'wp_head', 'insert_fb_in_head', 5 );
// Add specific CSS class by filter
add_filter( 'body_class', 'my_class_names' );
function my_class_names( $classes ) {
// add 'class-name' to the $classes array
// $classes[] = 'class-name';
$classes[] = get_field('page_color');
// return the $classes array
return $classes;
}
// Replaces the excerpt "more" text by a link
function new_excerpt_more($more) {
global $post;
return '<a class="moretag" href="'. get_permalink($post->ID) . '"> ...</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');
<file_sep>/base.php
<?php get_template_part('templates/head'); ?>
<body <?php body_class(); ?>>
<?php
if (has_nav_menu('primary_navigation')) :
wp_nav_menu(array('theme_location' => 'primary_navigation', 'menu_id' => 'mobile-menu', 'menu_class' => 'mobile-men', 'depth' => 4));
endif;
?>
<?php // Set variable "Show contactform in footer"
if ( get_field('vis_annoncor_kontaktform') ) {
$show_form = true;
}
if ( get_field('vis_forhandler_nyhedsbrev') ) {
$show_businessnewsletter = true;
}
?>
<?php
do_action('get_header');
get_template_part('templates/header');
?>
<?php include roots_template_path(); ?>
<?php get_template_part('templates/footer'); ?>
</body>
</html>
<file_sep>/single.php
<?php get_template_part('templates/content', 'page-builder'); ?><file_sep>/page.php
<?php
/*
*/
?>
<?php get_template_part('templates/content', 'page-builder'); ?>
<file_sep>/templates/footer.php
<div class="container">
<div class="col-xs-12">
<footer class="main-footer">
</footer>
</div>
</div>
<?php wp_footer(); ?>
<script>
window.fbAsyncInit = function(){
FB.init({
appId: '182764648520454', status: true, cookie: true, xfbml: true });
};
(function(d, debug){var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if(d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id;
js.async = true;js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);}(document, /*debug*/ false));
function postToFeed(title, desc, url, image){
var obj = {method: 'feed',link: url, picture: 'http://www.url.com/images/'+image,name: title,description: desc};
function callback(response){}
FB.ui(obj, callback);
}
$(document).ready(function() {
$('.btnShare').click(function(){
elem = $(this);
postToFeed(elem.data('title'), elem.data('desc'), elem.prop('href'), elem.data('image'));
return false;
});
});
</script>
<script type="text/javascript">
var _sf_async_config={};
/** CONFIGURATION START **/
var _sf_async_config = {};
_sf_async_config.uid = '49449';
_sf_async_config.domain = 'bt.dk';
_sf_async_config.title = "<?php the_title(); ?>";
_sf_async_config.sections = "BT Special";
_sf_async_config.useCanonical = true;
_sf_async_config.path = "<?php the_permalink(); ?>";
/** CONFIGURATION END **/
(function(){
function loadChartbeat() {
window._sf_endpt=(new Date()).getTime();
var e = document.createElement("script");
e.setAttribute("language", "javascript");
e.setAttribute("type", "text/javascript");
e.setAttribute('src', '//static.chartbeat.com/js/chartbeat.js');
document.body.appendChild(e);
}
var oldonload = window.onload;
window.onload = (typeof window.onload != "function") ?
loadChartbeat : function() { oldonload(); loadChartbeat(); };
})();
</script>
<!-- Begin comScore Inline Tag 1.1302.13 -->
<script type="text/javascript">
// <+1)for(d=0,p=r.split(";"),v=p[u];d<v;d++)h=p[d][s](t),h+1&&(i=c+unescape(p[d][o](h+t[u])));e+=l+"_t="+ +(new Date)+l+"c="+(n.characterSet||n.defaultCharset||"")+"&c8="+g(n.title)+i+"&c7="+g(n.URL)+"&c9="+g(n.referrer),e[u]>a&&e[s](c)>0&&(f=e[o](0,a-8).lastIndexOf(c),e=(e[o](0,f)+l+"cut="+g(e[o](f+1)))[o](0,a)),n.images?(h=new Image,m.ns_p||(ns_p=h),h.src=e):n.write("<","p","><",'img src="',e,'" height="1" width="1" alt="*"',"><","/p",">")};
udm_('//int.sitestat.com/berlingske/politiko/s?name=<?php the_permalink(); ?>');
// ]]>
</script>
<noscript><p><img src="//int.sitestat.com/berlingske/bt/s?name=<?php the_permalink(); ?>" height="1" width="1" alt="*"></p></noscript>
<!-- End comScore Inline Tag -->
<!-- (C)2000-2013 Gemius SA - gemiusAudience / bt.dk / blogs.bt.dk (forside) -->
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var pp_gemius_identifier = '.RzgxGOyo8GPaBFF0OcofWZUnFmNeXAq4yJ7L.RQKJz.N7';
(function(d,t) {var ex; try {var gt=d.createElement(t),s=d.getElementsByTagName(t)[0],l='http'+((location.protocol=='https:')?'s':'');
gt.async='true'; gt.src=l+'://gadk.hit.gemius.pl/xlgemius.js'; s.parentNode.insertBefore(gt,s);} catch (ex) {}}(document,'script'));
//--><!]]>
</script>
<script type="text/javascript">
(function($){
$(function() {
// Pause or play videos if they are visible or not.
function determineVideoStatus() {
$('video:not(.played)').each(function(){
if ($(this).is(":in-viewport")) {
$(this)[0].play();
} else {
$(this)[0].pause();
}
});
}
// Run check when loading page.
determineVideoStatus();
// Add listerner for scroll events.
$(window).scroll(determineVideoStatus);
// Add a played class when video ends to avoid replays.
$('video').on('ended', function() {
$(this).addClass('played');
});
});
})(jQuery);
</script>
<!--
<?php // echo get_num_queries (). ' Queries in ' . timer_stop (1). ' ! Seconds' ; ?>
<?php // echo 'MB Peak Memory Used: '.round(memory_get_peak_usage() / 1024 / 1024, 3); ?>
--><file_sep>/templates/content-show-more.php
<?php if(get_sub_field('page_text_hidden')) : ?>
<div class="hidden-text">
<?php the_sub_field('page_text_hidden'); ?>
</div>
<button class="btn btn-show-more">Vis mere </button>
<?php endif; ?><file_sep>/templates/head.php
<?php
$attachment_id = get_field('social_image');
$size = "social-media";
$social_image = wp_get_attachment_image_src( $attachment_id, $size );
?>
<!DOCTYPE html>
<html class="no-js" <?php language_attributes(); ?>>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?php wp_title('|', true, 'right'); ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta property="og:image" content="<?php echo $social_image[0]; ?>" />
<meta property="og:title" content="<?php the_title() ?> - BT Special" />
<meta property="og:site_name" content="www.bt.dk"/>
<meta property="og:url" content="<?php the_permalink(); ?>" />
<?php if($social_summary): ?>
<meta property="og:description" content="<?php echo $social_summary; ?>" />
<?php endif; ?>
<meta property="fb:app_id" content="182764648520454" />
<meta property="og:type" content="article" />
<meta property="twitter:site" content="@btdk" />
<meta property="twitter:domain" content="BT.dk" />
<meta property="twitter:url" content="<?php the_permalink(); ?>" />
<meta property="twitter:title" content="<?php the_title(); ?> - BT Special" />
<?php if($social_summary): ?><meta property="twitter:description" content="<?php echo $social_summary; ?>" /><?php endif; ?>
<meta property="twitter:image" content="<?php echo $social_image[0]; ?>" />
<!-- Favicons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="<?php echo get_bloginfo('stylesheet_directory'); ?>/assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="shortcut icon" href="<?php echo get_bloginfo('stylesheet_directory'); ?>/assets/ico/favicon.png">
<?php wp_head(); ?>
<link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo home_url(); ?>/feed/">
</head>
<file_sep>/templates/content-slider-royal.php
<div class="royalSlider heroSlider rsMinW module ">
<?php if(get_field('slider-repeater')): ?>
<?php while(the_repeater_field('slider-repeater')): ?>
<?php
$header_1 = get_sub_field('slider-header-1');
$header_2 = get_sub_field('slider-header-2');
$header_3 = get_sub_field('slider-header-3');
$image = wp_get_attachment_image_src(get_sub_field('slider-image'), 'slide');
if(get_sub_field('flat-design') ) {
$flat_design = 'info-block-flat';
} else {
$flat_design = 'info-block-tall';
};
$slider_color = get_sub_field('slider-color');
?>
<div class="rsContent">
<a href="<?php the_sub_field('slider-link');?>">
<img class="rsImg" src="<?php echo $image[0]; ?>">
<div class="info-block rsABlock <?php echo $flat_design; ?> <?php echo $slider_color; ?>" data-fade-effect="true" data-delay="600" data-move-offset="20" data-move-effect="bottom" data-speed="200" data-easing="easeOutSine">
<div class="info-header">
<h3><?php echo $header_1; ?></h3>
<?php if($flat_design == 'info-block-tall') : ?>
<h3><?php echo $header_2; ?></h3>
<h3><?php echo $header_3; ?></h3>
<?php endif; ?>
</div>
<p><?php the_sub_field('slider-subheader');?></p>
</div>
</a>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?><file_sep>/templates/content-page-builder.php
<?php
/*
*/
?>
<?php while(has_sub_field("deck_intro_video")): ?>
<?php if(get_field('deck_intro_video')): ?>
<?php
$attachment_id = get_sub_field('video_poster');
$size = "parralax";
$image = wp_get_attachment_image_src( $attachment_id, $size );
$video = get_sub_field('video_file');
?>
<div class="container-video" style="background-image: url(<?php echo $image[0]; ?>)">
<div class="row-video" style="background-image: url(<?php echo $image[0]; ?>)">
<video autoplay loop muted poster="<?php echo $image[0]; ?>">
<source src="<?php echo $video; ?>" type="video/mp4">
</video>
</div>
<div class="overlay "></div>
<div class="video-overlay fade-in">
<header>
<div class="logo bt-logo"></div>
<h1 class="page-title <?php the_sub_field('video_title_size') ?>"><?php the_sub_field('video_title') ?></h1>
</header>
</div>
</div>
<?php endif; ?>
<?php endwhile; ?>
<div class="main-content">
<?php while(has_sub_field("page_builder")): ?>
<?php if(get_row_layout() == "deck_text"): ?>
<section class="deck deck-text">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2 <?php if(get_sub_field('drop_letter')): ?> first-letter<?php endif; ?>">
<?php the_sub_field("page_text"); ?>
</div>
</div>
</div>
</section>
<?php elseif(get_row_layout() == "deck_fact"): ?>
<section class="deck deck-fact">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2 ">
<?php the_sub_field("page_text"); ?>
</div>
</div>
</div>
</section>
<?php elseif(get_row_layout() == "deck_html"): ?>
<section class="deck deck-html">
<?php if(get_sub_field('full_witdh')): ?>
<?php the_sub_field('html_text'); ?>
<?php else: ?>
<div class="container">
<div class="row">
<div class="col-xs-12">
<?php the_sub_field('html_text'); ?>
</div>
</div>
</div>
<?php endif; ?>
</section>
<?php elseif(get_row_layout() == "deck_html"): ?>
<section class="deck deck-html">
<?php if(get_sub_field('full_witdh')): ?>
<?php the_sub_field('html_text'); ?>
<?php else: ?>
<div class="container">
<div class="row">
<div class="col-xs-12">
<?php the_sub_field('html_text'); ?>
</div>
</div>
</div>
<?php endif; ?>
</section>
<?php elseif(get_row_layout() == "page_html"): ?>
<section class="deck deck-html">
<?php if(get_sub_field('full_width')): ?>
<?php the_sub_field('content'); ?>
<?php else: ?>
<div class="container">
<div class="row">
<div class="col-xs-12">
<?php the_sub_field('content'); ?>
</div>
</div>
</div>
<?php endif; ?>
</section>
<?php elseif(get_row_layout() == "deck_voxpop"): ?>
<?php
$attachment_id = get_sub_field('image_voxpop');
$size = "voxpop";
$image = wp_get_attachment_image_src( $attachment_id, $size );
?>
<section class="deck deck-voxpop">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-12">
<div class="voxpop-container">
<figure>
<img src="<?php echo $image[0]; ?>">
</figure>
<?php the_sub_field('page_text'); ?>
<?php get_template_part('templates/content-show-more'); ?>
</div>
</div>
<?php if(get_sub_field('video_caption')): ?>
<div class="col-md-8 col-md-offset-2">
<div class="slider-caption">
<?php the_sub_field("video_caption"); ?>
</div>
</div>
<?php endif; ?>
</div>
</div>
</section>
<?php elseif(get_row_layout() == "page_video"): ?>
<?php
$attachment_id = get_sub_field('video_poster');
$size = "video";
$image = wp_get_attachment_image_src( $attachment_id, $size );
$video_name = get_sub_field('video_url');
$video_link_part = preg_split('#[/-]#', $video_name);
?>
<section class="deck deck-video">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-12 text-center">
<video controls preload="auto" class="video" poster="<?php echo $image[0]; ?>" >
<source src="http://bmedia.scanpix.eu/berlingske/content/<?php echo $video_link_part[0]; ?>/<?php echo $video_name; ?>-mp4.mp4" type="video/mp4">
</video>
</div>
<?php if(get_sub_field('video_caption')): ?>
<div class="col-md-8 col-md-offset-2">
<div class="caption">
<?php the_sub_field("video_caption"); ?>
</div>
</div>
<?php endif; ?>
</div>
</div>
</section>
<?php elseif(get_row_layout() == "deck_byline"): ?>
<section class="deck deck-byline">
<div class="container">
<div class="row">
<div class="col-md-12 text-center byline ">
<?php while(has_sub_field('byline_repeater')): ?>
<span class="byline-container">
<?php if(get_sub_field('author_title')) : ?>
<?php echo the_sub_field('author_title') ?>:
<?php endif; ?>
<?php if(get_sub_field('author_name')) : ?>
<?php if(get_sub_field('author_email')) : ?>
<a href="mailto:<?php echo the_sub_field('author_email') ?>">
<?php endif; ?>
<?php echo the_sub_field('author_name') ?>
<?php if(get_sub_field('author_email')) : ?>
</a>
<?php endif; ?>
<?php endif; ?>
</span>
<?php endwhile; ?>
</div>
</div>
</div>
</section>
<?php elseif(get_row_layout() == "deck_summary"): ?>
<section class="deck deck-text">
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1 summary ">
<p><?php the_sub_field("page_summary"); ?></p>
</div>
</div>
</div>
</section>
<?php elseif(get_row_layout() == "slider"): ?>
<section class="deck deck-slider">
<div class="<?php if(get_sub_field('full_screen')): ?> container-fluid<?php else: ?> container<?php endif; ?>">
<div class="row">
<div class="col-md-12">
<div class="sliderContainer">
<div id="full-width-slider" class="royalSlider contentSlider rsDefault">
<?php while(has_sub_field('slider_repeater')): ?>
<?php
$attachment_meta = get_sub_field('photo');;
$attachment_id = get_sub_field('photo');
$size = "article"; // (thumbnail, medium, large, full or custom size)
$image = wp_get_attachment_image_src( $attachment_id, $size);
?>
<div>
<!-- <img class="rsImg" src="http://dimsemenov.com/plugins/royal-slider/img/home.jpg" data-rsw="707" data-rsh="397"> -->
<figure><img class="rsImg" src="<?php echo $image[0]; ?>" class="rsImg"></figure>
<?php if(get_sub_field('photo_caption')) : ?>
<figcaption class="photo-caption">
Foto: <?php echo the_sub_field('photo_caption') ?>
</figcaption>
<?php endif; ?>
<?php if(get_sub_field('photo_description')) : ?>
<div class="caption">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<?php echo the_sub_field('photo_description') ?>
</div>
</div>
</div>
<?php endif; ?>
</div>
<?php endwhile; ?>
</div>
</div>
</div>
</div>
</div>
</section>
<?php elseif(get_row_layout() == "page_quote"): ?>
<?php if(get_sub_field('quote')): // Check for wuote - just in case! ?>
<section class="deck deck-quote">
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<blockquote>
<p><?php the_sub_field('quote'); ?></p>
<?php if(get_sub_field('quote_cite')): ?>
<small><?php the_sub_field('quote_cite'); ?></small>
<?php endif; ?>
</blockquote>
</div>
</div>
</div>
</section>
<?php endif; ?>
<?php elseif(get_row_layout() == "page_parralax"): ?>
<section class="deck deck-parralax">
<?php
$attachment_id_1 = get_sub_field('picture_1');
$size = "parralax";
$size_mobile = "parralax-mobile";
$image_1 = wp_get_attachment_image_src( $attachment_id_1, $size );
$image_2 = wp_get_attachment_image_src( $attachment_id_2, $size_mobile );
?>
<div class="img-holder lazy" data-image="<?php echo $image_1[0]; ?>" data-image-mobile="<?php echo $image_2[0]; ?>" data-width="1680" data-height="1050"></div>
</section>
<?php elseif(get_row_layout() == "page_1_image"): // layout: File ?>
<?php
$attachment_id_1 = get_sub_field('picture_1');
$size = "article";
$image_1 = wp_get_attachment_image_src( $attachment_id_1, $size );
?>
<section class="deck deck-photo">
<div class="container">
<div class="row">
<div class="col-sm-12 module-sm">
<?php if($image_1) : ?>
<figure>
<img data-original="<?php echo $image_1[0]; ?>" class="img-responsive lazy" />
<?php if(get_sub_field('caption_1')): ?>
<figcaption class="row">
<div class="caption col-sm-12 col-md-8 col-md-offset-2">
<?php the_sub_field('caption_1'); ?>
<?php get_template_part('templates/content-show-more'); ?>
</div>
</figcaption>
<?php endif; ?>
</figure>
<?php endif; ?>
</div>
</div>
</div>
</section>
<?php elseif(get_row_layout() == "page_2_images"): // layout: File ?>
<?php
$attachment_id_1 = get_sub_field('picture_1');
$attachment_id_2 = get_sub_field('picture_2');
$size = "article";
$image_1 = wp_get_attachment_image_src( $attachment_id_1, $size );
$image_2 = wp_get_attachment_image_src( $attachment_id_2, $size );
?>
<section class="deck deck-photo">
<div class="container">
<div class="row">
<div class="col-sm-6 module-sm">
<?php if($image_1) : ?>
<figure>
<img data-original="<?php echo $image_1[0]; ?>" class="img-responsive lazy" />
<?php if(get_sub_field('caption_1')): ?>
<figcaption class="caption">
<?php the_sub_field('caption_1'); ?>
<?php if(get_sub_field('page_text_hidden_1')) : ?>
<div class="hidden-text">
<?php the_sub_field('page_text_hidden_1'); ?>
</div>
<button class="btn btn-show-more">Vis mere </button>
<?php endif; ?>
</figcaption>
<?php endif; ?>
</figure>
<?php endif; ?>
</div>
<div class="col-sm-6 module-sm">
<?php if($image_2) : ?>
<figure>
<img data-original="<?php echo $image_2[0]; ?>" class="img-responsive lazy" />
<?php if(get_sub_field('caption_2')): ?>
<figcaption class="caption">
<?php the_sub_field('caption_2'); ?>
<?php if(get_sub_field('page_text_hidden_2')) : ?>
<div class="hidden-text">
<?php the_sub_field('page_text_hidden_2'); ?>
</div>
<button class="btn btn-show-more">Vis mere </button>
<?php endif; ?>
</figcaption>
<?php endif; ?>
</figure>
<?php endif; ?>
</div>
</div>
</div>
</section>
<?php elseif(get_row_layout() == "page_3_images"): // layout: File ?>
<?php
$attachment_id_1 = get_sub_field('picture_1');
$attachment_id_2 = get_sub_field('picture_2');
$attachment_id_3 = get_sub_field('picture_3');
$size = "article";
$image_1 = wp_get_attachment_image_src( $attachment_id_1, $size );
$image_2 = wp_get_attachment_image_src( $attachment_id_2, $size );
$image_3 = wp_get_attachment_image_src( $attachment_id_3, $size );
?>
<section class="deck deck-photo">
<div class="container">
<div class="row">
<div class="col-sm-4 module-sm">
<?php if($image_1) : ?>
<figure>
<img data-original="<?php echo $image_1[0]; ?>" class="img-responsive lazy" />
<?php if(get_sub_field('caption_1')): ?>
<figcaption class="caption">
<?php the_sub_field('caption_1'); ?>
<?php if(get_sub_field('page_text_hidden_1')) : ?>
<div class="hidden-text">
<?php the_sub_field('page_text_hidden_1'); ?>
</div>
<button class="btn btn-show-more">Vis mere </button>
<?php endif; ?>
</figcaption>
<?php endif; ?>
</figure>
<?php endif; ?>
</div>
<div class="col-sm-4 module-sm">
<?php if($image_2) : ?>
<figure>
<img src="<?php echo $image_2[0]; ?>" class="img-responsive lazy" />
<?php if(get_sub_field('caption_2')): ?>
<figcaption class="caption">
<?php the_sub_field('caption_2'); ?>
<?php if(get_sub_field('page_text_hidden_2')) : ?>
<div class="hidden-text">
<?php the_sub_field('page_text_hidden_2'); ?>
</div>
<button class="btn btn-show-more">Vis mere </button>
<?php endif; ?>
</figcaption>
<?php endif; ?>
</figure>
<?php endif; ?>
</div>
<div class="col-sm-4 module-sm">
<?php if($image_3) : ?>
<figure>
<img data-original="<?php echo $image_3[0]; ?>" class="img-responsive lazy" />
<?php if(get_sub_field('caption_3')): ?>
<figcaption class="caption">
<?php the_sub_field('caption_3'); ?>
<?php if(get_sub_field('page_text_hidden_3')) : ?>
<div class="hidden-text">
<?php the_sub_field('page_text_hidden_3'); ?>
</div>
<button class="btn btn-show-more">Vis mere </button>
<?php endif; ?>
</figcaption>
<?php endif; ?>
</figure>
<?php endif; ?>
</div>
</div>
</div>
</section>
<?php elseif(get_row_layout() == "page_caption"): // layout: Image left ?>
<section class="deck deck-caption">
<div class="container">
<div class="slider-caption">
<div class="row">
<?php if(get_sub_field('deck_wide')): ?>
<div class="col-md-12">
<?php else : ?>
<div class="col-md-8 col-md-offset-2">
<?php endif; ?>
<?php the_sub_field("caption"); ?>
</div>
</div>
</div>
</div>
</section>
<?php endif; ?>
<?php endwhile; ?>
</div> | a878711f81ba465b71c4e1b398a52f1df6d293d1 | [
"PHP"
] | 9 | PHP | boskakke/special | e5c995585122b451d570eb631f4aa5f2d4f63b05 | ff53c5ae85958cab44f7b89c17111050d072559e |
refs/heads/master | <repo_name>panchennb/shiftMange<file_sep>/src/main/java/model/zhijian/LessonScheduleInfo.java
package model.zhijian;
import java.util.Objects;
/**
* 课表信息
*/
public class LessonScheduleInfo {
private String dsptZjszId;//章标号(节对应的章编号,章时传本章编号)
private Integer dsptBh;//标号
private String dsptZjszName;//章节名称
private String dsptZjszLevel;//章/节类型标识(1 章节 2 小节)
private Integer ext1;//学时(章学时必须等于其下小节的学时和;所有小节的学时和必须大于等于开班信息接口中的kbsqXs)
public String getDsptZjszId() {
return dsptZjszId;
}
public void setDsptZjszId(String dsptZjszId) {
this.dsptZjszId = dsptZjszId;
}
public Integer getDsptBh() {
return dsptBh;
}
public void setDsptBh(Integer dsptBh) {
this.dsptBh = dsptBh;
}
public String getDsptZjszName() {
return dsptZjszName;
}
public void setDsptZjszName(String dsptZjszName) {
this.dsptZjszName = dsptZjszName;
}
public String getDsptZjszLevel() {
return dsptZjszLevel;
}
public void setDsptZjszLevel(String dsptZjszLevel) {
this.dsptZjszLevel = dsptZjszLevel;
}
public Integer getExt1() {
return ext1;
}
public void setExt1(Integer ext1) {
this.ext1 = ext1;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LessonScheduleInfo that = (LessonScheduleInfo) o;
return Objects.equals(dsptZjszId, that.dsptZjszId) &&
Objects.equals(dsptBh, that.dsptBh) &&
Objects.equals(dsptZjszName, that.dsptZjszName) &&
Objects.equals(dsptZjszLevel, that.dsptZjszLevel) &&
Objects.equals(ext1, that.ext1);
}
@Override
public int hashCode() {
return Objects.hash(dsptZjszId, dsptBh, dsptZjszName, dsptZjszLevel, ext1);
}
}
<file_sep>/src/main/java/model/ConditionParam.java
package model;
public class ConditionParam {
private String courseName;
private Integer isRelated;
private Integer isJoin;
private String trainingAgencyName;
private Long trainingAgencyId;
private String name;
private String id;
private String sortName;
private String sortOrder;
public String getCourseName() {
return courseName;
}
public Integer getIsRelated() {
return isRelated;
}
public void setIsRelated(Integer isRelated) {
this.isRelated = isRelated;
}
public Integer getIsJoin() {
return isJoin;
}
public void setIsJoin(Integer isJoin) {
this.isJoin = isJoin;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getTrainingAgencyName() {
return trainingAgencyName;
}
public void setTrainingAgencyName(String trainingAgencyName) {
this.trainingAgencyName = trainingAgencyName;
}
public Long getTrainingAgencyId() {
return trainingAgencyId;
}
public void setTrainingAgencyId(Long trainingAgencyId) {
this.trainingAgencyId = trainingAgencyId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSortName() {
return sortName;
}
public void setSortName(String sortName) {
this.sortName = sortName;
}
public String getSortOrder() {
return sortOrder;
}
public void setSortOrder(String sortOrder) {
this.sortOrder = sortOrder;
}
@Override
public String toString() {
return "ConditionParam{" +
"courseName='" + courseName + '\'' +
", isRelated=" + isRelated +
", isJoin=" + isJoin +
", trainingAgencyName='" + trainingAgencyName + '\'' +
", trainingAgencyId=" + trainingAgencyId +
", name='" + name + '\'' +
", id='" + id + '\'' +
", sortName='" + sortName + '\'' +
", sortOrder='" + sortOrder + '\'' +
'}';
}
}
<file_sep>/src/main/java/model/ShiftRelateInfo.java
package model;
public class ShiftRelateInfo {
private String id;// 课程主键id
private Integer isRelated;//是否关联学习计划
private Integer isJoin;//学员是否加入学习计划
private String studyPlanName;//关联学习计划名
private String studyPlanId;//关联学习计划ID
private String courseId;//课程ID
private String trainingAgencyName;//机构名
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getIsRelated() {
return isRelated;
}
public void setIsRelated(Integer isRelated) {
this.isRelated = isRelated;
}
public Integer getIsJoin() {
return isJoin;
}
public void setIsJoin(Integer isJoin) {
this.isJoin = isJoin;
}
public String getStudyPlanName() {
return studyPlanName;
}
public void setStudyPlanName(String studyPlanName) {
this.studyPlanName = studyPlanName;
}
public String getStudyPlanId() {
return studyPlanId;
}
public void setStudyPlanId(String studyPlanId) {
this.studyPlanId = studyPlanId;
}
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public String getTrainingAgencyName() {
return trainingAgencyName;
}
public void setTrainingAgencyName(String trainingAgencyName) {
this.trainingAgencyName = trainingAgencyName;
}
}
<file_sep>/src/main/java/model/yxt/UserInfoJavaModel.java
package model.yxt;
public class UserInfoJavaModel {
/**
* 用户ID(同步必传)
*/
private String id;
/**
* 用户名(同步必传)
*/
private String userName;
/**
* 中文姓名(同步必传)
*/
private String cnName;
/**
* 工号
*/
private String userNo;
/**
* 密码备注:如果用MD5或者CMD5加密则必须使用标准MD5 32位小写加密的字符串(如果不传使用平台配置的默认密码)
*/
private String password;
/**
* 密码加密方式: YXT(云学堂加密默认)、MD5 (密码MD5加密)、CMD5(用户名+密码MD5加密)
*/
private String encryptionType;
/**
* 性别
*/
private String sex;
/**
* 移动电话
*/
private String mobile;
/**
* 电子邮件
*/
private String mail;
/**
* 部门编号
*/
private String orgOuCode;
/**
* 部门名称
*/
private String orgOuName;
/**
* 岗位编号
*/
private String postionNo;
/**
* 岗位名
*/
private String postionName;
/**
* 入职日期
*/
private String entrytime;
/**
* 出生日期
*/
private String birthday;
/**
* 过期日期
*/
private String expiredDate;
/**
* 用户状态
*/
private String status;
/**
* 用户删除状态
*/
private String deleteStatus;
/**
* 是否是部门主管
*/
private int isManager = 0;
/**
* 直属经理
*/
private String managerNo;
/**
* 职级
*/
private String gradeName;
/**
* 是否置空邮箱、手机号
*/
private int isUpdateNull = 0;
/**
* 是否需要绑定手机(0:不需要,1:需要) 默认设置为自动绑定手机号 如果不需要绑定可单独将该字段设置为0
*/
private int isMobileValidated = 1;
/**
* 是否需要绑定邮箱(0:不需要,1:需要) 默认设置为自动绑定邮箱 如果不需要绑定可单独将该字段设置为0
*/
private int isEmailValidated = 1;
/**
* 扩展字段 1~10
*/
private String spare1;
private String spare2;
private String spare3;
private String spare4;
private String spare5;
private String spare6;
private String spare7;
private String spare8;
private String spare9;
private String spare10;
private String isBindWXQY;
private String wXQYOpenID;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCnName() {
return cnName;
}
public void setCnName(String cnName) {
this.cnName = cnName;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEncryptionType() {
return encryptionType;
}
public void setEncryptionType(String encryptionType) {
this.encryptionType = encryptionType;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getOrgOuCode() {
return orgOuCode;
}
public void setOrgOuCode(String orgOuCode) {
this.orgOuCode = orgOuCode;
}
public String getOrgOuName() {
return orgOuName;
}
public void setOrgOuName(String orgOuName) {
this.orgOuName = orgOuName;
}
public String getPostionNo() {
return postionNo;
}
public void setPostionNo(String postionNo) {
this.postionNo = postionNo;
}
public String getPostionName() {
return postionName;
}
public void setPostionName(String postionName) {
this.postionName = postionName;
}
public String getEntrytime() {
return entrytime;
}
public void setEntrytime(String entrytime) {
this.entrytime = entrytime;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getExpiredDate() {
return expiredDate;
}
public void setExpiredDate(String expiredDate) {
this.expiredDate = expiredDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDeleteStatus() {
return deleteStatus;
}
public void setDeleteStatus(String deleteStatus) {
this.deleteStatus = deleteStatus;
}
public int getIsManager() {
return isManager;
}
public void setIsManager(int isManager) {
this.isManager = isManager;
}
public String getManagerNo() {
return managerNo;
}
public void setManagerNo(String managerNo) {
this.managerNo = managerNo;
}
public String getGradeName() {
return gradeName;
}
public void setGradeName(String gradeName) {
this.gradeName = gradeName;
}
public int getIsUpdateNull() {
return isUpdateNull;
}
public void setIsUpdateNull(int isUpdateNull) {
this.isUpdateNull = isUpdateNull;
}
public int getIsMobileValidated() {
return isMobileValidated;
}
public void setIsMobileValidated(int isMobileValidated) {
this.isMobileValidated = isMobileValidated;
}
public int getIsEmailValidated() {
return isEmailValidated;
}
public void setIsEmailValidated(int isEmailValidated) {
this.isEmailValidated = isEmailValidated;
}
public String getSpare1() {
return spare1;
}
public void setSpare1(String spare1) {
this.spare1 = spare1;
}
public String getSpare2() {
return spare2;
}
public void setSpare2(String spare2) {
this.spare2 = spare2;
}
public String getSpare3() {
return spare3;
}
public void setSpare3(String spare3) {
this.spare3 = spare3;
}
public String getSpare4() {
return spare4;
}
public void setSpare4(String spare4) {
this.spare4 = spare4;
}
public String getSpare5() {
return spare5;
}
public void setSpare5(String spare5) {
this.spare5 = spare5;
}
public String getSpare6() {
return spare6;
}
public void setSpare6(String spare6) {
this.spare6 = spare6;
}
public String getSpare7() {
return spare7;
}
public void setSpare7(String spare7) {
this.spare7 = spare7;
}
public String getSpare8() {
return spare8;
}
public void setSpare8(String spare8) {
this.spare8 = spare8;
}
public String getSpare9() {
return spare9;
}
public void setSpare9(String spare9) {
this.spare9 = spare9;
}
public String getSpare10() {
return spare10;
}
public void setSpare10(String spare10) {
this.spare10 = spare10;
}
public String getIsBindWXQY() {
return isBindWXQY;
}
public void setIsBindWXQY(String isBindWXQY) {
this.isBindWXQY = isBindWXQY;
}
public String getwXQYOpenID() {
return wXQYOpenID;
}
public void setwXQYOpenID(String wXQYOpenID) {
this.wXQYOpenID = wXQYOpenID;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserInfoJavaModel other = (UserInfoJavaModel) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
<file_sep>/src/main/java/model/zhijian/StudentInfo.java
package model.zhijian;
/**
* 学员信息
*/
public class StudentInfo {
private Long kbxyXyid;//学员ID
private String userNo;//登录账户
private String userPass;//登录密码
private String xyxxLxdh;//电话号码
private String xyxxName;//学员姓名
private String xyxxSfzh;//身份证号
public Long getKbxyXyid() {
return kbxyXyid;
}
public void setKbxyXyid(Long kbxyXyid) {
this.kbxyXyid = kbxyXyid;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
public String getXyxxLxdh() {
return xyxxLxdh;
}
public void setXyxxLxdh(String xyxxLxdh) {
this.xyxxLxdh = xyxxLxdh;
}
public String getXyxxName() {
return xyxxName;
}
public void setXyxxName(String xyxxName) {
this.xyxxName = xyxxName;
}
public String getXyxxSfzh() {
return xyxxSfzh;
}
public void setXyxxSfzh(String xyxxSfzh) {
this.xyxxSfzh = xyxxSfzh;
}
}
<file_sep>/src/main/java/controller/StudentController.java
package controller;
import Service.ShiftInterface;
import Service.StudentInterface;
import model.ConditionParam;
import model.ShiftInfo;
import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.AliasToEntityMapResultTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.List;
@Controller
@RequestMapping("student")
public class StudentController {
private static final Logger log = LoggerFactory.getLogger(StudentController.class);
@Autowired
private StudentInterface studentInterface;
@Autowired
private ShiftInterface shiftInterface;
@PersistenceContext
private EntityManager entityManager;
/**
* 开班信息详情
*
* @param param
* @param page
* @param rows
* @return
*/
@RequestMapping(value = "/showstudent", method = RequestMethod.POST)
@ResponseBody
@CrossOrigin
public HashMap showStudent(@RequestBody ConditionParam param, int page, int rows) {
log.info("showStudent {} {},param:{}", page, rows, param);
HashMap map = new HashMap();
ShiftInfo shift = shiftInterface.findById(param.getId());
StringBuffer sql = new StringBuffer("select * from t_student where shiftinfoid = ?1");
sql.append(" and name like CONCAT('%',?2,'%')");
Query nativeQuery = entityManager.createNativeQuery(sql.toString()).unwrap(SQLQuery.class).setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
nativeQuery.setParameter(1, param.getId());
nativeQuery.setParameter(2, StringUtils.isBlank(param.getName()) ? "" : param.getName());
nativeQuery.setFirstResult((page - 1) * rows);
nativeQuery.setMaxResults(rows);
List studentList = nativeQuery.getResultList();
map.put("shift", shift);
map.put("studentList", studentList);
map.put("totalNum", studentList.size());
return map;
}
/**
* 开班信息详情
*
* @param courseId
* @param page
* @param rows
* @return
*/
@RequestMapping(value = "/showStudent", method = RequestMethod.POST)
@ResponseBody
@CrossOrigin
public HashMap showStudent(@RequestParam String name, Long studentId, Long courseId, Integer page, Integer rows) {
log.info("showStudent ====={} {}", name, studentId);
HashMap map = new HashMap();
Sort sort = Sort.by(Sort.Direction.ASC, "studentId");
ShiftInfo shift = shiftInterface.findByCourseId(courseId);
StringBuffer sql = new StringBuffer("select * from t_student where name like CONCAT('%',?1,'%') ");
if (studentId != null) {
sql.append(" and studentid = " + studentId);
}
Query nativeQuery = entityManager.createNativeQuery(sql.toString()).unwrap(SQLQuery.class).setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
nativeQuery.setParameter(1, name);
nativeQuery.setFirstResult((page - 1) * rows);
nativeQuery.setMaxResults(rows);
List studentList = nativeQuery.getResultList();
// List<Student> studentList = studentInterface.findByCourseId(courseId,PageRequest.of(page-1,rows,sort));
map.put("shift", shift);
map.put("studentList", studentList);
map.put("totalNum", studentList.size());
return map;
}
}
<file_sep>/src/main/java/model/zhijian/LessonInfo.java
package model.zhijian;
/**
* 课程信息
*/
public class LessonInfo {
private Long kbsqId;//课程ID
private String userNo;//监管机构用户名
private String userPwd;//监管机构密码
private Long kbsqJgid;//培训机构ID
private String jgglName;//培训机构名称
private String kbsqKssj;//课程开始时间
private String kbsqJssj;//课程结束时间
private Integer kbsqXs;//课程总学时
private String kbsqKcmc;//课程名称
private String kbsqZygz;//工种名称
public Long getKbsqId() {
return kbsqId;
}
public void setKbsqId(Long kbsqId) {
this.kbsqId = kbsqId;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
public Long getKbsqJgid() {
return kbsqJgid;
}
public void setKbsqJgid(Long kbsqJgid) {
this.kbsqJgid = kbsqJgid;
}
public String getJgglName() {
return jgglName;
}
public void setJgglName(String jgglName) {
this.jgglName = jgglName;
}
public String getKbsqKssj() {
return kbsqKssj;
}
public void setKbsqKssj(String kbsqKssj) {
this.kbsqKssj = kbsqKssj;
}
public String getKbsqJssj() {
return kbsqJssj;
}
public void setKbsqJssj(String kbsqJssj) {
this.kbsqJssj = kbsqJssj;
}
public Integer getKbsqXs() {
return kbsqXs;
}
public void setKbsqXs(Integer kbsqXs) {
this.kbsqXs = kbsqXs;
}
public String getKbsqKcmc() {
return kbsqKcmc;
}
public void setKbsqKcmc(String kbsqKcmc) {
this.kbsqKcmc = kbsqKcmc;
}
public String getKbsqZygz() {
return kbsqZygz;
}
public void setKbsqZygz(String kbsqZygz) {
this.kbsqZygz = kbsqZygz;
}
}
| dafe3a308253b4dbe794fb8e7fe1e7edba2cc11d | [
"Java"
] | 7 | Java | panchennb/shiftMange | d88d40012d0f50794ba13aabbd1ca69fa793fbd0 | 37b2f8a9970cefc020af6df8517713c812e14ab1 |
refs/heads/master | <repo_name>MergEye/tumblr-registration<file_sep>/tumblr.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
from random import randint
import subprocess
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.webdriver import FirefoxProfile
profile = webdriver.FirefoxProfile()
profile.set_preference("places.history.enabled", False)
profile.set_preference("privacy.clearOnShutdown.offlineApps", True)
profile.set_preference("privacy.clearOnShutdown.passwords", True)
profile.set_preference("privacy.clearOnShutdown.siteSettings", True)
profile.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
profile.set_preference("signon.rememberSignons", False)
profile.set_preference("network.cookie.lifetimePolicy", 2)
profile.set_preference("network.dns.disablePrefetch", True)
profile.set_preference("network.http.sendRefererHeader", 0)
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.socks_version", 5)
profile.set_preference("network.proxy.socks", '127.0.0.1')
profile.set_preference("network.proxy.socks_port", 9050)
profile.set_preference("network.proxy.socks_remote_dns", True)
driver = webdriver.Firefox(profile)
driver.get("https://www.tumblr.com/register")
main_win = driver.current_window_handle
assert "Tumblr" in driver.title
driver.find_element_by_css_selector('.signup_get_started_btn').click()
time.sleep(randint(5, 10))
data = [
{'signup_email': '<EMAIL>'},
{'signup_password': '<PASSWORD>'},
{'signup_username': 'DmitryKalinin6666'},
]
for user in data:
for key, value in user.iteritems():
driver.find_element_by_id(key).send_keys(value)
time.sleep(randint(5, 10))
driver.find_element_by_css_selector('.signup_account_btn').click()
time.sleep(randint(5, 10))
if driver.find_elements_by_xpath("//*[contains(text(), 'Letters, numbers, and dashes only please. This is serious business')]"):
driver.find_element_by_css_selector('.signup_account_btn').click()
time.sleep(randint(5, 10))
driver.find_element_by_id('signup_age').send_keys(20)
time.sleep(randint(5, 10))
driver.find_element_by_id('signup_tos').click()
time.sleep(randint(5, 10))
driver.find_element_by_id('signup_forms_submit').click()
driver.switch_to_frame(driver.find_elements_by_tag_name("iframe")[0])
CheckBox = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID ,"recaptcha-anchor")))
time.sleep(randint(5, 10))
CheckBox.click()
driver.switch_to.window(main_win)
time.sleep(randint(5, 10))
driver.find_element_by_css_selector('.signup_register_btn').click()
driver.close()
subprocess.call("./tor_restart.sh", shell=True)
<file_sep>/README.md
# tumblr-registration
Script for registration on tumblr.com
install [tor browser] (https://www.torproject.org/download/download.html.en)
<file_sep>/tor_restart.sh
#!/bin/bash
service tor reload
| cf3b83c73fc9eb8884e6251c8e49ea480592fb91 | [
"Markdown",
"Python",
"Shell"
] | 3 | Python | MergEye/tumblr-registration | 2e0f92fc222e12a774fbb428730cb24fb0bcad71 | 4cd3dd55eb9f4b99ff56d67358da348b7bf62ba0 |
refs/heads/master | <repo_name>Symfomany/dojoFourteen<file_sep>/README.md
### Objectif: Playing With Lists/Arrays Series
Given an array of integers , Find the minimum sum which is obtained from summing each Two integers product .
### Contraintes
* Array/list will contain positives only .
* Array/list will always has even size
Examples:
```
minSum(5,4,2,3) ==> return (22)
// because 5*2 + 3*4 = 22
```
```
minSum(12,6,10,26,3,24) ==> return (342)
// because 3*26 + 6*24 + 10*12 = 342
```
Link
[https://www.codewars.com/kata/minimize-sum-of-array-array-series-number-1](https://www.codewars.com/kata/minimize-sum-of-array-array-series-number-1)
<file_sep>/index.js
function summing(integers) {}
| fad0cc8288a501940fffc35ca2099611a02c8331 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Symfomany/dojoFourteen | 9c9dd4c8e0385b10dd5d754225b738aca6f510ad | af3aa3feacec3ebd0007b9cda1dd57fd2f9f4aa3 |
refs/heads/master | <repo_name>Shraddha2702/Java-Files<file_sep>/README.md
# Project1
This is just a demo first project to see the usage.
<file_sep>/Exceptions/ExceptionTest1.java
//Exception Handling
class ExceptionTest1
{
public static void main(String args[])
{
int a=10;
int b=0;
try
{
if(b==0)
{
throw new ArithmeticException();
}
else
{
System.out.println("Good");
}
}
catch (NullPointerException e) {
System.out.println("Null Pointer Exception here!");
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception here !");
}
catch(Exception e)
{
System.out.println("Exception here!");
}
}
}<file_sep>/Exceptions/ExceptionTest.java
//Exceptions
import java.io.DataInputStream;
class ExceptionTest
{
public static void main(String args[])
{
try
{
int a=5;
int b=0;
System.out.println("Before Error");
int c=a/b;
//System.out.println(c);
if(a<6){
throw new myException();
}
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println("This is "+e);
}
catch(Exception e)
{
System.out.println("Catch Statement");
}
finally
{
System.out.println("This is the finally Statement");
}
}
}
class myException extends Exception
{
myException(){
System.out.println("This is my Exception created");}
} | 5512e3e0087f79a8e20175881e00be699e94c2f7 | [
"Markdown",
"Java"
] | 3 | Markdown | Shraddha2702/Java-Files | b80a2aea35b0f8bcce59faa1bb0b56eb648088cd | f9796d6d8b47a8b311f7019b3849f64661410be3 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace lab3Cs
{
public partial class Form1 : Form
{
public void button_Click(object sender, EventArgs e)
{
ComplexNumber a = new ComplexNumber();
ComplexNumber b = new ComplexNumber();
ComplexNumber c = new ComplexNumber();
ComplexNumber d = new ComplexNumber();
ComplexNumber R1 = new ComplexNumber();
ComplexNumber R2 = new ComplexNumber();
OupA.Text = a.Output();
OupB.Text = b.Output();
OupC.Text = c.Output();
OupD.Text = d.Output();
R1 = a - (b + c) / a;
OupR1.Text = R1.Output();
R2 = d * (a + c) / a;
OupR2.Text = R2.Output();
if (R1 == R2)
{
text.Text = "Числа сопряженные";
}
if (R1 != R2)
{
text.Text = "Числа не сопряженные";
}
}
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lab3Cs
{
public class ComplexNumber
{
static int f = 0;
int real;
int imaginable;
const char i = 'i';
Random r = new Random(f++);
public int Real { get => real; set => real = value; }
public int Imaginable { get => imaginable; set => imaginable = value; }
public ComplexNumber()
{
real = r.Next(0, 99);
imaginable = r.Next(0, 99);
}
public string Output()
{
string cout;
cout = $"{real} + {imaginable}*i";
return cout;
}
public static ComplexNumber operator +(ComplexNumber first, ComplexNumber second)
{
ComplexNumber num = new ComplexNumber();
num.real = first.real + second.real;
num.imaginable = first.imaginable + second.imaginable;
return num;
}
public static ComplexNumber operator -(ComplexNumber first, ComplexNumber second)
{
ComplexNumber num = new ComplexNumber();
num.real = first.real - second.real;
num.imaginable = first.imaginable - second.imaginable;
return num;
}
public static ComplexNumber operator *(ComplexNumber first, ComplexNumber second)
{
ComplexNumber num = new ComplexNumber();
num.real = first.real * second.real - first.imaginable * second.imaginable;
num.imaginable = first.real * second.imaginable + first.imaginable * second.real;
return num;
}
public static ComplexNumber operator /(ComplexNumber first, ComplexNumber second)
{
ComplexNumber num = new ComplexNumber();
num.real = (first.real * second.real + first.imaginable * second.imaginable) / (second.real * second.real + second.imaginable * second.imaginable);
num.imaginable = (first.imaginable * second.real - first.real * second.imaginable) / (second.real * second.real + second.imaginable * second.imaginable);
return num;
}
public static bool operator ==(ComplexNumber first, ComplexNumber second)
{
bool isConjugate = false;
if (first.real == second.real)
{
if (first.imaginable == second.imaginable)
{
isConjugate = true;
}
}
return isConjugate;
}
public static bool operator !=(ComplexNumber first, ComplexNumber second)
{
bool isConjugate = true;
if (first.real == second.real)
{
if (first.imaginable == second.imaginable)
{
isConjugate = false;
}
}
return isConjugate;
}
}
}
<file_sep># lab3Cs
<NAME>.
Вариант-23
| ae0c1092f69355d208a9f7b42c0d0bd767164ffe | [
"Markdown",
"C#"
] | 3 | C# | Misha1311/lab3Cs | 87e338df10246682c2293e2df88ce26c355e25f7 | 92ab7179700d3446458517355744ac901cd74d73 |
refs/heads/main | <file_sep>def Valid_Parentheses(s):
blanket_list = []
for blanket in s:
if blanket == "(" or blanket == "{" or blanket == "[":
blanket_list.append(blanket)
else:
# print(blanket_list)
if blanket_list:
# print(blanket_list)
blanket1 = blanket_list.pop()
if ord(blanket1) == ord(blanket) - 1 or ord(blanket1) == ord(blanket) - 2:
# print(ord(blanket1) == ord(blanket) + 1)
continue
else:
# print(blanket_list)
return False
else:
return False
if blanket_list:
return False
else:
return True
def main():
Valid_Parentheses("()")
Valid_Parentheses("()[]{}")
Valid_Parentheses("(]")
Valid_Parentheses("([)]")
Valid_Parentheses("{[]}")
if __name__ == 'main':
main()
| bb8e2d3d849f95547037660a66876e0f9934c8ab | [
"Python"
] | 1 | Python | mickey1233/valid_parentheses | 62694ba9b38350b728c7b589b07af3cee678afd2 | a0b2f5936578c008ddddaf39c21fb72ae1e66b4a |
refs/heads/master | <repo_name>dorrubin/simpleDraw<file_sep>/simpleDraw/ViewController.swift
//
// ViewController.swift
// simpleDraw
//
// Created by <NAME> on 10/15/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var drawView: DrawView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func clearTapped() {
let theDrawView : DrawView = drawView as DrawView
theDrawView.lines = []
theDrawView.setNeedsDisplay()
}
@IBAction func saveImage(sender: UIButton) {
print("saveImage")
UIGraphicsBeginImageContext(view.frame.size)
view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let sourceImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(sourceImage, nil, nil, nil)
}
}
| 8b2afa6131a39b3e2b2b41453e2fc6ed221fe56f | [
"Swift"
] | 1 | Swift | dorrubin/simpleDraw | 668d550bc1c6f315395d21075a9796d6f1a109a2 | 4142fb6607efed507ec661218e6ae84f10f7a74f |
refs/heads/master | <file_sep>package com.jacaCode.main;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
public abstract class Engine {
protected static final int CIRCLE_WIN = 12;
protected static final int SQUARE_WIN = 3;
private static final int DRAW = 24;
private static final int DRAW2 = 21;
private static final int X = 120;
private static final int Y = 100;
private int lastPlayIndex = 0;
private int[] occupied = {0, 0, 0, 0, 0, 0, 0, 0, 0};
protected int winCondition0;
protected int winCondition1;
protected int winCondition2;
protected int winCondition3;
protected int winCondition4;
protected int winCondition5;
protected int winCondition6;
protected int winCondition7;
private boolean turn = false;
private GraphicsContext gc;
private Alert whoWon = new Alert(AlertType.INFORMATION);
protected DrawShape drawer = new DrawShape();
// core of game, functions that place circle or square. Each game mode got it own function
protected void playAI(int number, Canvas drawAreaNumber) {
if (occupied[number] == 0) {
gc = drawAreaNumber.getGraphicsContext2D();
if (turn && !isGameWinned()) {
drawer.drawSquare(X, Y, gc);
occupied[number] = 1;
turn = false;
} else {
drawer.drawCircle(X, Y, gc);
occupied[number] = 4;
turn = true;
lastPlayIndex = number;
System.err.println("Last play index: " + lastPlayIndex);
isGameWinned();
enemyGoingToWin();
}
isGameWinned();
} else {
System.out.println("Occupied");
}
}
protected void play2P(int number, Canvas drawAreaNumber) {
System.out.println(number);
if (occupied[number] == 0) {
gc = drawAreaNumber.getGraphicsContext2D();
if (turn) {
drawer.drawSquare(X, Y, gc);
occupied[number] = 1;
turn = false;
} else {
drawer.drawCircle(X, Y, gc);
occupied[number] = 4;
turn = true;
}
lastPlayIndex = number;
isGameWinned();
} else {
System.out.println("Occupied");
}
}
private void aiPlaceSquare() {
if (!isGameWinned()) {
int random = (int) (Math.random() * 10);
if (random == 9) {
random = random - 1;
}
if (occupied[random] == 0) {
playAI(random, getDrawingArea(random));
System.out.println("I randomly placed square on: " + random);
} else if(!isDraw()) {
aiPlaceSquare();
}
}
}
private void aiPlaceSquare(int cellIndex) {
try {
if (occupied[cellIndex] == 0) {
playAI(cellIndex, getDrawingArea(cellIndex));
System.out.println("I placed square on: " + cellIndex);
} else if (occupied[cellIndex] != 0){
aiPlaceSquare();
}
} catch (ArrayIndexOutOfBoundsException are) {
aiPlaceSquare();
}
}
// functions that check if game is won, if yes who won? if no one then it's draw
private boolean isGameWinned() {
boolean isWinned = false;
if (isSquareWin()) {
whoWon.setTitle("And the winner is...");
whoWon.setHeaderText(null);
whoWon.setContentText("Square won");
whoWon.showAndWait();
isWinned = true;
reset();
} else if (isCircleWin()) {
whoWon.setTitle("And the winner is...");
whoWon.setHeaderText(null);
whoWon.setContentText("Circle won");
whoWon.showAndWait();
isWinned = true;
reset();
} else if (isDraw() && !isCircleWin() && !isSquareWin()) {
whoWon.setTitle("And the winner is...");
whoWon.setHeaderText(null);
whoWon.setContentText("It's a draw!");
whoWon.showAndWait();
isWinned = true;
reset();
}
return isWinned;
}
private boolean isCircleWin() {
setWinConditions();
int[] winConditions = {winCondition0, winCondition1, winCondition2, winCondition3, winCondition4, winCondition5, winCondition6, winCondition7};
boolean isCircleWin = false;
for (int i = 0; i < winConditions.length; i++) {
if (winConditions[i] == CIRCLE_WIN) {
isCircleWin = true;
}
}
return isCircleWin;
}
private boolean isSquareWin() {
boolean isSquareWin = false;
setWinConditions();
int[] winConditions = {winCondition0, winCondition1, winCondition2, winCondition3, winCondition4, winCondition5, winCondition6, winCondition7};
for (int i = 0; i < winConditions.length; i++) {
if (winConditions[i] == SQUARE_WIN) {
isSquareWin = true;
}
}
return isSquareWin;
}
private boolean isDraw() {
boolean isDraw = false;
int draw = 0;
for (int i = 0; i < occupied.length; i++) {
draw = draw + occupied[i];
if (draw == DRAW || draw == DRAW2) {
isDraw = true;
}
}
return isDraw;
}
//simple AI
private void enemyGoingToWin() {
setWinConditions();
int[] winConditions = {winCondition0, winCondition1, winCondition2, winCondition3, winCondition4, winCondition5, winCondition6, winCondition7};
System.out.println(winConditions.length);
for (int i = 0; i < winConditions.length; i++) {
if (turn) {
if (winConditions[i] + 4 == CIRCLE_WIN) {
try {
if (occupied[decideWhereToPlace(i)] == 0) {
System.out.println("Warning circle is going to win! I need to place square on: " + decideWhereToPlace(i) + " becouse of wincondition: " + i);
aiPlaceSquare(decideWhereToPlace(i));
} else if (occupied[decideWhereToPlace(i) + decide(i)] == 0){
System.out.println("Warning circle is going to win! I need to place square on: " + (decideWhereToPlace(i) + decide(i)) + " becouse of wincondition: " + i);
aiPlaceSquare(decideWhereToPlace(i) + decide(i));
} else if (occupied[decideWhereToPlaceNegative(i)] == 0) {
System.out.println("Warning circle is going to win! I need to place square on: " + decideWhereToPlaceNegative(i)+ " becouse of wincondition: " + i);
aiPlaceSquare(decideWhereToPlaceNegative(i));
} else if (occupied[decideWhereToPlaceNegative(i) - decide(i)] == 0) {
System.out.println("Warning circle is going to win! I need to place square on: " + (decideWhereToPlaceNegative(i) - decide(i)) + " becouse of wincondition: " + i);
aiPlaceSquare(decideWhereToPlaceNegative(i) - decide(i));
}
} catch (ArrayIndexOutOfBoundsException arrException) {
System.err.println(" ");
aiPlaceSquare(4 + decideWhereToPlace(i));
}
}
}
}
if (turn) {
aiPlaceSquare();
}
}
private int decideWhereToPlace(int i) {
int decide = lastPlayIndex;
switch (i) {
case 0: case 1: case 2:
decide = decide + 3;
break;
case 3: case 4: case 5:
decide = decide + 1;
break;
case 6:
decide = decide + 4;
break;
case 7:
decide = decide + 2;
break;
default:
break;
}
return decide;
}
private int decide(int i) {
int decide = lastPlayIndex;
switch (i) {
case 0: case 1: case 2:
decide = decide + 3;
break;
case 3: case 4: case 5:
decide = decide + 1;
break;
case 6:
decide = decide + 4;
break;
case 7:
decide = decide + 2;
break;
default:
break;
}
return decide;
}
private int decideWhereToPlaceNegative(int i) {
int decide = lastPlayIndex;
switch (i) {
case 0: case 1: case 2:
decide = decide - 3;
break;
case 3: case 4: case 5:
decide = decide - 1;
break;
case 6:
decide = decide - 4;
break;
case 7:
decide = decide - 2;
break;
default:
break;
}
return decide;
}
// utility functions
private void reset() {
clearCanvases();
for (int i = 0; i < occupied.length; i++) {
occupied[i] = 0;
turn = false;
lastPlayIndex = 0;
}
}
private void clearCanvases() {
Canvas[] drawAreas = getCanvasArray();
for (int i = 0; i < drawAreas.length; i++) {
GraphicsContext gc = drawAreas[i].getGraphicsContext2D();
drawer.clear(120, 100, gc);
}
}
protected void setWinConditions() {
winCondition0 = occupied[0] + occupied[3] + occupied[6];
winCondition1 = occupied[1] + occupied[4] + occupied[7];
winCondition2 = occupied[2] + occupied[5] + occupied[8];
winCondition3 = occupied[0] + occupied[1] + occupied[2];
winCondition4 = occupied[3] + occupied[4] + occupied[5];
winCondition5 = occupied[6] + occupied[7] + occupied[8];
winCondition6 = occupied[0] + occupied[4] + occupied[8];
winCondition7 = occupied[2] + occupied[4] + occupied[6];
}
public abstract Canvas getDrawingArea(int number);
public abstract Canvas[] getCanvasArray();
}<file_sep>Tic-Tac-Toe-Game is a simple Tic Tac Toe Game. But insted of crosses it got squares!
| ef6b9c7759354c03fd654b504889bba1a8ad552f | [
"Markdown",
"Java"
] | 2 | Java | JacaCode122/Tic-Tac-Toe-Game | 6e9ef686314e825d7352a833bb2067f6a335f0a1 | 47edd05e245b2ece3c70964af346f1c463afe107 |
refs/heads/master | <repo_name>nguyenvietmanhit/database_demo<file_sep>/mvc_demo.sql
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50505
Source Host : localhost:3306
Source Database : mvc_demo
Target Server Type : MYSQL
Target Server Version : 50505
File Encoding : 65001
Date: 2020-01-05 13:03:21
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for categories
-- ----------------------------
DROP TABLE IF EXISTS `categories`;
CREATE TABLE `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL COMMENT 'Tên danh mục',
`status` tinyint(3) DEFAULT '0' COMMENT 'Trạng thái danh mục: 0 - Inactive, 1 - Active',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Ngày tạo danh mục',
`updated_at` datetime DEFAULT NULL COMMENT 'Ngày cập nhật cuối',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for news
-- ----------------------------
DROP TABLE IF EXISTS `news`;
CREATE TABLE `news` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category_id` int(11) DEFAULT NULL COMMENT 'Id của danh mục mà tin tức thuộc về, là khóa ngoại liên kết với bảng categories',
`title` varchar(255) NOT NULL COMMENT 'Tiêu đề tin tức',
`summary` varchar(255) DEFAULT NULL COMMENT 'Mô tả ngắn cho tin tức',
`avatar` varchar(255) DEFAULT NULL COMMENT 'Tên file ảnh tin tức',
`content` text COMMENT 'Mô tả chi tiết cho sản phẩm',
`status` tinyint(3) DEFAULT '0' COMMENT 'Trạng thái danh mục: 0 - Inactive, 1 - Active',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Ngày tạo',
`updated_at` datetime DEFAULT NULL COMMENT 'Ngày cập nhật cuối',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for orders
-- ----------------------------
DROP TABLE IF EXISTS `orders`;
CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL COMMENT 'Id của user trong trường hợp đã login và đặt hàng, là khóa ngoại liên kết với bảng users',
`fullname` varchar(255) DEFAULT NULL COMMENT 'Tên khách hàng',
`address` varchar(255) DEFAULT NULL COMMENT 'Địa chỉ khách hàng',
`mobile` int(11) DEFAULT NULL COMMENT 'SĐT khách hàng',
`email` varchar(255) DEFAULT NULL COMMENT 'Email khách hàng',
`note` text COMMENT 'Ghi chú từ khách hàng',
`price_total` int(11) DEFAULT NULL COMMENT 'Tổng giá trị đơn hàng',
`payment_status` tinyint(2) DEFAULT NULL COMMENT 'Trạng thái đơn hàng: 0 - Chưa thành toán, 1 - Đã thành toán',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Ngày tạo đơn',
`updated_at` datetime DEFAULT NULL COMMENT 'Ngày cập nhật cuối',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for order_details
-- ----------------------------
DROP TABLE IF EXISTS `order_details`;
CREATE TABLE `order_details` (
`order_id` int(11) DEFAULT NULL COMMENT 'Id của order tương ứng, là khóa ngoại liên kết với bảng orders',
`product_id` int(11) DEFAULT NULL COMMENT 'Id của product tương ứng, là khóa ngoại liên kết với bảng products',
`quality` int(11) DEFAULT NULL COMMENT 'Số sản phẩm đã đặt'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for products
-- ----------------------------
DROP TABLE IF EXISTS `products`;
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category_id` int(11) DEFAULT NULL COMMENT 'Id của danh mục mà sản phẩm thuộc về, là khóa ngoại liên kết với bảng categories',
`news_id` int(11) DEFAULT NULL COMMENT 'Id của tin tức mà gắn với sản phẩm, là khóa ngoại liên kết với bảng news',
`title` varchar(255) NOT NULL COMMENT 'Tên sản phẩm',
`avatar` varchar(255) DEFAULT NULL COMMENT 'Tên file ảnh sản phẩm',
`price` int(11) DEFAULT NULL COMMENT 'Giá sản phẩm',
`summary` varchar(255) DEFAULT NULL COMMENT 'Mô tả ngắn cho sản phẩm',
`content` text COMMENT 'Mô tả chi tiết cho sản phẩm',
`status` tinyint(3) DEFAULT '0' COMMENT 'Trạng thái danh mục: 0 - Inactive, 1 - Active',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Ngày tạo',
`updated_at` datetime DEFAULT NULL COMMENT 'Ngày cập nhật cuối',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for slides
-- ----------------------------
DROP TABLE IF EXISTS `slides`;
CREATE TABLE `slides` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`news_id` int(11) DEFAULT NULL COMMENT 'Id của tin tức sẽ hiển thị trong slide, là khóa ngoại liên kết với bảng news',
`avatar` varchar(255) DEFAULT NULL COMMENT 'File ảnh slide',
`position` tinyint(3) DEFAULT NULL COMMENT 'Vị trí hiển thị của slide, ví dụ: = 0 hiển thị đầu tiên...',
`status` tinyint(3) DEFAULT '0' COMMENT 'Trạng thái danh mục: 0 - Inactive, 1 - Active',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Ngày tạo',
`updated_at` datetime DEFAULT NULL COMMENT 'Ngày cập nhật cuối',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL COMMENT '<NAME>',
`password` varchar(255) NOT NULL COMMENT '<NAME> <PASSWORD>',
`first_name` varchar(255) DEFAULT NULL COMMENT 'Fist name',
`last_name` varchar(255) DEFAULT NULL COMMENT 'Last name',
`avatar` varchar(255) DEFAULT NULL COMMENT 'File ảnh đại diện',
`jobs` varchar(255) DEFAULT NULL COMMENT 'Nghề nghiệp',
`last_login` datetime DEFAULT NULL COMMENT 'Lần đăng nhập gần đây nhất',
`facebook` varchar(255) DEFAULT NULL COMMENT 'Link facebook',
`status` tinyint(3) DEFAULT '0' COMMENT 'Trạng thái danh mục: 0 - Inactive, 1 - Active',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Ngày tạo',
`updated_at` datetime DEFAULT NULL COMMENT 'Ngày cập nhật cuối',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
| 7289814ec6caf387f42af698c26c31d7d6876101 | [
"SQL"
] | 1 | SQL | nguyenvietmanhit/database_demo | c170ff909d12881d8b8e9c9fc738fd45b93e1e7a | 0d15ee82124f9d112d5626d770238f48ea180c64 |
refs/heads/master | <file_sep><?php
//var_dump($_POST);
$id=$_POST['id'];
//$erit= $_POST['erit'];
//$eanio= $_POST['eanio'];
$eredactor= $_POST['eredactor'];
$eintegrante1= $_POST['eintegrante1'];
$eintegrante2= $_POST['eintegrante2'];
$emateria=$_POST['emateria'];
$esubmateria=$_POST['esubmateria'];
$eestado=$_POST['eestado'];
if ($_POST['id']) {
include_once('conexion/db.php');
if ($_FILES['einput']['name'] !="") {
$nombredoc=$_FILES['einput']['name'];
$directorio = 'documentos/';
$tempdoc=$_FILES['einput']['tmp_name'];
$prefijodoc=date("d.m.y-");
$finaldoc=$directorio.$prefijodoc.$nombredoc;
//move_uploaded_file($tempdoc, $directorio.$prefijodoc.$nombredoc);
move_uploaded_file($tempdoc, $finaldoc);
$qedita="UPDATE sentencia set
ministro1='$eredactor',
ministro2='$eintegrante1',
ministro3='$eintegrante2',
materia='$emateria',
submateria='$esubmateria',
estado='$eestado',
documento='$prefijodoc$nombredoc'
where id_oficio=$id";
echo $qedita;
echo "con subir archivo";
}// fin del if
else{
$qedita="UPDATE sentencia set
ministro1='$eredactor',
ministro2='$eintegrante1',
ministro3='$eintegrante2',
materia='$emateria',
submateria='$esubmateria',
estado='$eestado'
where id_oficio=$id";
echo $qedita;
echo "sin subir archivo";
}
if(mysqli_query($conn,$qedita)){
echo "Actualizado OK";
header("Location:mant_sentencias.php");
}
else{
echo "Falló edicion, intentelo denuevo o contactese con el Webmaster <EMAIL>";
header("Location:mant_sentencias.php");
}
} //fin isste id
else
{
echo "no entra a al if";
// header("Location:mant_sentencias.php");
}
?>
<file_sep><?php
include_once('conexion/db.php');
if(isset($_GET['idfolio'])){
$id=$_GET['idfolio'];
$qelimina="DELETE from sentencia where id_oficio='$id'";
echo $qelimina;
if(mysqli_query($conn,$qelimina)){
header("Location:mant_sentencias.php");
}
else{
echo "Falló ,contactese con el Webmaster <EMAIL>";
}
}
?>
<file_sep><?php
if ($_FILES['input-b2']) {
include_once('conexion/db.php');
$rit= $_POST['rit'];
$anio= $_POST['anio'];
$redactor=$_POST['redactor'];
$integrante1=$_POST['integrante1'];
$integrante2=$_POST['integrante2'];
//$ministro=$_POST['slMinistro'];
$materia=$_POST['materia'];
$submateria=$_POST['submateria'];
$estado=$_POST['estado'];
//$documento= $_POST['input-b2'];
//Subir archivo a carpeta
$directorio = 'documentos/';
$nombredoc=$_FILES['input-b2']['name'];
$tempdoc=$_FILES['input-b2']['tmp_name'];
$prefijodoc=date("d.m.y-");
if(move_uploaded_file($tempdoc, $directorio.$prefijodoc.$nombredoc))
{
$qinserta="INSERT INTO sentencia (rit,anio,ministro1,ministro2,ministro3,materia,submateria,estado,documento)
VALUES('$rit','$anio','$redactor','$integrante1','$integrante2','$materia','$submateria','$estado','$prefijodoc$nombredoc')";
//echo $qinserta;
if(mysqli_query($conn,$qinserta)){
header("Location:mant_sentencias.php");
}
else{
echo "Falló insercion, intentelo denuevo o contactese con el Webmaster <EMAIL>";
}
}
else
{
echo 'Error en la carga de archivo, intentelo denuevo o contactese con el Webmaster <EMAIL>';
header("Location:mant_sentencias.php");
}
}
?>
<file_sep><!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<!-- Fucking Popper previous Jquery-->
<script src="js/popper.min.js"></script>
<!-- Jquery -->
<script src="js/jquery.min.js"></script>
<!-- Fileinput krajee-->
<script src="js/fileinput.js"></script>
<script src="js/es.js"></script>
<link rel="stylesheet" href="css/fileinput.css"/>
<!--Datepicker bootstrap-->
<script src="js/bootstrap-datepicker.js"></script>
<script src="js/bootstrap-datepicker.es.min.js"></script>
<link href="css/bootstrap-datepicker.css" rel="stylesheet"/>
<!-- Viewport -->
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<!-- Bootstrap -->
<link rel="stylesheet" href="js/bootstrap.min.css">
<script src="js/bootstrap.min.js"></script>
<link href="js/font-awesome.min.css" rel="stylesheet">
<!-- Datatables -->
<link rel="stylesheet" type="text/css" href="js/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="js/jquery.dataTables.js"></script>
<!--Estilos CSS-->
<link rel="stylesheet" href="css/estilo.css">
<!--Scripts-->
<script src="js/eventos.js"></script>
<!-- Alertify -->
<!-- JavaScript -->
<script src="js/alertify.min.js"></script>
<!-- CSS -->
<link rel="stylesheet" href="css/alertify.min.css"/>
<!-- Default theme -->
<link rel="stylesheet" href="css/default.min.css"/>
<!-- Semantic UI theme -->
<link rel="stylesheet" href="css/semantic.min.css"/>
<!-- Bootstrap theme -->
<link rel="stylesheet" href="css/bootstrap.min.css"/>
<!-- Fin alertify -->
<!-- Inicializa krajee File input----inicializado en el input -->
<!-- Inicaliza krajee desde script pero mejor desde propiedades de etiqueta
<script>
$('#input-b2').fileinput({
language: 'es',
showRemove:false,
showUpload:false,
uploadUrl: "/file-upload-batch/2",
allowedFileExtensions: ["jpg", "png", "gif"]
});
</script>
-->
<!-- Inicializa Datatables -->
<script>
$(document).ready( function () {
$('#tabladatos')
.addClass( 'nowrap' )
.DataTable( {
"deferRender": true,
"dom": '<"top"f>rt<"bottom"ip><"clear">',
"language": {
"searchPlaceholder": "Buscar por cualquier criterio",
"lengthMenu": "Mostrar _MENU_ filas por página",
"zeroRecords": "No se encontró filas",
"info": "Página _PAGE_ de _PAGES_",
"infoEmpty": "No hay registros disponibles",
"infoFiltered": "(Filtrado de _MAX_ total de filas)",
"sSearch": "Buscar:",
"oPaginate": {
"sFirst": "Primero",
"sLast": "Último",
"sNext": "Siguiente",
"sPrevious": "Anterior"
},
},
responsive: true,
columnDefs: [
{ targets: [2, -3], className: 'dt-body-left' }
]
} );
} );
</script>
<?php
define('NUM_ITEMS_BY_PAGE', 15);
require 'conexion/db.php';
$query="SELECT * FROM materias ORDER BY materia DESC";
$resultado=mysqli_query($conn, $query);
$querytotal="SELECT count(*) as total_filas FROM sentencia";
$resultadototal=mysqli_query($conn, $querytotal);
$total_filas=mysqli_fetch_assoc($resultadototal);
$num_total_rows=$total_filas['total_filas'];
?>
<title>Materias</title>
</head>
<body>
<div class="container" style="width:50%" >
<h2 class="text-center">Mantenedor de Materias</h2>
</div>
<!-- Comienzo mantenedores -->
<!-- Ingreso Ministro-->
<div class="container" style="width:50%">
<div class="form-group">
<button type="button" class="btn btn-primary btn-lg col-lg" data-toggle="modal" data-target="#ingmateria">Ingresar Materia</button>
</div>
<div class="modal fade " id="ingmateria" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header bg-light mb-3">
<h5>Ingrese Materia</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="inserta">
<!-- Formulario ingreso -->
<form id="fimateria" action="ingmateria.php" method="post">
<input type="text" class="form-control form-group" name="nmateria" placeholder="Ingrese nombre de nueva Materia"
pattern="[a-zA-ZñÑáéíóúÁÉÍÓÚ\s]+" maxlength="200" required>
<input type="text" class="form-control form-group" name="nsubmateria" placeholder="Ingrese nombre de primera Submateria"
pattern="[0-9a-zA-ZñÑáéíóúÁÉÍÓÚ\s]+" maxlength="200" required>
<div class="modal-footer">
<button type="button bnt" class="btn btn-primary">Agregar</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div><!-- cierre div -->
<!-- Cierre ingreso de sentencias -->
<!-- Carga de datos en la tabla -->
<div class="container">
<table id="tabladatos" class="table table-hover table-striped container table-sm order-column compact" style="width:50%">
<thead>
<tr class="active table-primary">
<th>Nombre Materia</th>
<td><img src="images/editar_titulo.svg" style="width:20px"/></td>
<td><img src="images/borrar_titulo.svg" style="width:30px"/></td>
</tr>
</thead>
<tbody>
<?php
$result = $conn->query('SELECT DISTINCT materia FROM materia');
if ($result->num_rows > 0) {
echo '<tr class="table table-sm">';
while ($row = $result->fetch_assoc()) {
echo '<td>'.$row['materia'].'</td>';
//Modal editar
echo '<td ><a href="mant_submaterias.php?materia='.$row['materia'].'">
<img class="eimg" src="images/editar.svg" style="width:20px" /></a></td>';
//Eliminar
echo '<td ><a href="#" data-href="delmateria.php?materia='.$row['materia'].'" class="eliminar" data-toggle="modal" data-target="#confirm-delete" ><img class="dimg" src="images/borrar.svg" style="width:20px"/></a></td>';
echo '</tr>';
}
}
?>
</tbody>
</table>
<!-- fin tabla datos -->
</div>
<!-- modal Editar-->
<div class="modal fade" id="confirm-update" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header bg-light mb-3">
<h4 class="modal-title" id="myModalLabel">Editar</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="modal-body" id="editar">
<!-- formulario editar -->
<form id="eministro" action="#" method="post" enctype="multipart/form-data" >
<input type="hidden" id="id" >
<input type="text" class="form-control form-group" id="edministro"
pattern="[a-zA-ZñÑáéíóúÁÉÍÓÚ\s]+" maxlength="200" placeholder="Nombre Ministro" required >
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button btn" class="btn btn-success" id="btnedtmin">Editar</button>
<!-- <a class="btn btn-success btn-ok">Editar</a> -->
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- Fin modal delete -->
<!-- modal delete -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Eliminar</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>Esta a punto de eliminar.</p>
<p>Esta seguro que desea hacerlo?</p>
<p class="debug-url"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<a class="btn btn-danger btn-ok">Borrar</a>
</div>
</div>
</div>
</div>
<!-- Fin modal delete -->
<!-- Scripy llama a eliminar el registro -->
<script>
$('#confirm-delete').on('show.bs.modal', function(e) {
$(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
</script>
<!-- Fin script llama eliminar -->
<div class="footer">
<p class="rights"><a href="mailto:<EMAIL>">Desarrollado por <NAME></a></p>
</div>
</body>
</html>
<file_sep><?php
include_once('conexion/db.php');
$ministro= $_POST['nministro'];
$qinserta="INSERT INTO ministro (nombre_ministro) VALUES('$ministro')";
echo $qinserta;
if(mysqli_query($conn,$qinserta)){
header("Location:mant_ministros.php");
}
else{
echo "Falló insercion, intentelo denuevo o contactese con el Webmaster <EMAIL>";
}
?>
<file_sep><?php
include_once('conexion/db.php');
if(isset($_GET['materia'])){
$materia=$_GET['materia'];
$qelimina="DELETE from materia where materia like '$materia'";
//echo $qelimina;
if(mysqli_query($conn,$qelimina)){
//echo $qelimina;
header("Location:mant_materias.php");
}
else{
echo "Falló ,contactese con el Webmaster <EMAIL>";
}
}
?>
<file_sep><!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<!-- Fucking Popper previous Jquery-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Fileinput krajee-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.0.6/js/fileinput.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.0.6/js/locales/es.js" integrity="<KEY> crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.0.6/css/fileinput.css" integrity="<KEY> crossorigin="anonymous" />
<!--Calendario-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/locales/bootstrap-datepicker.es.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.css" rel="stylesheet"/>
<!-- Viewport -->
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<!-- Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- Datatables -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<!--Estilos CSS-->
<link rel="stylesheet" href="css/estilo.css">
<!--Scripts-->
<script src="js/eventos.js"></script>
<!--Bootstrap Multiselect CSS y JS y lenguajes-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.11/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.11/js/bootstrap-select.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.11/js/i18n/defaults-es_CL.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.11/js/i18n/defaults-es_CL.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<!-- Inicializa krajee File input -->
<!-- Inicaliza krajee desde script pero mejor desde propiedades de etiqueta
<script>
$('#input-b2').fileinput({
language: 'es',
showRemove:false,
showUpload:false,
uploadUrl: "/file-upload-batch/2",
allowedFileExtensions: ["jpg", "png", "gif"]
});
</script>
-->
<!-- Inicializa Datatables -->
<script>
$(document).ready( function () {
$('#tabladatos')
.addClass( 'nowrap' )
.DataTable( {
"deferRender": true,
"dom": '<"top"f>rt<"bottom"ip><"clear">',
"language": {
"searchPlaceholder": "Buscar por cualquier criterio",
"lengthMenu": "Mostrar _MENU_ filas por página",
"zeroRecords": "No se encontro filas",
"info": "Página _PAGE_ de _PAGES_",
"infoEmpty": "No hay registros disponibles",
"infoFiltered": "(Filtrado de _MAX_ total de filas)",
"sSearch": "Buscar:",
"oPaginate": {
"sFirst": "Primero",
"sLast": "Último",
"sNext": "Siguiente",
"sPrevious": "Anterior"
},
},
responsive: true,
columnDefs: [
{ targets: [2, -3], className: 'dt-body-left' }
]
} );
} );
</script>
<?php
define('NUM_ITEMS_BY_PAGE', 15);
require 'conexion/db.php';
$query="SELECT * FROM sentencia ORDER BY id_oficio DESC";
$resultado=mysqli_query($conn, $query);
$querytotal="SELECT count(*) as total_filas FROM sentencia";
$resultadototal=mysqli_query($conn, $querytotal);
$total_filas=mysqli_fetch_assoc($resultadototal);
$num_total_rows=$total_filas['total_filas'];
?>
<title>Sentencias</title>
</head>
<body>
<div class="container">
<div class="form-group">
<div class="row">
<div class="col-sm">
<img src="images/salir2.png" alt="salir">
</div>
<div class="col-lg">
<h2>Búsqueda de sentencias</h2>
</div>
<div class="col-sm float-right">
<img src="images/usuario.png" alt=" usuario" class="float-right">
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="container">
<div class="form-group">
<button type="button" class="btn btn-primary btn-lg col-lg" data-toggle="modal" data-target="#ingresaoficio">Ingresar Sentencia</button>
</div>
<div class="modal fade " id="ingresaoficio" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header bg-light mb-3">
<h5>Ingrese datos de sentencia</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="inserta">
<form id="ffolio" action="ingsentencia.php" method="post" enctype="multipart/form-data" >
<input type="text" class="form-control form-group" name="rit" placeholder="Rol Corte" pattern="[0-9]{1,4}" maxlength="4" required>
<div class="input-group form-group">
<input id="datepicker2" class="form-control form-group" name="anio" required>
<span class="input-group-text" id="basic-addon2" for="datepicker2" ><i class="fa fa-calendar" for="datepicker2"></i></span>
</div>
<!-- Aca va un select con los minitros -->
<select name="slMinistro[]" id="slMinistro[]" class="selectpicker mb-3 form-control form-group " data-live-search="true" multiple data-max-options="3" data-size="5" title="Seleccione ministros" data-lang="es_ES" required>
<!-- Carga select de tabla ministro -->
<?php
require 'conexion/db.php';
$mensaje = "";
$ministros="SELECT * FROM ministro";
//echo $query;
$query= mysqli_query($conn,$ministros);
while($campo = mysqli_fetch_array($query)) {
$idMinistro = $campo['id_ministro'];
$nombreMinistro = $campo['nombre_ministro'];
$apMinistro= $campo['apaterno_ministro'];
//$amMinistro = $campo['amaterno_ministro'];
echo '<option value="'.$nombreMinistro.'">'.$nombreMinistro.'</option>';
};//Fin while $resultados
?>
</select> <!-- fin select ministros -->
<select name="materia" id="materia" class="form-control mb-3" required >
<option name="" value=""></option>
<option name="Civil" value="Civil">Civil</option>
<option name="Ejecutivas" value="Ejecutivas">Ejecutivas</option>
<option name="Penal" value="Penal">Penal</option>
<option name="Laboral" value="Laboral">Laboral</option>
<option name="Familia" value="Familia">Familia</option>
<option name="Proteccion" value="Proteccion">Protección</option>
<option name="jlp" value="jlp">Juzgado Policia Local</option>
</select>
<div id="submateria"></div> <!-- Carga el select con las submaterias -->
<!-- Prueba file input krajee -->
<input id="input-b2" class="file" name="input-b2" type="file" data-show-preview="false" data-language="es" data-show-remove="false" data-show-cancel="false" data-show-upload="false" data-required="true" data-allowed-file-extensions='["doc", "docx","pdf"]'>
<!-- fin prueba file input -->
<!-- Comentado para probar funcionamient de krajee
<div class="custom-file mb-3" id="customFile" lang="es">
<input type="file" class="custom-file-input" id="fileName" required>
<label class="custom-file-label" for="fileName" data-browse="Abrir">Seleccione Sentencia</label>
</div>
-->
<div class="modal-footer">
<button type="button bnt" class="btn btn-primary" onclick="subeDatos();">Enviar</button>
</div>
</form>
<div id="resultadoinsert"></div> <!-- Eliminar -->
</div>
</div>
</div>
</div>
</div><!-- cierre div -->
<!-- Carga de datos en la tabla -->
<table id="tabladatos" class="table table-hover table-striped container table-sm order-column compact">
<thead>
<tr class="active table-primary">
<th>F.Ingreso</th>
<th>RIT</th>
<th>Año</th>
<th>Materia</th>
<th>Submateria</th>
<th>Ministro1</th>
<th>Ministro2</th>
<th>Ministro3</th>
<th>Doc.</th>
</tr>
</thead>
<tbody>
<?php
if ($num_total_rows > 0) {
$page = false;
$result = $conn->query('SELECT * FROM sentencia ORDER BY fechaingreso DESC');
if ($result->num_rows > 0) {
echo '<tr class="table table-sm">';
while ($row = $result->fetch_assoc()) {
echo '<td>'.strftime("%d-%m-%Y", strtotime($row['fechaingreso'])).'</td>';
echo '<td>'.$row['rit'].'</td>';
echo '<td>'.$row['anio'].'</td>';
echo '<td>'.$row['materia'].'</td>';
echo '<td>'.$row['submateria'].'</td>';
echo '<td>'.$row['ministro1'].'</td>';
echo '<td>'.$row['ministro2'].'</td>';
echo '<td>'.$row['ministro3'].'</td>';
echo '<td><a href="documentos/'.$row['documento'].'" target="_blank"><img src="images/doc.svg" style="width:20px"/></a></td>';
//echo '<td>'.$row['documento'].'</td>';
echo '</tr>';
}
}
echo "</tbody>"; //cierre tbody
echo "</table>";
}
?>
</body>
</html>
<file_sep><?php
include_once('conexion/db.php');
if(isset($_GET['idministro'])){
$id=$_GET['idministro'];
$qelimina="DELETE from ministro where id_ministro='$id'";
//echo $qelimina;
if(mysqli_query($conn,$qelimina)){
header("Location:mant_ministros.php");
}
else{
echo "Falló ,contactese con el Webmaster <EMAIL>";
}
}
?>
<file_sep><?php
// var_dump($_POST);
$id=$_POST['id'];
$edministro= $_POST['edministro'];
include_once('conexion/db.php');
if ($_POST['id']) {
$qedita="UPDATE ministro set nombre_ministro='$edministro' where id_ministro=$id";
if(mysqli_query($conn,$qedita)){
// header("Location:mant_ministros.php");
echo "Ministro actualizado";
}
else{
echo "Falló edición de ministro";
}
}
?>
<file_sep><?php
//Archivo de conexión a la base de datos
require 'conexion/db.php';
//Variable de búsqueda
$consultaBusqueda = $_POST['valorBusqueda'];
$fiBusqueda = $_POST['valorfiBusqueda'];
$ffBusqueda = $_POST['valorffBusqueda'];
//Filtro anti-XSS
$caracteres_malos = array("<", ">", "\"", "'", "/", "<", ">", "'", "/");
$caracteres_buenos = array("& lt;", "& gt;", "& quot;", "& #x27;", "& #x2F;", "& #060;", "& #062;", "& #039;", "& #047;");
$consultaBusqueda = str_replace($caracteres_malos, $caracteres_buenos, $consultaBusqueda);
//Variable vacía (para evitar los E_NOTICE)
$mensaje = "";
$query="SELECT * FROM OFICIOS ORDER BY id_oficio DESC";
//Comprueba si $consultaBusqueda está seteado
if (isset($consultaBusqueda)) {
if (isset($fiBusqueda)) {
$query="SELECT * FROM OFICIOS
WHERE fechaingreso between STR_TO_DATE('$fiBusqueda 00:00:00', '%d-%m-%Y %H:%i:%S')
AND STR_TO_DATE('$ffBusqueda 23:59:59', '%d-%m-%Y %H:%i:%S')
AND (letra COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
OR rit COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
OR anio COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
OR origen COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
OR destino COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
OR descripcion COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%')
";
//$mensaje .= $query;
}
else{
$query="SELECT * FROM OFICIOS
WHERE letra COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
OR rit COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
OR anio COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
OR origen COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
OR destino COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
OR descripcion COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
";
//$mensaje .= $query;
}
$consulta = mysqli_query($conn,$query);
//Obtiene la cantidad de filas que hay en la consulta
$filas = mysqli_num_rows($consulta);
//Si no existe ninguna fila que sea igual a $consultaBusqueda, entonces mostramos el siguiente mensaje
if ($filas == 0) {
//$mensaje = "<p>No se encontraron coincidencias</p>";
} else {
//Si existe alguna fila que sea igual a $consultaBusqueda, entonces mostramos el siguiente mensaje
//echo 'RESULTADOS PARA <strong>'.strtoupper($consultaBusqueda).'</strong>';
//echo '<hr>';
//La variable $resultado contiene el array que se genera en la consulta, así que obtenemos los datos y los mostramos en un bucle
while($resultados = mysqli_fetch_array($consulta)) {
$folio = $resultados['id_oficio'];
$fechaingreso = $resultados['fechaingreso'];
$letra = $resultados['letra'];
$rit = $resultados['rit'];
$anio = $resultados['anio'];
$origen = $resultados['origen'];
$destino = $resultados['destino'];
$descripcion = $resultados['descripcion'];
$fingreso = $resultados['fechaingreso'];
$usuario = $resultados['usuario'];
$fingreso = $resultados['fechaingreso'];
//Output
$mensaje .= '<tr class="table table-sm" >;
<td><p class="font-weight-bold">'.$folio."-".date("Y",strtotime($fechaingreso)).'</p></td>;
<td>'.$letra.'</td>;
<td>'.$rit.'</td>;
<td>'.$anio.'</td>;
<td>'.$origen.'</td>;
<td>'.$destino.'</td>;
<td>'.$descripcion.'</td>;
<td>'.$fingreso.'</td>;
<td>'.$usuario.'</td>;
<td>'.$documento.'</td>;
</tr>';
};//Fin while $resultados
}; //Fin else $filas
};//Fin isset $consultaBusqueda
//Devolvemos el mensaje que tomará jQuery
echo $mensaje;
//echo $query;
?><file_sep><?php
echo "archivo_". date("dmyHis");
?><file_sep>
<?php
require 'conexion/db.php';
$consultamateria = $_POST['bmateria'];
$mensaje = "";
if (isset($consultamateria)) {
$query="SELECT * FROM materia WHERE materia like '$consultamateria' ";
//echo $query;
$consulta = mysqli_query($conn,$query);
$mensaje .="<select name=\"submateria\" id=\"submateria\" class=\"form-control mb-3\">";
while($resultados = mysqli_fetch_array($consulta)) {
$submateria = $resultados['submateria'];
$name= $resultados['id_materia'];
$mensaje .= '<option name="' .$submateria. '" value="'.$submateria.'">'.$submateria.'</option>';
};//Fin while $resultados
$mensaje .="</select >";
}; //Fin else $filas
echo $mensaje;
?><file_sep><?php
if ($_FILES['input-b2']) {
include_once('conexion/db.php');
$rit= $_POST['rit'];
$anio= $_POST['anio'];
$ministro=$_POST['slMinistro'];
$materia=$_POST['materia'];
$submateria=$_POST['submateria'];
//$documento= $_POST['input-b2'];
//Subir archivo a carpeta
$directorio = 'documentos/';
$nombredoc=$_FILES['input-b2']['name'];
$tempdoc=$_FILES['input-b2']['tmp_name'];
$prefijodoc=date("d.m.y-");
if(move_uploaded_file($tempdoc, $directorio.$prefijodoc.$nombredoc))
{
$qinserta="INSERT INTO sentencia (rit,anio,ministro1,ministro2,ministro3,materia,submateria,documento)
VALUES('$rit','$anio','$ministro[0]','$ministro[1]','$ministro[2]','$materia','$submateria','$prefijodoc$nombredoc')";
//echo $qinserta;
echo $result=mysqli_query($conn,$qinserta);
}
}
?>
$('#enviar').click(function(){
rit=$('#rit').val();
anio=$('#anio').val();
slMinistro=$('#slMinistro').val();
materia=$('#materia').val();
submateria=$('#submateria').val();
input-b2=$('#input-b2').val();
subeDatos(rit, anio,slMministro,materia,submateria,input-b2);
});
function subeDatos(rit, anio,slMinistro,materia,submateria,input-b2){
//alert('subiendo datos');
cadena="rit" + rit +
"$anio" + anio +
"$slMinistro" + slMinistro +
"$materia" + materia +
"$submateria" + submateria +
"$input-b2" + input-b2 ;
$.ajax({
type: "POST",
url: "ingsentencia.php",
data: cadena,
success: function(r){
if(r==1){
//$("#tabladatos").load('../indexdt.php');
alertify.success("Datos agregados correctamente");
}else{
alertify.error("fallo ingreso de datos");
}
}
});
}
<file_sep><!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<!-- Fucking Popper previous Jquery-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Fileinput krajee-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.0.6/js/fileinput.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.0.6/js/locales/es.js" integrity="<KEY> crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.0.6/css/fileinput.css" integrity="<KEY> crossorigin="anonymous" />
<!--Calendario-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/locales/bootstrap-datepicker.es.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.css" rel="stylesheet"/>
<!-- Viewport -->
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<!-- Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- Datatables -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<!--Estilos CSS-->
<link rel="stylesheet" href="css/estilo.css">
<!--Scripts-->
<script src="js/eventos.js"></script>
<!--Bootstrap Multiselect CSS y JS y lenguajes-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.11/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.11/js/bootstrap-select.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.11/js/i18n/defaults-es_CL.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.11/js/i18n/defaults-es_CL.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<!-- Inicializa krajee File input----inicializado en el input -->
<!-- Inicaliza krajee desde script pero mejor desde propiedades de etiqueta
<script>
$('#input-b2').fileinput({
language: 'es',
showRemove:false,
showUpload:false,
uploadUrl: "/file-upload-batch/2",
allowedFileExtensions: ["jpg", "png", "gif"]
});
</script>
-->
<!-- Inicializa Datatables -->
<script>
$(document).ready( function () {
$('#tabladatos')
.addClass( 'nowrap' )
.DataTable( {
"deferRender": true,
"dom": '<"top"f>rt<"bottom"ip><"clear">',
"language": {
"searchPlaceholder": "Buscar por cualquier criterio",
"lengthMenu": "Mostrar _MENU_ filas por página",
"zeroRecords": "No se encontro filas",
"info": "Página _PAGE_ de _PAGES_",
"infoEmpty": "No hay registros disponibles",
"infoFiltered": "(Filtrado de _MAX_ total de filas)",
"sSearch": "Buscar:",
"oPaginate": {
"sFirst": "Primero",
"sLast": "Último",
"sNext": "Siguiente",
"sPrevious": "Anterior"
},
},
responsive: true,
columnDefs: [
{ targets: [2, -3], className: 'dt-body-left' }
]
} );
} );
</script>
<?php
define('NUM_ITEMS_BY_PAGE', 15);
require 'conexion/db.php';
$query="SELECT * FROM sentencia ORDER BY id_oficio DESC";
$resultado=mysqli_query($conn, $query);
$querytotal="SELECT count(*) as total_filas FROM sentencia";
$resultadototal=mysqli_query($conn, $querytotal);
$total_filas=mysqli_fetch_assoc($resultadototal);
$num_total_rows=$total_filas['total_filas'];
?>
<title>Sentencias</title>
</head>
<body>
<div class="container">
<div class="form-group">
<div class="row">
<div class="col-sm">
<img src="images/salir2.png" alt="salir">
</div>
<div class="col-lg-6">
<h2>Mantenedor de sentencias</h2>
</div>
<div class="col-sm float-right">
<img src="images/usuario.png" alt=" usuario" class="float-right">
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<!-- Comienzo mantenedores -->
<!-- Ingreso sentencias-->
<div class="container">
<div class="form-group">
<button type="button" class="btn btn-primary btn-lg col-lg" data-toggle="modal" data-target="#ingresaoficio">Ingresar Sentencia</button>
</div>
<div class="modal fade " id="ingresaoficio" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header bg-light mb-3">
<h5>Ingrese datos de sentencia</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="inserta">
<form id="ffolio" action="ingsentencia.php" method="post" enctype="multipart/form-data" >
<input type="text" class="form-control form-group" name="rit" placeholder="Rol Corte" pattern="[0-9]{1,4}" maxlength="4" required>
<div class="input-group form-group">
<input id="datepicker2" class="form-control form-group" name="anio" required>
<span class="input-group-text" id="basic-addon2" for="datepicker2" ><i class="fa fa-calendar" for="datepicker2"></i></span>
</div>
<!-- Aca va un select con los minitros -->
<select name="slMinistro[]" id="slMinistro[]" class="selectpicker mb-3 form-control form-group " data-live-search="true" multiple data-max-options="3" data-size="5" title="Seleccione ministros" data-lang="es_ES" required>
<!-- Carga select de tabla ministro -->
<?php
require 'conexion/db.php';
$mensaje = "";
$ministros="SELECT * FROM ministro";
//echo $query;
$query= mysqli_query($conn,$ministros);
while($campo = mysqli_fetch_array($query)) {
$idMinistro = $campo['id_ministro'];
$nombreMinistro = $campo['nombre_ministro'];
$apMinistro= $campo['apaterno_ministro'];
//$amMinistro = $campo['amaterno_ministro'];
echo '<option value="'.$nombreMinistro.'">'.$nombreMinistro.'</option>';
};//Fin while $resultados
?>
</select> <!-- fin select ministros -->
<select name="materia" id="materia" class="form-control mb-3" required >
<option name="" value=""></option>
<option name="Civil" value="Civil">Civil</option>
<option name="Ejecutivas" value="Ejecutivas">Ejecutivas</option>
<option name="Penal" value="Penal">Penal</option>
<option name="Laboral" value="Laboral">Laboral</option>
<option name="Familia" value="Familia">Familia</option>
<option name="Proteccion" value="Proteccion">Protección</option>
<option name="jlp" value="jlp">Juzgado Policia Local</option>
</select>
<div id="submateria"></div> <!-- Carga el select con las submaterias -->
<!-- Prueba file input krajee -->
<input id="input-b2" class="file" name="input-b2" type="file" data-show-preview="false" data-language="es" data-show-remove="false" data-show-cancel="false" data-show-upload="false" data-required="true" data-allowed-file-extensions='["doc", "docx","pdf"]'>
<!-- fin prueba file input -->
<div class="modal-footer">
<button type="button bnt" class="btn btn-primary" onclick="subeDatos();">Agregar</button>
</div>
</form>
<div id="resultadoinsert"></div> <!-- Eliminar -->
</div>
</div>
</div>
</div>
</div><!-- cierre div -->
<!-- Cierre ingreso de sentencias -->
<!-- Carga de datos en la tabla -->
<table id="tabladatos" class="table table-hover table-striped container table-sm order-column compact">
<thead>
<tr class="active table-primary">
<th>F.Ingreso</th>
<th>RIT</th>
<th>Año</th>
<th>Materia</th>
<th>Submateria</th>
<th>Ministro1</th>
<th>Ministro2</th>
<th>Ministro3</th>
<td><img src="images/editar_titulo.svg" style="width:20px"/></td>
<td><img src="images/borrar_titulo.svg" style="width:30px"/></td>
</tr>
</thead>
<tbody>
<?php
if ($num_total_rows > 0) {
$page = false;
$result = $conn->query('SELECT * FROM sentencia ORDER BY fechaingreso DESC');
if ($result->num_rows > 0) {
echo '<tr class="table table-sm">';
while ($row = $result->fetch_assoc()) {
echo '<td>'.strftime("%d-%m-%Y", strtotime($row['fechaingreso'])).'</td>';
echo '<td>'.$row['rit'].'</td>';
echo '<td>'.$row['anio'].'</td>';
echo '<td>'.$row['materia'].'</td>';
echo '<td>'.$row['submateria'].'</td>';
echo '<td>'.$row['ministro1'].'</td>';
echo '<td>'.$row['ministro2'].'</td>';
echo '<td>'.$row['ministro3'].'</td>';
//echo '<td><a href="documentos/'.$row['documento'].'" target="_blank"><img src="images/editar.svg" style="width:20px"/></a></td>';
echo '<td ><a href="#" class="edid" data-href="'.$row['id_oficio'].'" data-toggle="modal" data-target="#confirm-update" >
<img class="eimg" data-href="'.$row['id_oficio'].'" title="'.$row['id_oficio']/*solo para ver los valores en la pagina*/.'" src="images/editar.svg" style="width:20px"/></a></td>';
echo '<td ><a href="#" data-href="delsentencia.php?idfolio='.$row['id_oficio'].'" class="eliminar" data-toggle="modal" data-target="#confirm-delete" >
<img class="dimg" src="images/borrar.svg" style="width:20px"/></a></td>';
/* <button class="btn btn-default" data-href="/delete.php?id=54" data-toggle="modal" data-target="#confirm-delete">Delete record #54</button>*/
//echo '<td ><a id="eliminar" href="documentos/'.$row['documento'].'" target="_blank"><img src="images/borrar.svg" style="width:20px"/></a></td>';
//echo '<td>'.$row['documento'].'</td>';
echo '</tr>';
}
}
echo "</tbody>"; //cierre tbody
echo "</table>";
}
?>
<!-- modal Editar-->
<div class="modal fade" id="confirm-update" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Editar</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="modal-body" id="editar">
<form id="efolio" action="edtsentencia.php" method="post" enctype="multipart/form-data" >
<?php
require 'conexion/db.php';//revisar si es necesario ya que esta abierta anterior% sino sacar
$result = $conn->query('SELECT * FROM sentencia where id_oficio=');
?>
<input type="text" class="form-control form-group" name="erit" placeholder="<NAME>" pattern="[0-9]{1,4}" maxlength="4" value="sss" required>
<div class="input-group form-group">
<input id="edatepicker2" class="form-control form-group" name="eanio" required>
<span class="input-group-text" id="basic-addon2" for="datepicker2" ><i class="fa fa-calendar" for="datepicker2"></i></span>
</div>
<!-- Aca va un select con los minitros -->
<select name="eslMinistro[]" id="eslMinistro[]" class="selectpicker mb-3 form-control form-group " data-live-search="true" multiple data-max-options="3" data-size="5" title="Seleccione ministros" data-lang="es_ES" required>
<!-- Carga select de tabla ministro -->
<?php
require 'conexion/db.php';
$mensaje = "";
$ministros="SELECT * FROM ministro";
//echo $query;
$query= mysqli_query($conn,$ministros);
while($campo = mysqli_fetch_array($query)) {
$idMinistro = $campo['id_ministro'];
$nombreMinistro = $campo['nombre_ministro'];
$apMinistro= $campo['apaterno_ministro'];
//$amMinistro = $campo['amaterno_ministro'];
echo '<option value="'.$nombreMinistro.'">'.$nombreMinistro.'</option>';
};//Fin while $resultados
?>
</select> <!-- fin select ministros -->
<select name="emateria" id="emateria" class="form-control mb-3" required >
<option name="" value=""></option>
<option name="Civil" value="Civil">Civil</option>
<option name="Ejecutivas" value="Ejecutivas">Ejecutivas</option>
<option name="Penal" value="Penal">Penal</option>
<option name="Laboral" value="Laboral">Laboral</option>
<option name="Familia" value="Familia">Familia</option>
<option name="Proteccion" value="Proteccion">Protección</option>
<option name="jlp" value="jlp">Juzgado Policia Local</option>
</select>
<div id="submateria"></div> <!-- Carga el select con las submaterias -->
<!-- Prueba file input krajee -->
<input id="einput-b2" class="file" name="input-b2" type="file" data-show-preview="false" data-language="es" data-show-remove="false" data-show-cancel="false" data-show-upload="false" data-required="true" data-allowed-file-extensions='["doc", "docx","pdf"]'>
<!-- fin prueba file input -->
<div class="modal-footer">
<button type="button bnt" class="btn btn-primary" onclick="subeDatos();">Agregar</button>
</div>
</form>
<div id="resultadoinsert"></div> <!-- Eliminar -->
</div>
</p>
<p class="debug-url"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a class="btn btn-danger btn-ok">Editar</a>
</div>
</div>
</div>
</div>
<!-- Fin modal delete -->
<!-- modal delete -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Eliminar</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>Esta a punto de eliminar.</p>
<p>Esta seguro que desea hacerlo?</p>
<p class="debug-url"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a class="btn btn-danger btn-ok">Borrar</a>
</div>
</div>
</div>
</div>
<!-- Fin modal delete -->
<!-- Scripy llama a eliminar el registro -->
<script>
$('#confirm-delete').on('show.bs.modal', function(e) {
$(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
</script>
<!-- Fin script llama eliminar -->
</body>
</html>
<file_sep><?php
//var_dump($_POST);
$materia=$_POST['materia'];
$submateria= $_POST['submateria'];
$oldsubmateria= $_POST['oldsubmateria'];
include_once('conexion/db.php');
if ($_POST['materia']) {
$qedita="UPDATE materia set submateria='$submateria' where materia='$materia' and submateria='$oldsubmateria' ";
//echo $qedita;
if(mysqli_query($conn,$qedita)){
// header("Location:mant_ministros.php");
echo "Submateria Actualizada";
}
else{
echo "Falló edición de submateria";
}
}
?>
<file_sep><?php
require 'conexion/db.php';
$mensaje = "";
$ministros="SELECT * FROM ministro";
//echo $ministros;
$query= mysqli_query($conn,$ministros);
$min =[];
while($campo = mysqli_fetch_array($query)) {
$nombreMinistro = $campo['nombre_ministro'];
//$idMinistro=$campo['id_ministro'];
echo '<option value="'.$nombreMinistro.'">'.$nombreMinistro.'</option>';
//$min[] = ['id' => $idMinistro,'nombre' => $nombreMinistro];
};//Fin while $resultados
//echo $min[];
/*
foreach ($min as $result) {
echo nl2br($result['id']." ".$result['nombre']."\n");
}
*/
//echo json_encode($min);
?> | b05702fea3543e122cfbe93bb0e36bf317d67bb0 | [
"PHP"
] | 16 | PHP | mmujicaa2/sentencias | 8de527a4a307b0331c1e2f2e38c272f64179bbe2 | 7a0ee0f1ec64f04bd897065a5bb2400080a2db5e |
refs/heads/master | <repo_name>TellAnAx/npoc_processing<file_sep>/npoc_processing.R
# R script for processing NPOC/TOC data from Shimadzu TOC analyzers
# <NAME>
# February 2020
# ----------------------------------------------------------------------------------- -
# ----------------------------------------------------------------------------------- -
# STEP 1. load packages ----
library(drake)
pkgconfig::set_config("drake::strings_in_dots" = "literals")
library(googlesheets)
library(readxl)
library(readr)
library(tidyr)
library(dplyr)
library(ggplot2)
library(purrr)
library(stringr) # 1.1.0
#
# STEP 2. set input and output files ----
WSOC_DATA = "input/wsoc" # this is the directory for input files.
WSOC_KEY = "input/key.csv"
WSOC_WEIGHTS = "input/weights.csv"
WSOC_CALIB = "processed/calibration.csv"
CALIB_PLOT = "processed/calibration.tiff"
WSOC_RESULTS = "processed/wsoc_results.csv"
WATER_VOL = 40 # volume of water added for extraction, mL
### save all raw data files as .csv files in the directory "data/wsoc_data"
### make sure all the .csv files have the same column names
#
# STEP 3. import data files ---------------------------- ####
wsoc_raw = sapply(list.files(path = WSOC_DATA,pattern = "*.csv", full.names = TRUE),
read_csv, simplify = FALSE) %>% bind_rows()
# STEP 4. begin processing qith drake ----
wsoc_plan = drake_plan(
## i. import key ----
wsoc_key = read_csv(WSOC_KEY), # wsoc key
#core_key = read.csv(COREKEY) %>% mutate(Core = as.character(Core)), # core key
## ii. process raw data
wsoc_processed =
wsoc_raw %>%
# remove the appropriate rows
# in this case, we want Remove==NA and Excluded==1
filter(is.na(Remove)) %>%
# subset only the relevant columns, Sample Name and Area
dplyr::select(`Sample Name`, Area) %>%
group_by(`Sample Name`) %>%
dplyr::summarise(Area = mean(Area)) %>%
# the `Sample Name`` column is actually vial numbers, recorded as "Vial 1", "Vial 2", etc.
# Create a new column Vial_no by removing the "Vial " string at the start of the name.
mutate(Vial_no = str_remove(`Sample Name`, "Vial ")) %>%
# now combine with the wsoc_key
left_join(select(wsoc_key, Run,Vial_no, Sample_name, Type,Calib_ppm,Dilution), by = "Vial_no", all.x=T),
# create a new file for just the calibration standards
wsoc_calib =
wsoc_processed %>%
filter(Type=="calibration"),
## ii. calibration curves ---------------------------- ####
# plot calibration curve for each run
gg_calib =
ggplot(wsoc_calib, aes(x = Area, y = Calib_ppm))+
geom_smooth(method = "lm", color = "gray", alpha = 0.5, se = F)+
geom_point()+
# facet_wrap(~Run)+
ggtitle("Calibration curve")+
ylab("NPOC, mg/L")+
theme_bw(),
ggsave(CALIB_PLOT, gg_calib, height = 7, width = 7),
# create new columns with the slope and intercept for each calibration curve
wsoc_calib_slope =
wsoc_calib %>%
# dplyr::group_by(Run) %>%
dplyr::summarize(slope = lm(Calib_ppm~Area)$coefficients["Area"],
intercept = lm(Calib_ppm~Area)$coefficients["(Intercept)"]),
### if we are using a single calibration curve across all samples, then do this
SLOPE = mean(wsoc_calib_slope$slope),
INTERCEPT = mean(wsoc_calib_slope$intercept),
#
## iii. calculate DOC concentrations ---------------------------- ####
# first, create a file of only the sample data. no calibration or qaqc data
wsoc_samples =
wsoc_processed %>%
filter(Type=="sample") %>%
# next calculate DOC as y = mx + c
mutate(npoc = Area*SLOPE + INTERCEPT) %>%
# dilution conversions
mutate(npoc_mg_l = round(npoc*Dilution,2)) %>%
# subset only the relevant columns now
dplyr::select(`Sample_name`,npoc_mg_l),
#
## iv. calculate as mg/g ---------------------------- ####
# first, we need to retrieve weights of soil used for the extraction
# use moist weight and moisture to calculate dry soil weight used
wsoc_weights =
read_csv(WSOC_WEIGHTS) %>%
dplyr::mutate(dry_weight_g = round(moist_weight_g/((moisture_perc/100)+1),2),
soil_water_g = moist_weight_g - dry_weight_g),
wsoc_results = wsoc_samples %>%
left_join(wsoc_weights, by = "Sample_name") %>%
dplyr::mutate(wsoc_mg_g = round(npoc_mg_l * (WATER_VOL+soil_water_g)/(dry_weight_g*1000),3)) %>%
dplyr::select(Sample_name, npoc_mg_l,wsoc_mg_g),
write.csv(wsoc_results, WSOC_RESULTS, row.names = F, na=""))
message("Now type:make(wsoc_plan)
GRRR drake")
#
<file_sep>/README.md
# npoc_processing
General script for processing DOC/NPOC data from Shimadzu TOC analyzers
<NAME>
February 2020
- create calibration curve with standards
- calculate dissolved organic carbon/ non-purgeable organic carbon as mg/L
- calculate DOC/NPOC as mg/g relative to soil
example files provided in the `input` folder
| 683da5fe54f75cd3a066a6d29db5fdd1b5bdcd04 | [
"Markdown",
"R"
] | 2 | R | TellAnAx/npoc_processing | 6dd15a3b73a649625657f2d04fd25ce978d29295 | 2482a251901c836e9069d506a65563ee7d1659a9 |
refs/heads/main | <repo_name>NitikaSakhunChaudhary/Project-24-Crumpled-Ball-1<file_sep>/dustbin.js
class Dustbin{
constructor(x,y){
this.x = x;
this.y = y;
this.dustbinWidth = 200;
this.dustbinHeight = 100;
this.wallThickness = 20;
this.angle = 0;
this.boxBottomBody = Bodies.rectangle(this.x, this.y, this.dustbinWidth,this.wallThickness , {isStatic:true} );
World.add(world, this.boxBottomBody);
this.boxLeftBody = Bodies.rectangle(this.x-this.dustbinWidth/2,this.y-this.dustbinHeight/2,this.wallThickness,this.dustbinHeight,{isStatic:true});
Body.setAngle(this.boxLeftBody,this.angle);
World.add(world, this.boxLeftBody);
this.boxRightBody = Bodies.rectangle(this.x+this.dustbinWidth/2,this.y-this.dustbinHeight/2,this.wallThickness,this.dustbinHeight,{isStatic:true});
Body.setAngle(this.boxRightBody,-1*this.angle);
World.add(world, this.boxRightBody);
}
display(){
var posBottom = this.boxBottomBody.position;
var posLeft = this.boxLeftBody.position;
var posRight = this.boxRightBody.position;
push();
translate(posLeft.x,posLeft.y);
rectMode(CENTER);
angleMode(RADIANS);
fill(255);
stroke(255);
rotate(this.angle);
rect(0,0,this.wallThickness,this.dustbinHeight);
pop();
push();
translate(posRight.x, posRight.y);
rectMode(CENTER);
stroke(255);
angleMode(RADIANS);
fill(255);
rotate(-1*this.angle);
rect(0,0,this.wallThickness, this.dustbinHeight);
pop();
push();
translate(posBottom.x, posBottom.y);
rectMode(CENTER);
stroke(255);
angleMode(RADIANS);
fill(255);
rect(0,0,this.dustbinWidth, this.wallThickness);
pop();
}
}; | b6a056c8b75d04374feb90b5c4411b30ae5eb6e5 | [
"JavaScript"
] | 1 | JavaScript | NitikaSakhunChaudhary/Project-24-Crumpled-Ball-1 | 246c025cbd259c8d87edbe0b4238ebaa0e86f28f | 0abe524934b9edf90ce13478a61a8ed2645969e4 |
refs/heads/main | <file_sep>using System;
namespace Maze
{
static class Program
{
static void Main(string[] args)
{
Field.Fill(30);
Field.Print();
while (true)
{
Field.Move(Console.ReadKey().Key);
if (Field.Current.X == Field.Destination.X && Field.Current.Y == Field.Destination.Y)
{
Console.Clear();
break;
}
Console.Clear();
Field.Print();
}
Console.WriteLine("No way.");
}
}
}<file_sep>namespace Maze.Models
{
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public bool IsAccess { get; set; }
public char View { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using Maze.Models;
namespace Maze
{
public static class Field
{
public static Point Current { get; set; }
public static Point[,] Ground { get; set; }
public static int Size { get; set; }
public static Point Destination { get; set; }
public static List<Point[]> Ways { get; set; }
public static void Print()
{
for (int i = 0; i < Math.Sqrt(Ground.Length); i++)
{
for (int j = 0; j < Math.Sqrt(Ground.Length); j++)
{
if (Ground[i, j].View == '+')
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(Ground[i, j].View + " ");
Console.ResetColor();
}
else if(Ground[i, j].View == '0')
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(Ground[i, j].View + " ");
Console.ResetColor();
}
else
{
Console.Write(Ground[i, j].View + " ");
}
}
Console.WriteLine();
}
}
public static void Fill(int size)
{
Size = size;
Ground = new Point[Size, Size];
Random rnd = new Random();
for (int i = 0; i < Size; i++)
{
for (int j = 0; j < Size; j++)
{
Ground[i, j] = new Point {X = i, Y = j, View = rnd.Next(0, 3) == 0 ? '#' : '·'};
}
}
Point start = new Point { X = rnd.Next(0,Size), Y = rnd.Next(0,Size), View = '+'};
Ground[start.X, start.Y].View = start.View;
Current = start;
Point finish = new Point { X = rnd.Next(0,Size), Y = rnd.Next(0,Size), View = '0'};
Ground[finish.X, finish.Y].View = finish.View;
Destination = finish;
}
public static void Move(ConsoleKey key)
{
switch (key)
{
case ConsoleKey.UpArrow:
if (Ground[Current.X - 1, Current.Y].View != '#' || Current.X == 0)
{
Ground[Current.X, Current.Y].View = '·';
Ground[Current.X - 1, Current.Y].View = '+';
Current = Ground[Current.X - 1, Current.Y];
}
break;
case ConsoleKey.DownArrow:
if (Ground[Current.X + 1, Current.Y].View != '#' || Current.X == Size - 1)
{
Ground[Current.X, Current.Y].View = '·';
Ground[Current.X + 1, Current.Y].View = '+';
Current = Ground[Current.X + 1, Current.Y];
}
break;
case ConsoleKey.LeftArrow:
if (Ground[Current.X, Current.Y - 1].View != '#' || Current.Y == 0)
{
Ground[Current.X, Current.Y].View = '·';
Ground[Current.X, Current.Y - 1].View = '+';
Current = Ground[Current.X, Current.Y - 1];
}
break;
case ConsoleKey.RightArrow:
if (Ground[Current.X, Current.Y + 1].View != '#' || Current.Y == Size - 1)
{
Ground[Current.X, Current.Y].View = '·';
Ground[Current.X, Current.Y + 1].View = '+';
Current = Ground[Current.X, Current.Y + 1];
}
break;
}
}
public static void PathFinder()
{
Ways.Add(new [] {Current});
while (true)
{
}
}
}
} | 9821ea6ac5e52401805f593b925dc5cf3acd02ad | [
"C#"
] | 3 | C# | 0N3GH057GR34M/Maze | b4dceaafa068eff9fd3f0addd95c60eac14680fe | f4f1b0979e16b1e0ffe3d29bb3e0958b0dbba833 |
refs/heads/master | <repo_name>elcom64/auriga<file_sep>/src/com/auriga/chat/sql/MessageMapping.java
package com.auriga.chat.sql;
import com.auriga.chat.model.Message;
import org.springframework.jdbc.object.MappingSqlQuery;
import java.sql.ResultSet;
import java.sql.SQLException;
import static com.auriga.chat.sql.DataContract.MESSAGE.NICK;
import static com.auriga.chat.sql.DataContract.MESSAGE.TEXT;
import static com.auriga.chat.sql.DataContract.MESSAGE.TS;
/**
* User: e <EMAIL>
* Date: 19.09.13
*/
public class MessageMapping extends MappingSqlQuery<Message> {
public MessageMapping() {
super();
}
@Override
protected Message mapRow(ResultSet resultSet, int i) throws SQLException {
Message message = new Message();
message.setTs(resultSet.getTimestamp(TS)); // DateTime
message.setNick(resultSet.getString(NICK)); // Nick
message.setText(resultSet.getString(TEXT)); // Text
return message;
}
}
<file_sep>/selenium/src/test/AddMessageTest.java
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AddMessageTest {
public static void main(String[] args) {
// Create a new instance of the Firefox driver
WebDriver driver = new FirefoxDriver();
// Open test page
driver.get("http://localhost/chat");
// Lets make a series
for(int i = 0; i<32;i++) {
final String s = "test _# " + i + " timestamp : " + System.currentTimeMillis();
// Find the text input element by id
WebElement element = driver.findElement(By.id("text"));
// Enter something
element.sendKeys(s);
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Wait for the page to load, timeout after 5 seconds
(new WebDriverWait(driver, 5)) // fails on 4 sec
.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(By.id("messages")).getText().contains(s);
}
});
}
//
System.out.print("ok");
//Close the browser
driver.quit();
}
}<file_sep>/web/main.js
/**
* call refrehMessages every 4 sec < 5 sec
*/
setInterval(refresh, 4000);
/**
* refresh first time
*/
window.onload = function() {
refresh();
};
/**
* draw backlog messages in <div id="messages"></div>
* @param res server response
*/
function draw(res) {
var div = $('div#messages');
div.html('');
$.each(res,function(n,value) {
div.append('<p></p>');
var row = $('div p:last-child');
row.append(value.ts + " ");
row.append(value.nick +" ");
row.append(value.text);
});
// scroll down
var height = div[0].scrollHeight;
div.scrollTop(height);
}
/**
* ask server & render messages log
*/
function refresh() {
// изображаем бурную изменчивость по полю fake для IE, чтоб не кэшил запросы
// $.post() былобы решением вопроса если бs не надо было на лету разжевывать JSON ответ сервера
var arg = {fake:Date()}; // чтоб IE не кэшил
$.getJSON('service/get', arg, draw );
}
/**
* add new message from Form go GET request, then call draw() & reset Form
* @param form
*/
function addSubmit(form) {
var arg = $('form#add').serialize() + '&fake=' + Date(); // + чтоб IE не кэшил
$.getJSON('service/get', arg, draw);
form.reset();
}<file_sep>/src/com/auriga/chat/server/ContextListener.java
package com.auriga.chat.server;
/**
* User: <EMAIL>
* Date: 19.09.13
*/
import com.auriga.chat.sql.SqlAdapter;
import org.springframework.dao.DataAccessException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ContextListener implements ServletContextListener {
static final Logger log = Logger.getLogger(String.valueOf(ContextListener.class));
// Public constructor is required by servlet spec
public ContextListener() {
}
// -------------------------------------------------------
// ServletContextListener implementation
// -------------------------------------------------------
public void contextInitialized(ServletContextEvent sce) {
SqlAdapter sql = new SqlAdapter();
try {
// init DataBase structures if needed
sql.init();
// then, store sqlAdapter in servlet context to share with Servlets
sce.getServletContext().setAttribute(SqlAdapter.class.getSimpleName(), sql);
}
catch(DataAccessException dae) {
log.info("DataBase init error: " + dae.getLocalizedMessage());
dae.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent sce) {
// This manually deregisters JDBC driver, which prevents Tomcat 7 from complaining about memory leaks wrto this class
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver driver = drivers.nextElement();
try {
DriverManager.deregisterDriver(driver);
log.log(Level.INFO, String.format("deregistering jdbc driver: %s", driver));
} catch (SQLException e) {
log.log(Level.SEVERE, String.format("Error deregistering driver %s", driver), e);
}
}
}
}
<file_sep>/src/com/auriga/chat/test/SqlAdapterTest.java
package com.auriga.chat.test;
import com.auriga.chat.model.Message;
import com.auriga.chat.sql.SqlAdapter;
import org.junit.Before;
import org.junit.Test;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
/**
* User: <EMAIL>
* Date: 19.09.13
*/
public class SqlAdapterTest {
SqlAdapter sql;
/**
* для выполнения тостов надо иметь сформированную БД
* в слчае ошибок в коде создания БД вызывает исключение
* @throws Exception
*/
@Before
public void before() throws Exception {
sql = new SqlAdapter();
sql.init();
}
/**
* сначала добавим сообщения ипроверим это
* @throws Exception
*/
@Test
public void testAddMessage_GetMessages() throws Exception {
// normal
{
Message message = new Message();
message.setNick("nick" + Math.random());
message.setText("text" + Math.random());
sql.addMessage(message);
List<Message> messages = sql.getMessages();
Message message1 = messages.get(messages.size()-1);
assert(message.getText().equals(message1.getText()));
}
// nik = null
{
Message message = new Message();
message.setText("text" + Math.random());
sql.addMessage(message);
List<Message> messages = sql.getMessages();
Message message1 = messages.get(messages.size()-1);
assert(message.getText().equals(message1.getText()));
}
}
/**
* проверка выборки по дате за сегодня
* @throws Exception
*/
@Test
public void testGetMessagesSelect() throws Exception {
// get today messages
Date from = new Date(System.currentTimeMillis());
Date to = new Date(System.currentTimeMillis());
List<Message> messages = sql.getMessages(from,to);
// get yesterday messages
String sd = "2013-09-19";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date f = format.parse(sd);
Date ff = new Date(f.getTime());
List<Message> messages_y = sql.getMessages(ff,ff);
}
}
<file_sep>/src/com/auriga/chat/server/GetServlet.java
package com.auriga.chat.server;
import com.auriga.chat.model.Message;
import com.auriga.chat.sql.SqlAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.dao.DataAccessException;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* User: <EMAIL>
* Date: 19.09.13
*/
public class GetServlet extends HttpServlet {
static final Logger log = Logger.getLogger(String.valueOf(SqlAdapter.class));
protected Gson gson;
protected SqlAdapter sql;
@Override
public void init() throws ServletException {
super.init();
// create Gson object, with special date format
gson = new GsonBuilder()
.setDateFormat("dd.MM.yy HH:mm:ss")
.create();
// Get sql object created by ContextListener::contextInitialized()
sql = (SqlAdapter)getServletContext().getAttribute(SqlAdapter.class.getSimpleName());
if (sql == null) { // some error happened
throw new UnavailableException("No SlqAdapter !");
}
}
@Override
public void destroy() {
super.destroy();
}
/**
* все три типа валим в один сервлет которые разбирает по параметрам что от него требуется
* сценарий GET без параметров - выдать двухчасовой список
* сценарий GET ? from= & to= выдать выборку
* сценарий GET ? nick= & text = прикрутить сообщение и выдать 2 часовой список
*
*/
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
if(sql == null) {
log.log(Level.SEVERE, "DataBase unavailable! kill concurrent connections or check parameters");
throw new ServletException("DataBase unavailable! kill concurrent connections or check parameters");
}
Writer writer = response.getWriter();
try {
// анализ параметров и действия сразу
// **
// * 1 !действие - nick & text
String nick = request.getParameter("nick");
String text = request.getParameter("text");
// don't allow empty messages
if(text != null && text.length()>0) {
Message message = new Message(nick,text); // выпилка под размер строк - забота скула = это его ограничение - пилим в sqlAdaptere
sql.addMessage(message);
}
// **
// * 2 если есть from & to пробуем сделать выборку по дате
String fromString = request.getParameter("from");
String toString = request.getParameter("to");
// требуем оба параметра != null
if(fromString != null && toString != null) {
Date from = new Date(Long.parseLong(fromString));
Date to = new Date(Long.parseLong( toString));
List<Message> messageList = sql.getMessages(from, to);
gson.toJson(messageList,writer);
}
else {
// **
// * 3 - пусто по временнЫм параметрам - выдаем двухчасовой список
List<Message> messageList = sql.getMessages();
gson.toJson(messageList,writer);
}
}
catch (NumberFormatException nfe) {
log.log(Level.SEVERE, "incorrect date argument, plain UNIX date needed", nfe);
}
catch (DataAccessException dae) {
log.log(Level.SEVERE, "Servlet ata Access Exception", dae);
}
}
}
<file_sep>/selenium/src/test/WrongDateTest.java
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class WrongDateTest {
public static void main(String[] args) {
// Create a new instance of the Firefox driver
WebDriver driver = new FirefoxDriver();
// Open test page
driver.get("http://localhost/chat/history.jsp");
// Wrong Date Example
final String wrongFrom = "20.09.2013";
final String wrongTo = "19.09.2013";
// / Find the text input element by id
WebElement from = driver.findElement(By.id("from"));
WebElement to = driver.findElement(By.id("to"));
// Enter something WRONG
from.sendKeys(wrongFrom);
to.sendKeys(wrongTo);
// Now submit the form. WebDriver will find the form for us from the element
from.submit();
// Wait for the page to load, timeout after 5 seconds
(new WebDriverWait(driver, 5))
.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(By.id("error")).getText().contains("позже");
}
});
//
System.out.print("wrong date ok");
//Close the browser
driver.quit();
}
} | a85eb8feb623642e642487f97e1bcde8d96c2f9b | [
"JavaScript",
"Java"
] | 7 | Java | elcom64/auriga | 05a32dd33e6e85ebbdd8c2f14961c17f1b22e6d4 | 8abc37650e54a52c081d410eb39f6a42330e1b3d |
refs/heads/master | <file_sep>CREATE TABLE usuario (
codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
nome VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
senha VARCHAR(150) NOT NULL
) ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE TABLE permissao (
codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
descricao VARCHAR(50) NOT NULL
) ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE TABLE usuario_permissao (
codigo_usuario BIGINT(20) NOT NULL,
codigo_permissao BIGINT(20) NOT NULL,
PRIMARY KEY(codigo_usuario, codigo_permissao),
FOREIGN KEY (codigo_usuario) REFERENCES usuario(codigo),
FOREIGN KEY (codigo_permissao) REFERENCES permissao(codigo)
) ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
INSERT INTO usuario(codigo, nome, email, senha)
VALUES (1, "admin", "admin@zinsk", "$2a$10$4NFitvKx3jM8bkdbMUrTVOQVZlnh0EqFpX3A.8u9Wuxr9fbfGvMnO");
INSERT INTO usuario(codigo, nome, email, senha)
VALUES (2, "clenio", "<EMAIL>", "$2a$10$vJoGSX/6vhkTJC/7YzT1Bu8AtfgdzT2Ohx3/UBekrR06Rf7.jCIRS");
INSERT INTO permissao(codigo, descricao) values (1, "ROLE_CADASTRAR_MARCA");
INSERT INTO permissao(codigo, descricao) values (2, "ROLE_PESQUISAR_MARCA");
INSERT INTO usuario_permissao (codigo_usuario, codigo_permissao) VALUES (1, 1);
INSERT INTO usuario_permissao (codigo_usuario, codigo_permissao) VALUES (1, 2);
INSERT INTO usuario_permissao (codigo_usuario, codigo_permissao) VALUES (2, 1);
INSERT INTO usuario_permissao (codigo_usuario, codigo_permissao) VALUES (2, 2);
<file_sep>logging.level.org.springframework.web=DEBUG
spring.jpa.database=MYSQL
spring.datasource.url=jdbc:mysql://localhost/lavajato?createDatabaseIfNotExist=true&SSL=false
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.jpa.show-sql=true
spring.jackson.deserialization.fail-on-unknown-properties=true
spring.jackson.date-format=yyyy-MM-dd | 0f7a1ba8fa2260418f0da60bd5d27b2e94ab803d | [
"SQL",
"INI"
] | 2 | SQL | liomazi/lavajato | c748e85a1b3da93ca21ff6331e44b494ce3e2cc0 | f22070fcd1e8348022ab258d4cbe299cdddf7983 |
refs/heads/master | <file_sep>$(function(){
function buildHTML(comment){
var html = `<p class="name-write--name">${comment.user_name}</p>
<p class="name-write--date">${comment.updated_time}</p>
`
if (comment.text != null) {
html = html + `<p class="name-write--small">${comment.text}</p>
`
}
if (comment.image.url != null) {
html = html + `<p><img src="${comment.image.url}" alt="image"></p>
`
}
return html;
}
$('#new_message').on('submit', function(e){
e.preventDefault();
var formData = new FormData(this);
var url = $(this).attr('action')
$.ajax({
url: url,
type: "POST",
data: formData,
dataType: 'json',
processData: false,
contentType: false
})
.done(function(data){
var html = buildHTML(data);
$('.right-mid').append(html)
$('#message_text').val('')
$('.bottom-content__form__image__field').val('')
$('.right-foot__image--display').val('')
$("html,body").animate({scrollTop: $('.name-write--small')[$('.name-write--name').length-1].getBoundingClientRect().top})
// $(".name-write--name").each(function(index,elem){
// $("html,body").animate({scrollTop:$(elem).offset().top});
// });
})
.fail(function(){
alert('メッセージを入力してください');
})
})
});
<file_sep>class MessagesController < ApplicationController
before_action :authenticate_user!,only: :index
before_action :get_instance
def index
respond_to do |format|
format.html
format.json
end
end
def create
@message = Message.new(message_params)
if @message.save
flash[:notice] = "メッセージの作成に成功しました。"
respond_to do |format|
format.html { redirect_to action: :index }
format.json
end
else
flash[:alert] = "メッセージを送信してください"
render action: :index
end
end
private
def get_instance
@group = Group.find(params[:group_id])
@groups = current_user.groups
@message = Message.new
@messages = @group.messages
end
def message_params
params.require(:message).permit(:text, :image).merge(group_id: params[:group_id].to_i,user_id: current_user.id)
end
end
<file_sep>class Group < ApplicationRecord
validates :name, presence: true
has_many :usergroups
has_many :users, through: :usergroups
has_many :messages
end
<file_sep>json.text @message.text
json.image @message.image
json.user_name @message.user.name
json.updated_time @message.time
<file_sep>class GroupsController < ApplicationController
before_action :authenticate_user!
def index
@group = Group.new
@groups = current_user.groups
end
def new
@group = Group.new
@users = User.where(id: current_user.id)
end
def create
@group = Group.new(group_permit_params)
if @group.save
flash[:notice] = "グループの作成に成功しました。"
redirect_to action: :index
else
@user = User.all
flash[:alert] = "グループの作成に失敗しました。"
render action: :new
end
end
def edit
@group = Group.find(params[:id])
@users = @group.users
end
def update
@group = Group.find(params[:id])
if @group.update(group_permit_params)
flash[:notice] = "グループの編集に成功しました。"
redirect_to action: :index
else
@user = User.all
flash[:notice] = "グループの編集に失敗しました。"
render action: :edit
end
end
private
def group_permit_params
params.require(:group).permit(:name, user_ids: [])
end
end
<file_sep>class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :usergroups
has_many :groups,through: :usergroups
has_many :messages
scope :search, -> (keyword,user_id){ where('name LIKE(?)', "%#{keyword}%").where.not(id: user_id).limit(20) }
end
<file_sep>json.messages @messages.each do |message|
json.name message.user.name
json.date message.time
json.image message.image
json.id message.id
json.text message.text
end
<file_sep>class UsersController < ApplicationController
def index
user_id = []
if params[:user_ids]
params[:user_ids].each do |users_id|
user_id << users_id.to_i
end
end
@users = User.search(params[:keyword],user_id)
respond_to do |format|
format.html
format.json { render 'index', json: @users }
end
end
def edit
@user = User.find(current_user.id)
end
def update
user = User.find(current_user.id)
user.update(params_permit)
redirect_to controller: :groups, action: :index
end
private
def params_permit
params.require(:user).permit(:name,:email)
end
end
| eb2099ce3839bae0c5fe0377e492e4f85176bb69 | [
"JavaScript",
"Ruby"
] | 8 | JavaScript | tekonfo/chat-space | b0b585293e2f7371986cbbdfbd9f8ffddca3c3fe | bb39bbba9a58e548dfcdde96c75732df2f61e6c9 |
refs/heads/master | <repo_name>MuellerMarius/covid19-status<file_sep>/src/constants/index.js
export const KEYS = ['active', 'recovered', 'deaths'];
export const COLORS = ['#a4c5c6', '#d4ebd0', '#f78259'];
export const FAV_COUNTRIES = [
'Germany',
'Spain',
'Italy',
'China',
'United States of America',
'United Kingdom',
'Viet Nam',
];
export const MIN_CASES_TO_DISPLAY = 20;
export const MAX_AUTOCOMPLETE_RESULTS = 20;
<file_sep>/src/app.js
'use strict';
import * as d3 from 'd3';
import { addAutocomplete } from './autocomplete';
import * as Constants from './constants';
import './style.scss';
document.addEventListener('DOMContentLoaded', onDOMContentLoaded, false);
async function onDOMContentLoaded() {
const countryFilter = document.getElementById('countryFilter');
try {
const countries = await fetch('https://api.covid19api.com/countries')
.then(handleHttpErrors)
.then((res) => res.json())
.then((data) => data.map((elem) => elem.Country));
addAutocomplete(
countryFilter,
'country-filter',
countries,
createChart,
Constants.FAV_COUNTRIES
);
createChart();
} catch (err) {
displayLoadingScreenError(true, `${err} - Data could not be loaded.`);
}
}
window.showFavourites = function () {
const countryFilter = document.getElementById('countryFilter');
countryFilter.focus();
countryFilter.value = '';
countryFilter.dispatchEvent(new Event('input'));
event.stopPropagation();
};
window.createChart = async function () {
const country = document.getElementById('countryFilter').value;
const apiRequests = [
`https://api.covid19api.com/total/country/${country}/status/confirmed`,
`https://api.covid19api.com/total/country/${country}/status/deaths`,
`https://api.covid19api.com/total/country/${country}/status/recovered`,
];
displayLoadingScreen(true);
displayLoadingScreenError(false);
try {
const data = await Promise.all(
apiRequests.map((url) =>
fetch(url)
.then(handleHttpErrors)
.then((res) => res.json())
)
).then((dataArrays) => mergeAndFormatDataArrays.apply(this, dataArrays));
data.length > 0 ? drawChart(data) : drawEmptyChart();
displayLoadingScreen(false);
} catch (err) {
displayLoadingScreenError(true, `${err} - Data could not be loaded.`);
}
};
function handleHttpErrors(response) {
if (!response.ok) {
throw Error(response.status);
}
return response;
}
function displayLoadingScreenError(displayError, errMsg) {
const loadingBars = document.getElementsByClassName('chart__loading-bar');
const errMsgDisplay = document.getElementById('chart__err-msg');
for (const bar of loadingBars) {
displayError
? bar.classList.add('chart__loading--red')
: bar.classList.remove('chart__loading--red');
}
if (errMsg && displayError) {
errMsgDisplay.innerHTML = errMsg;
errMsgDisplay.style.opacity = 1;
} else if (!displayError) {
errMsgDisplay.style.visibility = 0;
}
}
function displayLoadingScreen(displayLoadingScreen) {
document.getElementById('chart__loading').hidden = !displayLoadingScreen;
}
function mergeAndFormatDataArrays(confirmedData, deathsData, recoveredData) {
return confirmedData
.map((confElem) => {
const deaths =
deathsData.find(
(deathElem) => deathElem.Date === confElem.Date && deathElem
).Cases || 0;
const recovered =
recoveredData.find(
(recovElem) => recovElem.Date === confElem.Date && recovElem
).Cases || 0;
return {
date: new Date(confElem.Date),
active: confElem.Cases - recovered - deaths,
deaths,
recovered,
};
})
.filter(
(elem) =>
elem.active + elem.recovered + elem.deaths >
Constants.MIN_CASES_TO_DISPLAY
);
}
function drawEmptyChart() {
updateMainStats({ active: '-', recovered: '-', deaths: '-' });
d3.select('#chart__area').selectAll('svg > *').remove();
}
function updateMainStats(data) {
Constants.KEYS.map(
(key) =>
(document.getElementById(`total-${key}`).innerHTML = data[key]
.toString()
.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.'))
);
}
function drawChart(data) {
updateMainStats(data[data.length - 1]);
const stackedData = d3.stack().keys(Constants.KEYS)(data);
const svg = d3.select('#chart__area');
const margin = { top: 10, right: 20, bottom: 30, left: 20 },
width = 700 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
svg.selectAll('svg > *').remove();
svg
.attr('width', '100%')
.attr('height', '100%')
.attr('viewBox', `0 0 ${width} 400 `)
.append('g');
// X-Axis
const xAxis = (svg) =>
svg
.call((g) => g.select('.domain').remove())
.call((g) =>
g.selectAll('.tick line').attr('stroke', '#ccc').attr('opacity', 0.5)
)
.call((g) =>
g.selectAll('.tick text').attr('fill', '#ccc').attr('opacity', 0.9)
);
const x = d3
.scaleTime()
.domain(
d3.extent(data, function (d) {
return d.date;
})
)
.range([margin.left, width - margin.right]);
svg
.append('g')
.attr('transform', 'translate(0,' + height + ')')
.call(d3.axisBottom(x))
.call(xAxis);
// Y-Axis
const yAxis = (svg) =>
svg
.call(d3.axisRight(y).tickSize(width - margin.right))
.call((g) => g.select('.domain').remove())
.call((g) => g.selectAll('.tick:first-of-type line').attr('opacity', 0))
.call((g) =>
g
.selectAll('.tick:not(:first-of-type) line')
.attr('stroke-opacity', 0.3)
.attr('stroke-dasharray', '2,2')
.attr('stroke', '#ccc')
)
.call((g) =>
g
.selectAll('.tick text')
.attr('opacity', 0.9)
.attr('fill', '#ccc')
.attr('x', 4)
.attr('dy', -4)
);
const y = d3
.scaleLinear()
.domain([
0,
d3.max(data, function (d) {
return d.active + d.recovered + d.deaths;
}),
])
.range([height, margin.top + margin.bottom]);
svg.append('g').call(yAxis);
// chart areas
const area = d3
.area()
.x(function (d) {
return x(d.data.date);
})
.y0(function (d) {
return y(d[0]);
})
.y1(function (d) {
return y(d[1]);
});
svg
.append('g')
.selectAll('mylayers')
.data(stackedData)
.enter()
.append('path')
.style('fill', (d, i) => {
return Constants.COLORS[i];
})
.attr('opacity', 0.75)
.attr('d', area);
}
<file_sep>/src/autocomplete.js
'use strict';
import * as Constants from './constants';
export function addAutocomplete(object, id, data, updateFunction, favs) {
let focusedItem = -1;
object.addEventListener('input', onInputChange);
object.addEventListener('keydown', onKeyDown);
object.addEventListener('blur', () => {
updateFunction();
removeAllItems();
});
function onInputChange(e) {
const inputValue = this.value.toUpperCase();
const matches = data
.filter((elem) => elem.toUpperCase().includes(inputValue))
.sort((a, b) => a.localeCompare(b));
const itemContainer = document.createElement('div');
itemContainer.setAttribute('class', `${id}__autocomplete-container`);
removeAllItems();
focusedItem = -1;
if (matches.length < Constants.MAX_AUTOCOMPLETE_RESULTS) {
matches.map((elem) => {
itemContainer.appendChild(createItem(elem, inputValue));
});
} else if (inputValue.length === 0 && favs) {
favs.map((elem) => {
itemContainer.appendChild(createItem(elem, inputValue));
});
}
if (itemContainer.hasChildNodes())
this.parentNode.appendChild(itemContainer);
}
function onKeyDown(e) {
const items = document.getElementsByClassName(`${id}__autocomplete-item`);
switch (e.keyCode) {
case 13:
//Enter
e.preventDefault();
if (focusedItem > -1)
this.value = items[focusedItem].attributes.name.value;
removeAllItems();
object.blur();
break;
case 40:
// Arrow down
focusedItem = focusedItem === items.length - 1 ? 0 : ++focusedItem;
markItemActive(focusedItem, items);
break;
case 38:
// Arrow up
focusedItem = focusedItem === 0 ? items.length - 1 : --focusedItem;
markItemActive(focusedItem, items);
break;
default:
break;
}
}
function markItemActive(focusedItem, items) {
const itemsLength = items.length;
let i = 0;
for (i; i < itemsLength; i++) {
if (i === focusedItem) {
items[i].classList.add(`${id}__autocomplete-item--active`);
} else {
items[i].classList.remove(`${id}__autocomplete-item--active`);
}
}
}
function createItem(label, searchValue) {
const item = document.createElement('div');
const index = label.toUpperCase().indexOf(searchValue);
item.setAttribute('class', `${id}__autocomplete-item`);
item.setAttribute('name', label);
item.innerHTML =
label.substr(0, index) +
'<strong>' +
label.substr(index, searchValue.length) +
'</strong>' +
label.substr(index + searchValue.length);
item.addEventListener('mousedown', (e) => {
object.value = label;
});
return item;
}
function removeAllItems() {
const items = document.getElementsByClassName(
`${id}__autocomplete-container`
);
for (const item of items) {
item.remove();
}
}
}
<file_sep>/README.md
# covid19-status
Fetches current data about the Corona Pandemy and displays the current status in a chart. Working sample can be found [here](http://mariusmueller.info/public/covid/)

| 50ba58ece42cbe2adba7064967c6ec7cd7910d1b | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | MuellerMarius/covid19-status | f8f274be4671df937fce3e36a3cb0cb2b2567507 | f06ecaaf716ff52cc7d8ebb4d661d422779ed53e |
refs/heads/master | <file_sep>from src.training.trainer import Trainer
from src.training.features_builder import FeaturesBuilder
from src.common.loader import loadUDGrammasFromFile
import os
def train_all_models(filename):
sentences = loadUDGrammasFromFile(filename)
predictors = [
'pos',
'mood',
'voice',
'nameType',
'poss',
'reflex',
'degree',
'number',
'case',
'gender',
'verbForm',
]
for predictor in predictors:
trainer = Trainer(verbose=True)
features_builder = FeaturesBuilder(predictor)
for sentence in sentences:
(features, results) = features_builder.make_features_and_results(sentence)
trainer.append(features, results)
print("trainer %s appended. Start to train" % predictor)
trainer.train(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'model', 'ud', 'crf_%s.model' % predictor)
)
<file_sep>from src.common.nnPredictor import NnPredictor
from src.common.loader import loadUDGrammasFromFile
from src.oc.converter_oc2ud import OC2UDConverter
def nnVsCrfTest():
predictor = NnPredictor("oc", "pos")
oc_sentences = loadUDGrammasFromFile('tmp/opencorpora_parsed.txt')
# result = predictor.predict(ud_sencentes[30], 0)
# result = predictor.predict(ud_sencentes[32], 0)
# result = predictor.predict(ud_sencentes[33], 0)
result = predictor.predict(oc_sentences[34], 0)
print(result)
# oc2udConverter = OC2UDConverter(True)
# for sentenceIndex in range(len(oc_sentences)):
# sentence = oc_sentences[sentenceIndex]
# for grammaIndex in range(len(sentence)):
# gramma = sentence[grammaIndex]
# конвертируем OC в UD
# конвертируем UD в OC
<file_sep>from src.training.trainer import Trainer
from src.training.features_builder import FeaturesBuilder
from src.common.loader import loadNKRYGrammasFromFile
import os
"""
Какие предсказатели нужны для конвертации UD -> NKRY:
pos
case
mood
degree
nameType
trans
fullForm
"""
def train_all_models(filename):
sentences = loadNKRYGrammasFromFile(filename)
predictors = [
'pos',
'case',
'mood',
'degree',
'nameType',
'trans',
'fullForm',
]
for predictor in predictors:
print("start to train %s predictor" % predictor)
trainer = Trainer(True)
features_builder = FeaturesBuilder(predictor)
for sentence in sentences:
(features, results) = features_builder.make_features_and_results(sentence)
trainer.append(features, results)
print("trainer %s appended. Start to train" % predictor)
trainer.train(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'model', 'nkry', "crf_%s.model" % predictor)
)<file_sep>from src.test.nnVsCrfTest import nnVsCrfTest
nnVsCrfTest()<file_sep>import collections
import os
TAGS_ORDER = [
'unkn',
'numb',
'latn',
'pnct',
'romn',
'symb',
'post',
'noun',
'adjf',
'adjs',
'adjx',
'comp',
'verb',
'infn',
'prtf',
'prts',
'grnd',
'numr',
'advb',
'npro',
'pred',
'prep',
'conj',
'prcl',
'intj',
'anim',
'anim',
'inan',
'gndr',
'masc',
'femn',
'neut',
'ms-f',
'nmbr',
'sing',
'plur',
'sgtm',
'pltm',
'fixd',
'case',
'nomn',
'gent',
'datv',
'accs',
'ablt',
'loct',
'voct',
'gen1',
'gen2',
'acc2',
'loc1',
'loc2',
'abbr',
'name',
'surn',
'patr',
'geox',
'orgn',
'trad',
'subx',
'supr',
'qual',
'apro',
'anum',
'poss',
'v-ey',
'v-oy',
'cmp2',
'v-ej',
'aspc',
'perf',
'impf',
'impx',
'trns',
'tran',
'intr',
'impe',
'uimp',
'mult',
'refl',
'pers',
'1per',
'2per',
'3per',
'tens',
'pres',
'past',
'futr',
'mood',
'indc',
'impr',
'invl',
'incl',
'excl',
'voic',
'actv',
'pssv',
'infr',
'slng',
'arch',
'litr',
'erro',
'dist',
'ques',
'dmns',
'prnt',
'v-be',
'v-en',
'v-ie',
'v-bi',
'fimp',
'prdx',
'coun',
'coll',
'v-sh',
'af-p',
'inmx',
'vpre',
'anph',
'init',
]
class OCSaver():
def save(self, filename, sentences):
with open(filename, 'w') as targetFile:
for sentence in sentences:
targetFile.write("BEGIN\n")
for gramma in sentence:
string = self.grammaToString(gramma)
targetFile.write(string)
targetFile.write("END\n")
def grammaToString(self, gramma):
tags = []
tags.append(gramma.pos)
if gramma.gender != None: tags.append(gramma.gender)
if gramma.animacy != None: tags.append(gramma.animacy)
if gramma.number != None: tags.append(gramma.number)
if gramma.case != None: tags.append(gramma.case)
if gramma.aspect != None: tags.append(gramma.aspect)
if gramma.mood != None: tags.append(gramma.mood)
if gramma.person != None: tags.append(gramma.person)
if gramma.poss != None: tags.append(gramma.poss)
if gramma.reflex != None: tags.append(gramma.reflex)
if gramma.tense != None: tags.append(gramma.tense)
if gramma.verbForm != None: tags.append(gramma.verbForm)
if gramma.voice != None: tags.append(gramma.voice)
if gramma.degree != None: tags.append(gramma.degree)
if gramma.nameType != None: tags.append(gramma.nameType)
if gramma.trans != None: tags.append(gramma.trans)
if gramma.invl != None: tags.append(gramma.invl)
tags.extend(gramma.additional)
tags = self.sortTags(tags)
return "%s\t%s\t%s\n" % (gramma.word, gramma.lemma, ",".join(tags))
def sortTags(self, tags):
tagsDict = {}
for tag in tags:
if not tag:
continue
index = TAGS_ORDER.index(tag.lower())
tagsDict[index] = tag
tagsDict = collections.OrderedDict(sorted(tagsDict.items()))
sortedTags = []
for key, value in tagsDict.items():
sortedTags.append(value)
return sortedTags
<file_sep>from src.common.gramma import Gramma
"""
Чтение файла в массив предложений, состоящих из грамем
"""
def loadOCGrammasFromFile(filename):
with open(filename) as OC:
sentences = []
sentence = []
for line in OC:
line = line.strip()
if line == 'BEGIN':
sentence = []
continue
elif line == 'END':
sentences.append(sentence)
continue
# « « PNCT
# Школа школа NOUN,inan,femn,sing,nomn
word = None
lemma = None
pos = None
gender = None
animacy = None
number = None
case = None
aspect = None
mood = None
person = None
poss = None
reflex = None
tense = None
verbForm = None
voice = None
degree = None
nameType = None
trans = None
invl = None
additional = []
lineParts = line.strip().split('\t')
word = lineParts[0]
lemma = lineParts[1]
tags = lineParts[2] if lineParts[2] else ""
tags = tags.split(",")
pos = tags[0] if len(tags) else None
tags = tags[1:] if len(tags) > 1 else []
# род
if 'masc' in tags:
gender = 'masc'
if 'femn' in tags:
gender = 'femn'
if 'neut' in tags:
gender = 'neut'
if 'anim' in tags:
animacy = 'anim'
if 'inan' in tags:
animacy = 'inan'
if 'sing' in tags:
number = 'sing'
if 'plur' in tags:
number = 'plur'
if 'Pltm' in tags:
number = 'Pltm'
if 'Sgtm' in tags:
number = 'Sgtm'
if 'nomn' in tags:
case = 'nomn'
if 'voct' in tags:
case = 'voct'
if 'gent' in tags:
case = 'gent'
if 'gen1' in tags:
case = 'gen1'
if 'gen2' in tags:
case = 'gen2'
if 'datv' in tags:
case = 'datv'
if 'accs' in tags:
case = 'accs'
if 'acc2' in tags:
case = 'acc2'
if 'loct' in tags:
case = 'loct'
if 'loc1' in tags:
case = 'loc1'
if 'loc2' in tags:
case = 'loc2'
if 'ablt' in tags:
case = 'ablt'
if 'impf' in tags:
aspect = 'impf'
if 'perf' in tags:
aspect = 'perf'
if 'indc' in tags:
mood = 'indc'
if 'impr' in tags:
mood = 'impr'
if '1per' in tags:
person = '1per'
if '2per' in tags:
person = '2per'
if '3per' in tags:
person = '3per'
if 'past' in tags:
tense = 'past'
if 'pres' in tags:
tense = 'pres'
if 'futr' in tags:
tense = 'futr'
if 'INFN' in tags:
verbForm = 'INFN'
if 'PRTF' in tags:
verbForm = 'PRTF'
if 'PRTS' in tags:
verbForm = 'PRTS'
if 'GRND' in tags:
verbForm = 'GRND'
if 'Fimp' in tags:
verbForm = 'Fimp'
if 'V-sh' in tags:
verbForm = 'V-sh'
if 'actv' in tags:
voice = 'actv'
if 'pssv' in tags:
voice = 'pssv'
if 'ADVB' in tags:
degree = 'ADVB'
if 'COMP' in tags and 'Cmp2' in tags:
degree = 'COMP, Cmp2'
if 'COMP' in tags and 'V-ej' in tags:
degree = 'COMP, V-ej'
if 'COMP' in tags and 'Supr' in tags:
degree = 'COMP, Supr'
if 'Geox' in tags:
nameType = 'Geox'
if 'Part' in tags:
nameType = 'Part'
if 'Name' in tags:
nameType = 'Name'
if 'Surn' in tags:
nameType = 'Surn'
if 'Orgn' in tags:
nameType = 'Orgn'
if 'Trad' in tags:
nameType = 'Trad'
if 'Init' in tags:
nameType = 'Init'
if 'tran' in tags:
trans = 'tran'
if 'intr' in tags:
trans = 'intr'
if 'incl' in tags:
invl = 'tran'
if 'excl' in tags:
invl = 'intr'
if 'Infr' in tags:
additional.append('Infr')
if 'Slng' in tags:
additional.append('Slng')
if 'Arch' in tags:
additional.append('Arch')
if 'Litr' in tags:
additional.append('Litr')
if 'Erro' in tags:
additional.append('Erro')
if 'Dist' in tags:
additional.append('Dist')
if 'Ques' in tags:
additional.append('Ques')
if 'Dmns' in tags:
additional.append('Dmns')
if 'Prnt' in tags:
additional.append('Prnt')
if 'V-be' in tags:
additional.append('V-be')
if 'V-en' in tags:
additional.append('V-en')
if 'V-ie' in tags:
additional.append('V-ie')
if 'V-bi' in tags:
additional.append('V-bi')
if 'V-ey' in tags:
additional.append('V-ey')
if 'V-oy' in tags:
additional.append('V-oy')
if 'Coun' in tags:
additional.append('Coun')
if 'Af-p' in tags:
additional.append('Af-p')
if 'Anph' in tags:
additional.append('Anph')
if 'Subx' in tags:
additional.append('Subx')
if 'Vpre' in tags:
additional.append('Vpre')
if 'Prdx' in tags:
additional.append('Prdx')
if 'Coll' in tags:
additional.append('Coll')
if 'Adjx' in tags:
additional.append('Adjx')
if 'Qual' in tags:
additional.append('Qual')
if 'Apro' in tags:
additional.append('Apro')
if 'Anum' in tags:
additional.append('Anum')
if 'Poss' in tags:
additional.append('Poss')
if 'ms-f' in tags:
additional.append('ms-f')
if 'Ms-f' in tags:
additional.append('Ms-f')
if 'Impe' in tags:
additional.append('Impe')
if 'Impx' in tags:
additional.append('Impx')
if 'Mult' in tags:
additional.append('Mult')
if 'Abbr' in tags:
additional.append('Abbr')
if 'Fixd' in tags:
additional.append('Fixd')
gramma = Gramma(
word,
lemma,
pos,
gender,
animacy,
number,
case,
aspect,
mood,
person,
poss,
reflex,
tense,
verbForm,
voice,
degree,
nameType,
trans,
invl,
additional
)
sentence.append(gramma)
return sentences
def loadNKRYGrammasFromFile(filename):
with open(filename, 'r') as NKRY:
sentences = []
sentence = []
for line in NKRY:
line = line.strip()
if line == 'BEGIN':
sentence = []
continue
elif line == 'END':
sentences.append(sentence)
continue
word = None
lemma = None
pos = None
gender = None
animacy = None
number = None
case = None
aspect = None
mood = None
person = None
poss = None
reflex = None
tense = None
verbForm = None
voice = None
degree = None
nameType = None
trans = None
invl = None
fullForm = None
additional = []
lineParts = line.split('\t')
word = lineParts[0]
lemma = lineParts[1] if len(lineParts) > 1 else ""
tags = lineParts[2] if len(lineParts) > 2 else ""
tags = tags.split(",")
pos = tags[0] if len(tags) else None
tags = tags[1:] if len(tags) > 1 else []
if 'm' in tags:
gender = 'm'
if 'f' in tags:
gender = 'f'
if 'n' in tags:
gender = 'n'
if 'm-f' in tags:
gender = 'm-f'
if 'anim' in tags:
animacy = 'anim'
if 'inan' in tags:
animacy = 'inan'
if 'sg' in tags:
number = 'sg'
if 'pl' in tags:
number = 'pl'
if 'nom' in tags:
case = 'nom'
if 'voc' in tags:
case = 'voc'
if 'gen' in tags:
case = 'gen'
if 'gen2' in tags:
case = 'gen2'
if 'adnum' in tags:
case = 'adnum'
if 'dat' in tags:
case = 'dat'
if 'dat2' in tags:
case = 'dat2'
if 'acc' in tags:
case = 'acc'
if 'acc2' in tags:
case = 'acc2'
if 'loc' in tags:
case = 'loc'
if 'loc2' in tags:
case = 'loc2'
if 'ins' in tags:
case = 'ins'
if 'brev' in tags:
fullForm = 'brev'
if 'plen' in tags:
fullForm = 'plen'
if 'ipf' in tags:
aspect = 'ipf'
if 'pf' in tags:
aspect = 'pf'
if 'indic' in tags:
mood = 'indic'
if 'imper' in tags:
mood = 'imper'
if 'imper2' in tags:
mood = 'imper2'
if '1p' in tags:
person = '1p'
if '2p' in tags:
person = '2p'
if '3p' in tags:
person = '3p'
if 'praet' in tags:
tense = 'praet'
if 'praes' in tags:
tense = 'praes'
if 'fut' in tags:
tense = 'fut'
if 'inf' in tags:
verbForm = 'inf'
if 'partcp' in tags:
verbForm = 'partcp'
if 'ger' in tags:
verbForm = 'ger'
if 'act' in tags:
voice = 'act'
if 'med' in tags:
voice = 'med'
if 'pass' in tags:
voice = 'pass'
if 'comp' in tags:
degree = 'comp'
if 'comp2' in tags:
degree = 'comp2'
if 'supr' in tags:
degree = 'supr'
if 'patrn' in tags:
nameType = 'patrn'
if 'zoon' in tags:
nameType = 'zoon'
if 'persn' in tags:
nameType = 'persn'
if 'famn' in tags:
nameType = 'famn'
if 'tran' in tags:
trans = 'tran'
if 'intr' in tags:
trans = 'intr'
gramma = Gramma(
word,
lemma,
pos,
gender,
animacy,
number,
case,
aspect,
mood,
person,
poss,
reflex,
tense,
verbForm,
voice,
degree,
nameType,
trans,
invl,
additional,
fullForm
)
sentence.append(gramma)
return sentences
def loadUDGrammasFromFile(filename):
with open(filename, 'r') as UD:
sentences = []
sentence = []
for line in UD:
line = line.strip()
if line == 'BEGIN':
sentence = []
continue
elif line == 'END':
sentences.append(sentence)
continue
word = None
lemma = None
pos = None
gender = None
animacy = None
number = None
case = None
aspect = None
mood = None
person = None
poss = None
reflex = None
tense = None
verbForm = None
voice = None
degree = None
nameType = None
trans = None
invl = None
additional = []
lineParts = line.split('\t')
word = lineParts[0]
lemma = lineParts[1] if len(lineParts) > 1 else ""
tags = lineParts[2] if len(lineParts) > 2 else ""
tags = tags.split(",")
pos = tags[0] if len(tags) else None
tags = tags[1:] if len(tags) > 1 else []
if 'Gender=Masc' in tags:
gender = 'Gender=Masc'
if 'Gender=Fem' in tags:
gender = 'Gender=Fem'
if 'Gender=Neut' in tags:
gender = 'Gender=Neut'
if 'Animacy=Anim' in tags:
animacy = 'Animacy=Anim'
if 'Animacy=Inan' in tags:
animacy = 'Animacy=Inan'
if 'Number=Sing' in tags:
number = 'Number=Sing'
if 'Number=Coll' in tags:
number = 'Number=Coll'
if 'Number=Plur' in tags:
number = 'Number=Plur'
if 'Number=Ptan' in tags:
number = 'Number=Ptan'
if 'Case=Nom' in tags:
case = 'Case=Nom'
if 'Case=Gen' in tags:
case = 'Case=Gen'
if 'Case=Dat' in tags:
case = 'Case=Dat'
if 'Case=Acc' in tags:
case = 'Case=Acc'
if 'Case=Loc' in tags:
case = 'Case=Loc'
if 'Case=Ins' in tags:
case = 'Case=Ins'
if 'Aspect=Imp' in tags:
aspect = 'Aspect=Imp'
if 'Aspect=Perf' in tags:
aspect = 'Aspect=Perf'
if 'Mood=Ind' in tags:
mood = 'Mood=Ind'
if 'Mood=Cnd' in tags:
mood = 'Mood=Cnd'
if 'Mood=Imp' in tags:
mood = 'Mood=Imp'
if 'Person=1' in tags:
person = 'Person=1'
if 'Person=2' in tags:
person = 'Person=2'
if 'Person=3' in tags:
person = 'Person=3'
if 'Poss=Yes' in tags:
poss = 'Poss=Yes'
if 'Reflex=Yes' in tags:
reflex = 'Reflex=Yes'
if 'Tense=Past' in tags:
tense = 'Tense=Past'
if 'Tense=Pres' in tags:
tense = 'Tense=Pres'
if 'Tense=Fut' in tags:
tense = 'Tense=Fut'
if 'VerbForm=Fin' in tags:
verbForm = 'VerbForm=Fin'
if 'VerbForm=Inf' in tags:
verbForm = 'VerbForm=Inf'
if 'VerbForm=Part' in tags:
verbForm = 'VerbForm=Part'
if 'VerbForm=Trans' in tags:
verbForm = 'VerbForm=Trans'
if 'Voice=Act' in tags:
voice = 'Voice=Act'
if 'Voice=Mid' in tags:
voice = 'Voice=Mid'
if 'Voice=Pass' in tags:
voice = 'Voice=Pass'
if 'Degree=Pos' in tags:
degree = 'Degree=Pos'
if 'Degree=Cmp' in tags:
degree = 'Degree=Cmp'
if 'Degree=Sup' in tags:
degree = 'Degree=Sup'
if 'NameType=Geo' in tags:
nameType = 'NameType=Geo'
if 'NameType=Prs' in tags:
nameType = 'NameType=Prs'
if 'NameType=Giv' in tags:
nameType = 'NameType=Giv'
if 'NameType=Sur' in tags:
nameType = 'NameType=Sur'
if 'NameType=Com' in tags:
nameType = 'NameType=Com'
if 'NameType=Pro' in tags:
nameType = 'NameType=Pro'
if 'NameType=Oth' in tags:
nameType = 'NameType=Oth'
gramma = Gramma(
word,
lemma,
pos,
gender,
animacy,
number,
case,
aspect,
mood,
person,
poss,
reflex,
tense,
verbForm,
voice,
degree,
nameType,
trans,
invl,
additional
)
sentence.append(gramma)
return sentences
def loadGIKRYGrammasFromFile(filename):
with open(filename, 'r') as GIKRY:
sentences = []
sentence = []
for line in GIKRY:
line = line.strip()
if line == 'BEGIN':
sentence = []
continue
elif line == 'END':
sentences.append(sentence)
continue
word = None
lemma = None
pos = None
gender = None
animacy = None
number = None
case = None
aspect = None
mood = None
person = None
poss = None
reflex = None
tense = None
verbForm = None
voice = None
degree = None
nameType = None
trans = None
invl = None
fullForm = None
additional = []
nounType = None
additionalCase = None
aspectual = None
categoryOfAdjective = None
syntaxType = None
categoryOfNumeral = None
formOfNumeral = None
typeOfAdposition = None
structureOfAdposition = None
typeOfAnother = None
lineParts = line.split('\t')
word = lineParts[0]
lemma = lineParts[1] if len(lineParts) > 1 else ""
tags = lineParts[2] if len(lineParts) > 2 else ""
tags = tags.split(',')
pos = tags[0] if len(tags) else None
tags = tags[1:] if len(tags) > 1 else []
if pos == 'N':
nounType = tags[0]
gender = tags[1]
number = tags[2]
case = tags[3]
additionalCase = tags[4]
animacy = tags[5]
if pos == 'A':
degree = tags[0]
gender = tags[1] if len(tags) >= 2 else None
number = tags[2] if len(tags) >= 3 else None
case = tags[3] if len(tags) >= 4 else None
fullForm = tags[4] if len(tags) >= 5 else None
if pos == 'V':
if tags[0] in ['i', 'm']:
mood = tags[0]
elif tags[0] in ['n', 'g', 'p', 'x']:
verbForm = tags[0]
gender = tags[1]
number = tags[2]
case = tags[3] if len(tags) >= 4 else None
person = tags[4] if len(tags) >= 5 else None
tense = tags[5] if len(tags) >= 6 else None
trans = tags[6] if len(tags) >= 7 else None
voice = tags[7] if len(tags) >= 8 else None
aspect = tags[8] if len(tags) >= 9 else None
aspectual = tags[9] if len(tags) >= 10 else None
fullForm = tags[10] if len(tags) >= 11 else None
if pos == 'R':
degree = tags[0]
# if pos == 'W':
if pos == 'P':
categoryOfAdjective = tags[0]
gender = tags[1] if len(tags) >= 2 else None
number = tags[2] if len(tags) >= 3 else None
case = tags[3] if len(tags) >= 4 else None
person = tags[4] if len(tags) >= 5 else None
syntaxType = tags[5] if len(tags) >= 6 else None
if pos == 'M':
categoryOfNumeral = tags[0] if len(tags) >= 1 else None
gender = tags[1] if len(tags) >= 2 else None
number = tags[2] if len(tags) >= 3 else None
case = tags[3] if len(tags) >= 4 else None
formOfNumeral = tags[4] if len(tags) >= 5 else None
if pos == 'S':
typeOfAdposition = tags[0]
structureOfAdposition = tags[1]
case = tags[3] if len(tags) >= 4 else None
# if pos == 'C':
# if pos == 'H':
# if pos == 'I':
# if pos == 'Q':
if pos == 'X':
typeOfAnother = tags[0] if len(tags) > 0 else None
gramma = Gramma(
word,
lemma,
pos,
gender,
animacy,
number,
case,
aspect,
mood,
person,
poss,
reflex,
tense,
verbForm,
voice,
degree,
nameType,
trans,
invl,
additional,
fullForm,
nounType,
additionalCase,
aspectual,
categoryOfAdjective,
syntaxType,
categoryOfNumeral,
formOfNumeral,
typeOfAdposition,
structureOfAdposition,
typeOfAnother
)
sentence.append(gramma)
return sentences<file_sep>import collections
import os
from src.common.gramma import Gramma
class GIKRYSaver():
def save(self, filename, sentences):
with open(filename, 'w') as targetFile:
for sentence in sentences:
targetFile.write('BEGIN\n')
for gramma in sentence:
string = self.grammaToString(gramma)
targetFile.write("%s\n" % string)
targetFile.write('END\n')
def grammaToString(self, gramma: Gramma):
tags = []
tags.append(gramma.pos)
if gramma.pos == 'N':
tags.append(gramma.nounType)
tags.append(gramma.gender)
tags.append(gramma.number)
tags.append(gramma.case)
tags.append(gramma.additionalCase)
tags.append(gramma.animacy)
if gramma.pos == 'A':
tags.append(gramma.degree)
tags.append(gramma.gender)
tags.append(gramma.number)
tags.append(gramma.case)
tags.append(gramma.fullForm)
if gramma.pos == 'V':
if gramma.mood:
tags.append(gramma.mood)
else:
tags.append(gramma.verbForm)
tags.append(gramma.gender)
tags.append(gramma.number)
tags.append(gramma.case)
tags.append(gramma.person)
tags.append(gramma.tense)
tags.append(gramma.trans)
tags.append(gramma.voice)
tags.append(gramma.aspect)
tags.append(gramma.aspectual)
tags.append(gramma.fullForm)
if gramma.pos == 'R':
tags.append(gramma.degree)
# if gramma.pos == 'W':
if gramma.pos == 'P':
tags.append(gramma.categoryOfAdjective)
tags.append(gramma.gender)
tags.append(gramma.number)
tags.append(gramma.case)
tags.append(gramma.person)
tags.append(gramma.syntaxType)
if gramma.pos == 'M':
tags.append(gramma.categoryOfNumeral)
tags.append(gramma.gender)
tags.append(gramma.number)
tags.append(gramma.case)
tags.append(gramma.formOfNumeral)
if gramma.pos == 'S':
tags.append(gramma.typeOfAdposition)
tags.append(gramma.structureOfAdposition)
tags.append('-')
tags.append(gramma.case)
# if gramma.pos == 'C':
# if gramma.pos == 'H':
# if gramma.pos == 'I':
# if gramma.pos == 'Q':
if gramma.pos == 'X':
tags.append(gramma.typeOfAnother)
tags = ['-' if not tag else tag for tag in tags]
tags = self.clearEmptyTags(tags)
lemma = gramma.lemma if gramma.lemma else gramma.word
return "%s\t%s\t%s" % (gramma.word, lemma, ",".join(tags))
"""
Очищаем пустые теги в конце списка тегов. Пустые теги: "-"
"""
def clearEmptyTags(self, tags):
# ищем последний тег, который не пустой
normalIndex = -1
for index in range(len(tags)):
if tags[index] != '-':
normalIndex = index
if normalIndex >= 0:
return tags[0:normalIndex+1]
else:
return []
<file_sep>from src.training.trainer import Trainer
from src.common.loader import loadOCGrammasFromFile
from src.training.features_builder import FeaturesBuilder
import os
"""
Обучение всех моделей для всех признаков
"""
def train_all_models(filename):
# считываем строки из файла в формате OC и переводим в граммы
sentences = loadOCGrammasFromFile(filename)
# создаем тренера и загружаем грамемы (предложения) в него
predictors = [
'pos',
'gender',
'animacy',
'number',
'case',
'aspect',
'mood',
'person',
'poss',
'reflex',
'tense',
'verbForm',
'voice',
'degree',
'nameType',
'trans',
'invl',
'additional' # Дополнительные теги учим по одному
]
for predictor in predictors:
print("start to train %s" % predictor)
trainer = Trainer(verbose=True)
features_builder = FeaturesBuilder(predictor)
for sencence in sentences:
(features, results) = features_builder.make_features_and_results(sencence)
trainer.append(features, results)
print("trainer %s appended. Start to train" % predictor)
trainer.train(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'model', 'oc', "crf_%s.model" % predictor)
)
# отдельные теги быстро учатся, но плохо и долго работают. не учим отдельно
# additionalTags = [
# 'Infr',
# 'Slng',
# 'Arch',
# 'Litr',
# 'Erro',
# 'Dist',
# 'Ques',
# 'Dmns',
# 'Prnt',
# 'V-be',
# 'V-en',
# 'V-ie',
# 'V-bi',
# 'V-ey',
# 'V-oy',
# 'Coun',
# 'Af-p',
# 'Anph',
# 'Subx',
# 'Vpre',
# 'Prdx',
# 'Coll',
# 'Adjx',
# 'Qual',
# 'Apro',
# 'Anum',
# 'Poss',
# 'ms-f',
# 'Ms-f',
# 'Impe',
# 'Impx',
# 'Mult',
# 'Abbr',
# 'Fixd',
# ]
# for additionalTag in additionalTags:
# print("start to train additional tag %s" % additionalTag)
# trainer = Trainer()
# features_builder = FeaturesBuilder('additional', additionalTag)
# for sentence in sentences:
# (features, results) = features_builder.make_features_and_results(sentence)
# trainer.append(features, results)
# print("trainer additiona - %s appended. Start to train" % additionalTag)
# trainer.train(
# os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'model', 'oc', "crf_additional_%s.model" % additionalTag)
# )<file_sep>post = {
'NOUN',
'ADJF',
'ADJS',
'COMP',
'VERB',
'INFN',
'PRTF',
'PRTS',
'GRND',
'NUMR',
'ADVB',
'NPRO',
'PRED',
'PREP',
'CONJ',
'PRCL',
'INTJ',
}
anim = {
'anim',
'inan'
}
gndr = {
'masc',
'femn',
'neut',
'ms-f',
}
nmbr = {
'sing',
'plur',
}
case = {
'nomn',
'gent',
'datv',
'accs',
'ablt',
'loct',
'voct',
'gen1',
'gen2',
'acc2',
'loc1',
'loc2',
}
aspc = {
'perf',
'impf',
}
trns = {
'tran',
'intr',
}
pers = {
'1per',
'2per',
'3per',
}
tens = {
'pres',
'past',
'futr',
}
mood = {
'indc',
'impr',
}
invl = {
'incl',
'excl',
}
voic = {
'actv',
'pssv',
}<file_sep>from src.common.gramma import Gramma
from src.ud.predictor import UDPredictor
import sys
class GIKRY2UDConverter():
def __init__(self, use_prediction):
self.posPredictor = UDPredictor('pos')
self.numberPredictor = UDPredictor('number')
self.possPredictor = UDPredictor('poss')
self.reflexPredictor = UDPredictor('reflex')
self.moodPredictor = UDPredictor('mood')
self.verbFormPredictor = UDPredictor('verbForm')
self.nameTypePredictor = UDPredictor('nameType')
self.use_prediction = use_prediction
def convert(self, gikry_sentences):
ud_sentences = []
for index in range(len(gikry_sentences)):
sys.stdout.write("convery %s/%s\r" % (index, len(gikry_sentences)))
sys.stdout.flush()
gikry_sentence = gikry_sentences[index]
ud_sentence = []
for grammaIndex in range(len(gikry_sentence)):
gikry_gramma = gikry_sentence[grammaIndex]
ud_gramma = self.convertGramma(gikry_gramma, gikry_sentence, grammaIndex)
ud_sentence.append(ud_gramma)
ud_sentences.append(ud_sentence)
return ud_sentences
def convertGramma(self, gikry_gramma, sentence, grammaInSentenceIndex):
pos = 'X'
gender = None
animacy = None
number = None
case = None
aspect = None
mood = None
person = None
poss = None
reflex = None
tense = None
verbForm = None
voice = None
degree = None
nameType = None
trans = None
invl = None
additional = []
if gikry_gramma.pos == 'N':
pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['NOUN', 'PROPN'])
if gikry_gramma.pos == 'P':
pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['PRON', 'DET'])
if gikry_gramma.pos == 'A':
pos = 'ADJ'
if gikry_gramma.pos == 'M':
pos = 'NUM'
if gikry_gramma.pos == 'R':
pos = 'ADV'
if gikry_gramma.pos == 'W':
pos = 'ADV'
if gikry_gramma.pos == 'V':
pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['VERB', 'AUX'])
if gikry_gramma.pos == 'C':
pos = 'CONJ'
if gikry_gramma.pos == 'S':
pos = 'ADP'
if gikry_gramma.pos == 'I':
pos = 'INTJ'
if gikry_gramma.pos == 'H':
pos = 'X'
if gikry_gramma.pos == 'Q':
pos = "PART"
if gikry_gramma.pos == 'X':
pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['SYM', 'PUNCT', 'X'])
if gikry_gramma.gender == 'm':
gender = 'Gender=Masc'
elif gikry_gramma.gender == 'f':
gender = 'Gender=Fem'
elif gikry_gramma.gender == 'n':
gender = 'Gender=Neut'
if gikry_gramma.animacy == 'y':
animacy = 'Animacy=Anim'
if gikry_gramma.animacy == 'n':
animacy = 'Animacy=Inan'
if gikry_gramma.number == 's':
number = 'Number=Sing'
if gikry_gramma.number == 'p':
number = 'Number=Plur'
if gikry_gramma.number == 'i':
number = self.predict(self.numberPredictor, sentence, grammaInSentenceIndex, ['Number=Ptan', 'Number=Coll'])
if gikry_gramma.case == 'n' or gikry_gramma.case == 'v':
case = 'Case=Nom'
if gikry_gramma.case == 'g' or gikry_gramma.case == 'p':
case = 'Case=Gen'
if gikry_gramma.case == 'd':
case = 'Case=Dat'
if gikry_gramma.case == 'a':
case = 'Case=Acc'
if gikry_gramma.case == 'l':
case = 'Case=Loc'
if gikry_gramma.case == 'i':
case = 'Case=Ins'
if gikry_gramma.aspect == 'i':
aspect = 'Aspect=Imp'
if gikry_gramma.aspect == 'p':
aspect = 'Aspect=Perf'
if gikry_gramma.mood == 'i':
mood = self.predict(self.moodPredictor, sentence, grammaInSentenceIndex, ['Mood=Ind', 'Mood=Cnd'])
if gikry_gramma.mood == 'm':
mood = 'Mood=Imp'
if gikry_gramma.person == '1':
person = 'Person=1'
if gikry_gramma.person == '2':
person = 'Person=2'
if gikry_gramma.person == '3':
person = 'Person=3'
poss = self.predict(self.possPredictor, sentence, grammaInSentenceIndex, [None, 'Poss=Yes'])
poss = self.predict(self.reflexPredictor, sentence, grammaInSentenceIndex, [None, 'Reflex=Yes'])
if gikry_gramma.tense == 's':
tense = 'Tense=Past'
if gikry_gramma.tense == 'p':
tense = 'Tense=Pres'
if gikry_gramma.tense == 'f':
tense = 'Tense=Fut'
if gikry_gramma.verbForm == 'n':
verbForm = 'VerbForm=Inf'
elif gikry_gramma.verbForm == 'p':
verbForm = 'VerbForm=Part'
elif gikry_gramma.verbForm == 'g':
verbForm = 'VerbForm=Trans'
# else:
# verbForm = self.predict(self.verbFormPredictor, sentence, grammaInSentenceIndex, [None, 'VerbForm=Fin'])
if gikry_gramma.voice == 'a':
voice = 'Voice=Act'
if gikry_gramma.voice == 'p':
voice = 'Voice=Mid'
if gikry_gramma.voice == 's':
voice = 'Voice=Pass'
if gikry_gramma.degree == 'p':
degree = 'Degree=Pos'
if gikry_gramma.degree == 'c':
degree = 'Degree=Cmp'
if gikry_gramma.degree == 's':
degree = 'Degree=Sup'
nameType = self.predict(
self.nameTypePredictor,
sentence,
grammaInSentenceIndex,
[
None,
'NameType=Geo',
'NameType=Prs',
'NameType=Giv',
'NameType=Sur',
'NameType=Com',
'NameType=Pro',
'NameType=Oth',
]
)
gramma = Gramma(
gikry_gramma.word,
gikry_gramma.lemma,
pos,
gender,
animacy,
number,
case,
aspect,
mood,
person,
poss,
reflex,
tense,
verbForm,
voice,
degree,
nameType,
trans,
invl,
additional
)
return gramma
def predict(self, predictor, sentence, grammaInSentenceIndex, variants):
if not self.use_prediction:
return variants[0]
prediction = predictor.predict(sentence, grammaInSentenceIndex)
if not prediction or prediction not in variants:
return variants[0]
else:
return prediction
<file_sep>from src.common.gramma import Gramma
from src.nkry.predictor import NKRYPrecitor
import sys
class UD2NKRYConverter():
def __init__(self, use_prediction):
self.posPredictor = NKRYPrecitor('pos')
self.casePredictor = NKRYPrecitor('case')
self.moodPredictor = NKRYPrecitor('mood')
self.degreePredictor = NKRYPrecitor('degree')
self.nameTypePredictor = NKRYPrecitor('nameType')
self.transPredictor = NKRYPrecitor('trans')
self.fullFormPredictor = NKRYPrecitor('fullForm')
self.use_prediction = use_prediction
def convert(self, ud_sentences):
nkry_sentences = []
for index in range(len(ud_sentences)):
sys.stdout.write("convert %s/%s\r" % (index, len(ud_sentences)))
sys.stdout.flush()
ud_sentence = ud_sentences[index]
nkry_sentence = []
for grammaIndex in range(len(ud_sentence)):
ud_gramma = ud_sentence[grammaIndex]
nkry_gramma = self.convertGramma(ud_gramma, ud_sentence, grammaIndex)
nkry_sentence.append(nkry_gramma)
nkry_sentences.append(nkry_sentence)
return nkry_sentences
def convertGramma(self, ud_gramma, sentence, grammaInSentenceIndex):
pos = '-'
gender = None
animacy = None
number = None
case = None
aspect = None
mood = None
person = None
poss = None
reflex = None
tense = None
verbForm = None
voice = None
degree = None
nameType = None
trans = None
invl = None
additional = []
fullForm = None
if ud_gramma.gender == 'Gender=Masc': gender = 'm'
if ud_gramma.gender == 'Gender=Fem': gender = 'f'
if ud_gramma.gender == 'Gender=Neut': gender = 'n'
# todo - сделать угадывание пола m-f
if ud_gramma.animacy == 'Animacy=Anim': animacy = 'anim'
if ud_gramma.animacy == 'Animacy=Inan': animacy = 'inan'
if ud_gramma.number == 'Number=Sing': number = 'sg'
if ud_gramma.number == 'Number=Plur': number = 'pl'
if ud_gramma.number == 'Number=Ptan': number = 'pl'
if ud_gramma.number == 'Number=Coll': number = 'sg'
if ud_gramma.case == 'Case=Nom': case = self.predict(self.casePredictor, sentence, grammaInSentenceIndex, ['nom', 'voc'])
if ud_gramma.case == 'Case=Gen': case = self.predict(self.casePredictor, sentence, grammaInSentenceIndex, ['gen', 'gen2', 'adnum'])
if ud_gramma.case == 'Case=Dat': case = self.predict(self.casePredictor, sentence, grammaInSentenceIndex, ['dat', 'dat2'])
if ud_gramma.case == 'Case=Acc': case = self.predict(self.casePredictor, sentence, grammaInSentenceIndex, ['acc', 'acc2'])
if ud_gramma.case == 'Case=Loc': case = self.predict(self.casePredictor, sentence, grammaInSentenceIndex, ['loc', 'loc2'])
if ud_gramma.case == 'Case=Ins': case = 'ins'
fullForm = self.predict(self.fullFormPredictor, sentence, grammaInSentenceIndex, [None, 'brev', 'plen'])
if ud_gramma.aspect == 'Aspect=Imp': aspect = 'ipf'
if ud_gramma.aspect == 'Aspect=Perf': aspect = 'pf'
if ud_gramma.mood == 'Mood=Ind': mood = 'indic'
if ud_gramma.mood == 'Mood=Cnd': mood = 'indic'
if ud_gramma.mood == 'Mood=Imp': mood = 'imper'
# todo - сделать угадывание mood=imper2
if ud_gramma.person == 'Person=1': person = '1p'
if ud_gramma.person == 'Person=2': person = '2p'
if ud_gramma.person == 'Person=3': person = '3p'
if ud_gramma.tense == 'Tense=Past': tense = 'praet'
if ud_gramma.tense == 'Tense=Pres': tense = 'praes'
if ud_gramma.tense == 'Tense=Fut': tense = 'fut'
if ud_gramma.verbForm == 'VerbForm=Fin': verbForm = None
if ud_gramma.verbForm == 'VerbForm=Inf': verbForm = 'inf'
if ud_gramma.verbForm == 'VerbForm=Part': verbForm = 'partcp'
if ud_gramma.verbForm == 'VerbForm=Trans': verbForm = 'ger'
if ud_gramma.voice == 'Voice=Act': voice = 'act'
if ud_gramma.voice == 'Voice=Mid': voice = 'med'
if ud_gramma.voice == 'Voice=Pass': voice = 'pass'
if ud_gramma.degree == 'Degree=Pos': degree = None
if ud_gramma.degree == 'Degree=Cmp': degree = self.predict(self.degreePredictor, sentence, grammaInSentenceIndex, ['comp', 'comp2'])
if ud_gramma.degree == 'Degree=Sup': degree = 'supr'
if ud_gramma.nameType == 'NameType=Geo': nameType = None
if ud_gramma.nameType == 'NameType=Prs': nameType = 'patrn'
if ud_gramma.nameType == 'NameType=Giv': nameType = self.predict(self.nameTypePredictor, sentence, grammaInSentenceIndex, ['zoon', 'persn'])
if ud_gramma.nameType == 'NameType=Sur': nameType = 'famn'
if ud_gramma.nameType == 'NameType=Com': nameType = None
if ud_gramma.nameType == 'NameType=Pro': nameType = None
if ud_gramma.nameType == 'NameType=Oth': nameType = None
trans = self.predict(self.transPredictor, sentence, grammaInSentenceIndex, [None, 'tran', 'intr'])
if ud_gramma.pos == 'NOUN': pos = 'S'
if ud_gramma.pos == 'PROPN': pos = 'S'
if ud_gramma.pos == 'PRON': pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['SPRO', 'PREADICPRO'])
if ud_gramma.pos == 'DET': pos = 'APRO'
if ud_gramma.pos == 'ADJ': pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['A', 'ANUM'])
if ud_gramma.pos == 'NUM': pos = 'NUM'
if ud_gramma.pos == 'CONJ':
if ud_gramma.word == 'где' or ud_gramma.word == 'вот':
pos = 'ADVPRO'
else:
pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['CONJ', 'ADVPRO', 'PARENTH'])
if ud_gramma.pos == 'ADV': pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['ADV', 'PRAEDIC'])
if ud_gramma.pos == 'PART': pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['PART', 'ADVPRO'])
if ud_gramma.pos == 'ADP': pos = 'PR'
if ud_gramma.pos == 'AUX': pos = 'V'
if ud_gramma.pos == 'VERB': pos = 'V'
if ud_gramma.pos == 'INTJ': pos = 'INTJ'
if ud_gramma.pos == 'PART': pos = 'PART'
if ud_gramma.pos == 'SYM': pos = '-'
if ud_gramma.pos == 'PUNCT': pos = '-'
if ud_gramma.pos == 'X': pos = '-'
gramma = Gramma(
ud_gramma.word,
ud_gramma.lemma,
pos,
gender,
animacy,
number,
case,
aspect,
mood,
person,
poss,
reflex,
tense,
verbForm,
voice,
degree,
nameType,
trans,
invl,
additional,
fullForm
)
return gramma
def predict(self, predictor, sentence, grammaInSentenceIndex, variants, debug=False):
if not self.use_prediction:
return variants[0]
prediction = predictor.predict(sentence, grammaInSentenceIndex)
if debug == True:
print("Prediction is: %s" % prediction)
if not prediction or prediction not in variants:
return variants[0]
else:
return prediction<file_sep>import sys
from lxml import etree
def parse_nkry(filename):
print("Start to parse file %s" % filename)
nkryFile = open(filename)
text = nkryFile.read()
text = text.replace('encoding="windows-1251"', '')
tree = etree.fromstring(text)
print("Finish parse file %s" % filename)
lines = []
pIndex = 1
for sentence in tree.iter('se'):
sys.stdout.write("sentence num: %s \r" % pIndex)
sys.stdout.flush()
pIndex += 1
lines.append("BEGIN")
for wordTag in sentence.iter('w'):
word = None
lemma=None
tags=None
for ana in wordTag.iter('ana'):
# ana = word.find('ana')
if ana.tail:
word = ana.tail
if not word:
continue
word = word.replace('`', '')
lemma = ana.get('lex')
tags = ana.get('gr')
if not word or not lemma or not tags:
continue
lines.append("%s\t%s\t%s" % (word.strip(), lemma.strip(), tags.strip().replace('=', ',').replace('-', '')))
lines.append("END")
print()
return "\n".join(lines)<file_sep>import collections
import os
TAGS_ORDER = [
'-',
's',
'spro',
'praedicpro',
'apro',
'a',
'anum',
'num',
'advpro',
'adv',
'praedic',
'parenth',
'v',
'conj',
'pr',
'intj',
'part',
'nonlex',
'init',
'm',
'f',
'n',
'm-f',
'anim',
'inan',
'sg',
'pl',
'nom',
'voc',
'gen',
'gen2',
'adnum',
'dat',
'dat2',
'acc',
'acc2',
'loc',
'loc2',
'ins',
'brev',
'plen',
'ipf',
'pf',
'indic',
'imper',
'imper2',
'1p',
'2p',
'3p',
'praet',
'praes',
'fut',
'inf',
'partcp',
'ger',
'act',
'med',
'pass',
'comp',
'comp2',
'supr',
'patrn',
'zoon',
'persn',
'famn',
'tran',
'intr',
]
class NKRYSaver():
def save(self, filename, sentences):
with open(filename, 'w') as targetFile:
for sentence in sentences:
targetFile.write("BEGIN\n")
for gramma in sentence:
string = self.grammaToString(gramma)
targetFile.write(string)
targetFile.write("ENDN\n")
def grammaToString(self, gramma):
tags = []
tags.append(gramma.pos)
if gramma.gender != None: tags.append(gramma.gender)
if gramma.animacy != None: tags.append(gramma.animacy)
if gramma.number != None: tags.append(gramma.number)
if gramma.case != None: tags.append(gramma.case)
if gramma.aspect != None: tags.append(gramma.aspect)
if gramma.mood != None: tags.append(gramma.mood)
if gramma.person != None: tags.append(gramma.person)
if gramma.poss != None: tags.append(gramma.poss)
if gramma.reflex != None: tags.append(gramma.reflex)
if gramma.tense != None: tags.append(gramma.tense)
if gramma.verbForm != None: tags.append(gramma.verbForm)
if gramma.voice != None: tags.append(gramma.voice)
if gramma.degree != None: tags.append(gramma.degree)
if gramma.nameType != None: tags.append(gramma.nameType)
if gramma.trans != None: tags.append(gramma.trans)
if gramma.invl != None: tags.append(gramma.invl)
tags = self.sortTags(tags)
return "%s\t%s\t%s\n" % (gramma.word, gramma.lemma, ",".join(tags))
def sortTags(self, tags):
tagsDict = {}
for tag in tags:
if not tag:
continue
index = TAGS_ORDER.index(tag.lower())
tagsDict[index] = tag
tagsDict = collections.OrderedDict(sorted(tagsDict.items()))
sortedTags = []
for key, value in tagsDict.items():
sortedTags.append(value)
return sortedTags
<file_sep>from src.common.gramma import Gramma
from src.ud.predictor import UDPredictor
import sys
class OC2UDConverter():
def __init__(self, use_prediction):
self.posPredictor = UDPredictor('pos')
self.moodPredictor = UDPredictor('mood')
self.voicePredictor = UDPredictor('voice')
self.nameTypePredictor = UDPredictor('nameType')
self.possPredictor = UDPredictor('poss')
self.reflexPredictor = UDPredictor('reflex')
self.degreePredictor = UDPredictor('degree')
self.use_prediction = use_prediction
def convert(self, oc_sentences):
ud_sentences = []
for sentence_index in range(len(oc_sentences)):
oc_sentence = oc_sentences[sentence_index]
sys.stdout.write("convert %s/%s\r" % (sentence_index, len(oc_sentences)))
sys.stdout.flush()
ud_sentence = []
for index in range(len(oc_sentence)):
oc_gramma = oc_sentence[index]
ud_gramma = self.convertGramma(oc_gramma, oc_sentence, index)
ud_sentence.append(ud_gramma)
ud_sentences.append(ud_sentence)
return ud_sentences
def convertGramma(self, oc_gramma, sentence, grammaInSentenceIndex):
pos = 'X'
gender = None
animacy = None
number = None
case = None
aspect = None
mood = None
person = None
poss = None
reflex = None
tense = None
verbForm = None
voice = None
degree = None
nameType = None
trans = None
invl = None
additional = []
# Ошибок больше, чем через модель
# if oc_gramma.pos == 'NOUN': pos = 'NOUN'
# if oc_gramma.pos == 'NOUN' and (
# oc_gramma.nameType == 'Name' or
# oc_gramma.nameType == 'Surn' or
# oc_gramma.nameType == 'Patr' or
# oc_gramma.nameType == 'Geox' or
# oc_gramma.nameType == 'Orgn' or
# oc_gramma.nameType == 'Trad' or
# oc_gramma.nameType == 'Init'): pos = 'PROPN'
if oc_gramma.pos == 'NOUN': pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['NOUN', 'PROPN'])
if oc_gramma.pos == 'NPRO': pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['PRON', 'DET'])
if oc_gramma.pos == 'ADJF': pos = 'ADJ'
if oc_gramma.pos == 'ADJS': pos = 'ADJ'
if oc_gramma.pos == 'COMP': pos = 'ADJ'
if oc_gramma.pos == 'NUMR': pos = 'NUM'
if oc_gramma.pos == 'ADVB': pos = 'ADV'
if oc_gramma.pos == 'PRED': pos = 'ADV'
if oc_gramma.pos == 'VERB': pos = 'VERB'
if oc_gramma.pos == 'INFN':
verbForm = 'VerbForm=Inf'
pos = 'VERB'
if oc_gramma.pos == 'PRTF':
verbForm = 'VerbForm=Part'
pos = 'VERB'
if oc_gramma.pos == 'PRTS':
verbForm = 'VerbForm=Part'
pos = 'VERB'
if oc_gramma.pos == 'GRND':
verbForm = 'VerbForm=Trans'
pos = 'VERB'
if oc_gramma.pos == 'CONJ': pos = 'CONJ'
if oc_gramma.pos == 'PREP': pos = 'ADP'
if oc_gramma.pos == 'INTJ': pos = 'INTJ'
if oc_gramma.pos == 'PRCL': pos = 'PART'
if oc_gramma.pos == 'PNCT': pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['PUNCT', 'SYM'])
if oc_gramma.pos == 'LATN': pos = 'X'
if oc_gramma.pos == 'NUMB': pos = 'X'
if oc_gramma.pos == 'ROMN': pos = 'X'
if oc_gramma.pos == 'UNKN': pos = 'X'
if oc_gramma.gender == 'masc': gender = 'Gender=Masc'
if oc_gramma.gender == 'femn': gender = 'Gender=Fem'
if oc_gramma.gender == 'neut': gender = 'Gender=Neut'
if oc_gramma.animacy == 'anim': animacy = 'Animacy=Anim'
if oc_gramma.animacy == 'inan': animacy = 'Animacy=Inan'
if oc_gramma.number == 'sing': number = 'Number=Sing'
if oc_gramma.number == 'plur': number = 'Number=Plur'
if oc_gramma.number == 'Pltm': number = 'Number=Ptan'
if oc_gramma.number == 'Sgtm': number = 'Number=Coll'
if oc_gramma.case == 'nomn' or oc_gramma.case == 'voct': case = 'Case=Nom'
if oc_gramma.case == 'gent' or oc_gramma.case =='gen1' or oc_gramma.case =='gen2': case = 'Case=Gen'
if oc_gramma.case == 'datv': case = 'Case=Dat'
if oc_gramma.case == 'accs' or oc_gramma.case =='acc2': case = 'Case=Acc'
if oc_gramma.case == 'loct' or oc_gramma.case =='loc1' or oc_gramma.case =='loc2': case = 'Case=Loc'
if oc_gramma.case == 'ablt': case = 'Case=Ins'
if oc_gramma.aspect == 'impf': aspect = 'Aspect=Imp'
if oc_gramma.aspect == 'perf': aspect = 'Aspect=Perf'
if oc_gramma.verbForm == 'INFN':
verbForm = 'VerbForm=Inf'
if oc_gramma.verbForm == 'PRTF':
verbForm = 'VerbForm=Part'
if oc_gramma.verbForm == 'PRTS':
verbForm = 'VerbForm=Part'
if oc_gramma.verbForm == 'GRND':
verbForm = 'VerbForm=Trans'
# попробовать модель для остальных случаев
if oc_gramma.mood == 'indc':
verbForm = 'VerbForm=Fin'
mood = self.predict(self.moodPredictor, sentence, grammaInSentenceIndex, ['Mood=Ind', 'Mood=Cnd'])
if oc_gramma.mood == 'impr':
verbForm = 'VerbForm=Fin'
mood = 'Mood=Imp'
if oc_gramma.person == '1per': person = 'Person=1'
if oc_gramma.person == '2per': person = 'Person=2'
if oc_gramma.person == '3per': person = 'Person=3'
if oc_gramma.tense == 'past': tense = 'Tense=Past'
if oc_gramma.tense == 'pres': tense = 'Tense=Pres'
if oc_gramma.tense == 'futr': tense = 'Tense=Fut'
if oc_gramma.voice == 'actv': voice = self.predict(self.voicePredictor, sentence, grammaInSentenceIndex, ['Voice=Act', 'Voice=Mid'])
if oc_gramma.voice == 'pssv': voice = 'Voice=Pass'
if oc_gramma.nameType == 'Geox': nameType = 'NameType=Geo'
if oc_gramma.nameType == 'Patr': nameType = 'NameType=Prs'
if oc_gramma.nameType == 'Name': nameType = self.predict(self.nameTypePredictor, sentence, grammaInSentenceIndex, ['NameType=Prs', 'NameType=Giv'])
if oc_gramma.nameType == 'Surn': nameType = 'NameType=Sur'
if oc_gramma.nameType == 'Orgn': nameType = 'NameType=Com'
if oc_gramma.nameType == 'Trad': nameType = 'NameType=Pro'
if oc_gramma.nameType == 'Init': nameType = 'NameType=Oth'
degree = self.predict(self.degreePredictor, sentence, grammaInSentenceIndex, [None, 'Degree=Pos', 'Degree=Cmp', 'Degree=Sup'])
poss = self.predict(self.possPredictor, sentence, grammaInSentenceIndex, [None, 'Poss=Yes'])
reflex = self.predict(self.reflexPredictor, sentence, grammaInSentenceIndex, [None, 'Reflex=Yes'])
gramma = Gramma(
oc_gramma.word,
oc_gramma.lemma,
pos,
gender,
animacy,
number,
case,
aspect,
mood,
person,
poss,
reflex,
tense,
verbForm,
voice,
degree,
nameType,
trans,
invl,
additional
)
return gramma
def predict(self, predictor, sentence, grammaInSentenceIndex, variants):
if not self.use_prediction:
return variants[0]
prediction = predictor.predict(sentence, grammaInSentenceIndex)
if not prediction or prediction not in variants:
return variants[0]
else:
return prediction<file_sep>class Gramma():
def __init__(
self,
word,
lemma,
pos,
gender,
animacy,
number,
case,
aspect,
mood,
person,
poss,
reflex,
tense,
verbForm,
voice,
degree,
nameType,
trans,
invl,
additional,
fullForm = None,
nounType = None,
additionalCase = None,
aspectual = None,
categoryOfAdjective = None,
syntaxType = None,
categoryOfNumeral = None,
formOfNumeral = None,
typeOfAdposition = None,
structureOfAdposition = None,
typeOfAnother = None
):
self.word = word
self.lemma = lemma
self.pos = pos
self.gender = gender
self.animacy = animacy
self.number = number
self.case = case
self.aspect = aspect
self.mood = mood
self.person = person
self.poss = poss
self.reflex = reflex
self.tense = tense
self.verbForm = verbForm
self.voice = voice
self.degree = degree
self.nameType = nameType
self.trans = trans
self.invl = invl
self.additional = additional
self.fullForm = fullForm
self.nounType = nounType
self.additionalCase = additionalCase
self.aspectual = aspectual
self.categoryOfAdjective = categoryOfAdjective
self.syntaxType = syntaxType
self.categoryOfNumeral = categoryOfNumeral
self.formOfNumeral = formOfNumeral
self.typeOfAdposition = typeOfAdposition
self.structureOfAdposition = structureOfAdposition
self.typeOfAnother = typeOfAnother<file_sep>import pycrfsuite
from src.training.features_builder import FeaturesBuilder
import os
class OCPrecitor():
def __init__(self, tagType, additionalTag = None):
self.tagType = tagType
self.tagger = pycrfsuite.Tagger()
if False and tagType == 'additional':
self.tagger.open(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'model', 'oc', "crf_additional_%s.model" % additionalTag)
)
else:
self.tagger.open(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'model', 'oc', "crf_%s.model" % tagType)
)
self.featuresBuilder = FeaturesBuilder(tagType, additionalTag)
def predict(self, sentence, index):
(features, _) = self.featuresBuilder.make_features_and_results(sentence)
results = self.tagger.tag(features)
return results[index]<file_sep>from src.common.gramma import Gramma
from src.ud.predictor import UDPredictor
import sys
class NKRY2UDConverter():
def __init__(self, use_prediction):
self.posPredictor = UDPredictor('pos')
self.moodPredictor = UDPredictor('mood')
self.voicePredictor = UDPredictor('voice')
self.nameTypePredictor = UDPredictor('nameType')
self.possPredictor = UDPredictor('poss')
self.reflexPredictor = UDPredictor('reflex')
self.degreePredictor = UDPredictor('degree')
self.genderPredictor = UDPredictor('gender')
self.casePredictor = UDPredictor('case')
self.verbFormPredictor = UDPredictor('verbForm')
self.numberPredictor = UDPredictor('number')
self.use_prediction = use_prediction
def convert(self, nkry_sentences):
ud_sentences = []
for index in range(len(nkry_sentences)):
sys.stdout.write("convert %s/%s\r" % (index, len(nkry_sentences)))
sys.stdout.flush()
nkry_sentence = nkry_sentences[index]
ud_sentence = []
for grammaIndex in range(len(nkry_sentence)):
nkry_gramma = nkry_sentence[grammaIndex]
ud_gramma = self.convertGramma(nkry_gramma, nkry_sentence, grammaIndex)
ud_sentence.append(ud_gramma)
ud_sentences.append(ud_sentence)
return ud_sentences
def convertGramma(self, nkry_gramma, sentence, grammaInSentenceIndex):
pos = 'X'
gender = None
animacy = None
number = None
case = None
aspect = None
mood = None
person = None
poss = None
reflex = None
tense = None
verbForm = None
voice = None
degree = None
nameType = None
trans = None
invl = None
additional = []
if nkry_gramma.pos == 'S': pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['NOUN', 'PROPN'])
elif nkry_gramma.pos == 'SPRO' or nkry_gramma.pos == 'PRAEDICPRO': pos = 'PRON'
elif nkry_gramma.pos == 'APRO': pos = 'DET'
elif nkry_gramma.pos == 'A' or nkry_gramma.pos == 'ANUM': pos = 'ADJ'
elif nkry_gramma.pos == 'NUM': pos = 'NUM'
elif nkry_gramma.pos == 'ADVPRO' and nkry_gramma.word == 'где': pos = 'CONJ'
elif nkry_gramma.pos == 'ADVPRO' and nkry_gramma.word == 'вот': pos = 'PART'
elif nkry_gramma.pos == 'ADV' or nkry_gramma.pos == 'PRAEDIC': pos = 'ADV'
elif nkry_gramma.pos == 'PARENTH' and nkry_gramma.word == 'кстати': pos = 'CONJ'
elif nkry_gramma.pos == 'PARENTH' and nkry_gramma.word == 'по-моему': pos = 'ADP'
elif nkry_gramma.pos == 'V': pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['VERB', 'V'])
elif nkry_gramma.pos == 'CONJ': pos = 'CONJ'
elif nkry_gramma.pos == 'PR': pos = 'ADP'
elif nkry_gramma.pos == 'INTJ': pos = 'INTJ'
elif nkry_gramma.pos == 'PART': pos = 'PART'
else: pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['SYM', 'PUNCT', 'X'])
if nkry_gramma.gender == 'm': gender = 'Gender=Masc'
if nkry_gramma.gender == 'f': gender = 'Gender=Fem'
if nkry_gramma.gender == 'n': gender = 'Gender=Neut'
if nkry_gramma.gender == 'm-f': gender = self.predict(self.genderPredictor, sentence, grammaInSentenceIndex, [None, 'Gender=Masc', 'Gender=Fem', 'Gender=Neut'])
if nkry_gramma.animacy == 'anim': animacy = 'Animacy=Anim'
if nkry_gramma.animacy == 'inan': animacy = 'Animacy=Inan'
if nkry_gramma.number == 'sg': number = self.predict(self.numberPredictor, sentence, grammaInSentenceIndex, ['Number=Sing', 'Number=Coll'])
if nkry_gramma.number == 'pl': number = self.predict(self.numberPredictor, sentence, grammaInSentenceIndex, ['Number=Plur', 'Number=Ptan'])
if nkry_gramma.case == 'nom' or nkry_gramma.case == 'voc': case = "Case=Nom"
if nkry_gramma.case == 'gen' or nkry_gramma.case == 'gen2' or nkry_gramma.case == 'adnum': case = "Case=Gen"
if nkry_gramma.case == 'dat' or nkry_gramma.case == 'dat2': case = "Case=Dat"
if nkry_gramma.case == 'acc' or nkry_gramma.case == 'acc2': case = "Case=Acc"
if nkry_gramma.case == 'loc' or nkry_gramma.case == 'loc2': case = "Case=Loc"
if nkry_gramma.case == 'ins': case = "Case=Ins"
if nkry_gramma.case == 'brev' or nkry_gramma.case == 'plen':
case = self.predict(self.casePredictor, sentence, grammaInSentenceIndex, [
'Case=Nom',
'Case=Gen',
'Case=Dat',
'Case=Acc',
'Case=Loc',
'Case=Ins',
])
if nkry_gramma.aspect == 'ipf': aspect = 'Aspect=Imp'
if nkry_gramma.aspect == 'pf': aspect = 'Aspect=Perf'
if nkry_gramma.mood == 'indic': mood = self.predict(self.moodPredictor, sentence, grammaInSentenceIndex, ['Mood=Ind', 'Mood=Cnd'])
if nkry_gramma.mood == 'imper': mood = 'Mood=Imp'
if nkry_gramma.mood == 'imper2': mood = self.predict(self.moodPredictor, sentence, grammaInSentenceIndex, [None, 'Mood=Ind', 'Mood=Cnd', 'Mood=Imp'])
if nkry_gramma.person == '1p': person = "Person=1"
if nkry_gramma.person == '2p': person = "Person=2"
if nkry_gramma.person == '3p': person = "Person=3"
poss = self.predict(self.possPredictor, sentence, grammaInSentenceIndex, [None, 'Poss=Yes'])
reflex = self.predict(self.reflexPredictor, sentence, grammaInSentenceIndex, [None, 'Reflex=Yes'])
if nkry_gramma.tense == 'praet': tense = "Tense=Past"
if nkry_gramma.tense == 'praes': tense = "Tense=Pres"
if nkry_gramma.tense == 'fut': tense = "Tense=Fut"
if nkry_gramma.verbForm == 'inf': verbForm = "VerbForm=Inf"
elif nkry_gramma.verbForm == 'partcp': verbForm = "VerbForm=Part"
elif nkry_gramma.verbForm == 'ger': verbForm = "VerbForm=Trans"
else: verbForm = self.predict(self.verbFormPredictor, sentence, grammaInSentenceIndex, [None, 'VerbForm=Fin'])
if nkry_gramma.voice == 'act': voice = 'Voice=Act'
if nkry_gramma.voice == 'med': voice = 'Voice=Mid'
if nkry_gramma.voice == 'pass': voice = 'Voice=Pass'
if nkry_gramma.degree == 'comp' or nkry_gramma.degree == 'comp2': degree = "Degree=Cmp"
elif nkry_gramma.degree == 'supr': degree = "Degree=Sup"
else: degree = self.predict(self.degreePredictor, sentence, grammaInSentenceIndex, [None, 'Degree=Pos'])
if nkry_gramma.nameType == 'patrn': nameType = 'NameType=Prs'
elif nkry_gramma.nameType == 'zoon' or nkry_gramma.nameType == 'persn': nameType = 'NameType=Giv'
elif nkry_gramma.nameType == 'famn': nameType = 'NameType=Sur'
else: nameType = self.predict(self.nameTypePredictor, sentence, grammaInSentenceIndex, [
None,
'NameType=Geo'
'NameType=Com'
'NameType=Pro'
'NameType=Oth'
])
gramma = Gramma(
nkry_gramma.word,
nkry_gramma.lemma,
pos,
gender,
animacy,
number,
case,
aspect,
mood,
person,
poss,
reflex,
tense,
verbForm,
voice,
degree,
nameType,
trans,
invl,
additional
)
return gramma
def predict(self, predictor, sentence, grammaInSentenceIndex, variants):
if not self.use_prediction:
return variants[0]
prediction = predictor.predict(sentence, grammaInSentenceIndex)
if not prediction or prediction not in variants:
return variants[0]
else:
return prediction<file_sep>from sklearn.model_selection import train_test_split
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, LSTM, InputLayer, Bidirectional, TimeDistributed, Embedding, Activation
from keras.optimizers import Adam
import numpy as np
import os
import json
class ClassifierTrainer():
def __init__(self, sentences, tag):
self.tag = tag
(self.sentences, self.sentences_tags) = self.buildSentencesAndTags(sentences)
self.word2Index = {}
self.tag2Index = {}
self.buildIndexes()
self.MAX_LENGTH = 0
def buildSentencesAndTags(self, grammasSentences):
sentences = []
sentences_tags = []
for grammaSentence in grammasSentences:
sentence = []
tags = []
for gramma in grammaSentence:
sentence.append(gramma.word.lower())
tagValue = getattr(gramma, self.tag)
if isinstance(tagValue, list):
tagValue = ",".join(tagValue)
tags.append(tagValue)
sentences.append(sentence)
sentences_tags.append(tags)
return sentences, sentences_tags
def buildIndexes(self):
words, tags = set([]), set([])
for sentence in self.sentences:
for word in sentence:
words.add(word)
self.word2Index = {w: i + 2 for i, w in enumerate(list(words))}
self.word2Index['-PAD-'] = 0
self.word2Index['-OOV-'] = 1
for sentenceTags in self.sentences_tags:
for tag in sentenceTags:
tags.add(tag)
self.tag2Index = {t: i + 1 for i, t in enumerate(list(tags))}
self.tag2Index['-PAD-'] = 0
def prepareSequences(self):
(train_sentences, test_sentences, train_tags, test_tags) = train_test_split(self.sentences, self.sentences_tags, test_size=0.2)
train_sentences_X, test_sentences_X, train_tags_y, test_tags_y = [], [], [], []
for s in train_sentences:
s_int = []
for word in s:
try:
s_int.append(self.word2Index[word])
except KeyError:
# слова нет в индексе
s_int.append(self.word2Index['-OOV-'])
train_sentences_X.append(s_int)
for s in test_sentences:
s_int = []
for word in s:
try:
s_int.append(self.word2Index[word])
except KeyError:
# слова нет в индексе
s_int.append(self.word2Index['-OOV-'])
test_sentences_X.append(s_int)
for s in train_tags:
train_tags_y.append([self.tag2Index[t] for t in s])
for s in test_tags:
test_tags_y.append([self.tag2Index[t] for t in s])
self.MAX_LENGTH = len(max(train_sentences_X, key=len))
train_sentences_X = pad_sequences(train_sentences_X, maxlen=self.MAX_LENGTH, padding='post')
test_sentences_X = pad_sequences(test_sentences_X, maxlen=self.MAX_LENGTH, padding='post')
train_tags_y = pad_sequences(train_tags_y, maxlen=self.MAX_LENGTH, padding='post')
test_tags_y = pad_sequences(test_tags_y, maxlen=self.MAX_LENGTH, padding='post')
return train_sentences_X,test_sentences_X,train_tags_y,test_tags_y
def train(self, modelSavePath):
(train_sentences_X,test_sentences_X,train_tags_y,test_tags_y) = self.prepareSequences()
model = Sequential()
model.add(InputLayer(input_shape=(self.MAX_LENGTH, )))
model.add(Embedding(len(self.word2Index), 128))
model.add(Bidirectional(LSTM(256, return_sequences=True)))
model.add(TimeDistributed(Dense(len(self.tag2Index))))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer=Adam(0.001), metrics=['accuracy'])
#model.summary()
cat_train_tags_y = self.toCategorical(train_tags_y, len(self.tag2Index))
# print(cat_train_tags_y)
# quit()
model.fit(train_sentences_X, cat_train_tags_y, batch_size=128, epochs=1, validation_split=0.2)
scores = model.evaluate(test_sentences_X, self.toCategorical(test_tags_y, len(self.tag2Index)))
print(f"{model.metrics_names[1]}: {scores[1] * 100}") # acc: 99.09751977804825
if not os.path.exists(modelSavePath):
os.makedirs(modelSavePath)
model.save(modelSavePath + '/model.h5')
with open(modelSavePath + '/tag2Index.json', 'w') as outfile:
json.dump(self.tag2Index, outfile)
with open(modelSavePath + '/word2Index.json', 'w') as outfile:
json.dump(self.word2Index, outfile)
with open(modelSavePath + '/maxLength.json', 'w') as outfile:
json.dump(self.MAX_LENGTH, outfile)
def toCategorical(self, sequences, categories):
cat_sequences = []
for s in sequences:
cats = []
for item in s:
cats.append(np.zeros(categories))
cats[-1][item] = 1.0
cat_sequences.append(cats)
return np.array(cat_sequences)
<file_sep>class FeaturesBuilder():
def __init__(self, param, additionalTag = None):
self.param = param
self.additionalTag = additionalTag
def make_features_and_results(self, sentence):
featuresList = []
resultsList = []
for index in range(len(sentence)):
gramma = sentence[index]
features = {
'word': gramma.word,
}
if len(gramma.word) > 3:
features['word_ending'] = gramma.word[-3:]
if index > 0:
prevGramma = sentence[index-1]
features['prev_word'] = prevGramma.word
else:
features['BEGIN'] = True
if index < len(sentence) - 1:
nextGramma = sentence[index+1]
features['next_word'] = nextGramma.word
else:
features['END'] = True
featuresList.append(features)
if self.param == 'additional' and self.additionalTag:
additionalTagsInGramma = gramma.additional
if self.additionalTag in additionalTagsInGramma:
result = self.additionalTag
else:
result = None
else:
result = getattr(gramma, self.param)
if isinstance(result, list):
result = ",".join(result)
resultsList.append(result if result != None else "")
return featuresList, resultsList<file_sep>from src.training.trainer import Trainer
from src.training.features_builder import FeaturesBuilder
from src.common.loader import loadGIKRYGrammasFromFile
import os
"""
Нужны модели для признаков:
часть речи
пол
падеж
тип существительного
форма прилагательного
аспект
парность
время
форма глагола
форма причастия
переходность
разряд прилагательного
синтаксический тип прилагательного
признак части речи X
тип предлога
структура предлога
разряд числительного
форма записи числительного
разряд местоимения
синтаксический тип местоимения
"""
def train_all_models(filename):
sentences = loadGIKRYGrammasFromFile(filename)
predictors = [
'pos',
'gender',
'case',
'nounType',
'fullForm',
'aspect',
'aspectual',
'tense',
'verbForm',
'trans',
'categoryOfAdjective',
'syntaxType',
'typeOfAnother',
'typeOfAdposition',
'structureOfAdposition',
'categoryOfNumeral',
'formOfNumeral',
]
for predictor in predictors:
print("start to train %s predictor" % predictor)
trainer = Trainer(verbose=True)
features_builder = FeaturesBuilder(predictor)
for sentence in sentences:
(features, results) = features_builder.make_features_and_results(sentence)
trainer.append(features, results)
print("trainer %s appended. Start to train" % predictor)
trainer.train(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'model', 'gikry', "crf_%s.model" % predictor)
)<file_sep>from keras.models import Sequential
from keras.layers import Dense, LSTM, InputLayer, Bidirectional, TimeDistributed, Embedding, Activation
from keras.optimizers import Adam
from keras.preprocessing.sequence import pad_sequences
import numpy as np
import json
class NnPredictor():
def __init__(self, markupName, tag):
self.markupName = markupName
self.tag = tag
with open('model/%s/classifier/%s/maxLength.json' % (self.markupName, self.tag), 'r') as maxLengthFile:
self.MAX_LENGTH = json.load(maxLengthFile)
with open('model/%s/classifier/%s/tag2Index.json' % (self.markupName, self.tag), 'r') as tag2IndexFile:
self.tag2Index = json.load(tag2IndexFile)
with open('model/%s/classifier/%s/word2Index.json' % (self.markupName, self.tag), 'r') as word2IndexFile:
self.word2Index = json.load(word2IndexFile)
model = Sequential()
model.add(InputLayer(input_shape=(self.MAX_LENGTH, )))
model.add(Embedding(len(self.word2Index), 128))
model.add(Bidirectional(LSTM(256, return_sequences=True)))
model.add(TimeDistributed(Dense(len(self.tag2Index))))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer=Adam(0.001), metrics=['accuracy'])
model.load_weights("model/%s/classifier/%s/model.h5" % (self.markupName, self.tag))
self.model = model
def predict(self, sentences):
sequences = self.prepareFeatures(sentences)
print("Start prediction")
predictions = self.model.predict(sequences, batch_size=256, verbose=True)
print("Finish prediction")
index = {i: t for t, i in self.tag2Index.items()}
tokens = self.logitsToTokens(predictions, index)
return tokens
def prepareFeatures(self, sentences):
sequences = []
for sentence in sentences:
s_int = []
for gramma in sentence:
word = gramma.word
try:
s_int.append(self.word2Index[word])
except KeyError:
s_int.append(self.word2Index['-OOV-'])
words = [g.word for g in sentence]
sequences.append(s_int)
sequences = pad_sequences(sequences, maxlen=self.MAX_LENGTH, padding='post')
return sequences
def logitsToTokens(self, sequences, index):
token_sequences = []
for categorical_sequence in sequences:
token_sequence = []
for categorical in categorical_sequence:
token_sequence.append(index[np.argmax(categorical)])
token_sequences.append(token_sequence)
return token_sequences
<file_sep>from src.common.gramma import Gramma
import operator
class GrammaDiffer():
def __init__(self):
self.tags = [
'pos',
'gender',
'animacy',
'number',
'case',
'aspect',
'mood',
'person',
'poss',
'reflex',
'tense',
'verbForm',
'voice',
'degree',
'nameType',
'trans',
'invl',
'additional',
'fullForm',
'nounType',
'additionalCase',
'aspectual',
'categoryOfAdjective',
'syntaxType',
'categoryOfNumeral',
'formOfNumeral',
'typeOfAdposition',
'structureOfAdposition',
'typeOfAnother',
]
self.errors = {}
self.errorsCount = 0
self.totalCount = 0
def registerPair(self, originalGramma: Gramma, reconvertedGramma: Gramma):
for tag in self.tags:
originalAttr = getattr(originalGramma, tag)
if originalAttr == '-':
originalAttr = None
reconvertedAttr = getattr(reconvertedGramma, tag)
if reconvertedAttr == '-':
reconvertedAttr = None
if (originalAttr != reconvertedAttr ):
# print("%s: %s. %s -> %s" % (originalGramma.pos, tag, originalAttr, reconvertedAttr))
if not tag in self.errors:
self.errors[tag] = 0
self.errors[tag] += 1
self.errorsCount += 1
self.totalCount += 1
def dumpResult(self):
sorted_d = sorted(self.errors.items(), key=operator.itemgetter(1))
for (error, num) in sorted_d:
print("Error in tag %s, errors count: %s" % (error, num))
print("Total: %s. Errors: %s. Accuracy: %s" % (self.totalCount, self.errorsCount, round(100 - self.errorsCount / self.totalCount * 100, 2)))
def diff_sentences(originalSentences, reconvertedSentences):
if len(originalSentences) != len(reconvertedSentences):
raise Exception("Original sentences and reconverted sentences length must be equals")
grammaDiffer = GrammaDiffer()
for index in range(len(originalSentences)):
originalSentence = originalSentences[index]
reconvertedSentence = reconvertedSentences[index]
for wordIndex in range(len(originalSentence)):
originalWord = originalSentence[wordIndex]
reconvertedWord = reconvertedSentence[wordIndex]
grammaDiffer.registerPair(originalWord, reconvertedWord)
grammaDiffer.dumpResult()
<file_sep>from src.common.gramma import Gramma
from src.gikry.predictor import GIKRYPredictor
import sys
class UD2GIKRYConverter():
def __init__(self, use_prediction):
self.posPredictor = GIKRYPredictor('pos')
self.genderPredictor = GIKRYPredictor('gender')
self.casePredictor = GIKRYPredictor('case')
self.nounTypePredictor = GIKRYPredictor('nounType')
self.fullFormPredictor = GIKRYPredictor('fullForm')
self.aspectPredictor = GIKRYPredictor('aspect')
self.aspectualPredictor = GIKRYPredictor('aspectual')
self.tensePredictor = GIKRYPredictor('tense')
self.verbFormPredictor = GIKRYPredictor('verbForm')
self.transPredictor = GIKRYPredictor('trans')
self.categoryOfAdjectivePredictor = GIKRYPredictor('categoryOfAdjective')
self.syntaxTypePredictor = GIKRYPredictor('syntaxType')
self.typeOfAnotherPredictor = GIKRYPredictor('typeOfAnother')
self.typeOfAdpositionPredictor = GIKRYPredictor('typeOfAdposition')
self.structureOfAdpositionPredictor = GIKRYPredictor('structureOfAdposition')
self.categoryOfNumeralPredictor = GIKRYPredictor('categoryOfNumeral')
self.formOfNumeralPredictor = GIKRYPredictor('formOfNumeral')
self.use_prediction = use_prediction
def convert(self, ud_sentences):
gikry_sentences = []
for index in range(len(ud_sentences)):
sys.stdout.write("convert %s/%s\r" % (index, len(ud_sentences)))
sys.stdout.flush()
ud_sentence = ud_sentences[index]
gikry_sentence = []
for grammaIndex in range(len(ud_sentence)):
ud_gramma = ud_sentence[grammaIndex]
gikry_gramma = self.convertGramma(ud_gramma, ud_sentence, grammaIndex)
gikry_sentence.append(gikry_gramma)
gikry_sentences.append(gikry_sentence)
return gikry_sentences
def convertGramma(self, ud_gramma, sentence, grammaInSentenceIndex):
pos = 'X'
gender = None
animacy = None
number = None
case = None
aspect = None
mood = None
person = None
poss = None
reflex = None
tense = None
verbForm = None
voice = None
degree = None
nameType = None
trans = None
invl = None
additional = []
fullForm = None
nounType = None
additionalCase = None
aspectual = None
categoryOfAdjective = None
syntaxType = None
categoryOfNumeral = None
formOfNumeral = None
typeOfAdposition = None
structureOfAdposition = None
typeOfAnother = None
if ud_gramma.pos == 'NOUN':
pos = 'N'
if ud_gramma.pos == 'PROPN':
pos = 'N'
if ud_gramma.pos == 'PRON':
pos = 'P'
if ud_gramma.pos == 'DET':
pos = 'P'
if ud_gramma.pos == 'ADJ':
pos = 'A'
if ud_gramma.pos == 'NUM':
pos = 'M'
if ud_gramma.pos == 'ADV':
pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['R', 'W'])
if ud_gramma.pos == 'AUX':
pos = 'V'
if ud_gramma.pos == 'VERB':
pos = 'V'
if ud_gramma.pos == 'CONJ':
pos = 'C'
if ud_gramma.pos == 'ADP':
pos = 'S'
if ud_gramma.pos == 'INTJ':
pos = 'I'
if ud_gramma.pos == 'PART':
pos = 'Q'
if ud_gramma.pos == 'SYM':
pos = 'X'
if ud_gramma.pos == 'PUNCT':
pos = 'X'
if ud_gramma.pos == 'X':
pos = 'X'
if ud_gramma.gender == 'Gender=Masc': gender = 'm'
elif ud_gramma.gender == 'Gender=Fem': gender = 'f'
elif ud_gramma.gender == 'Gender=Neut': gender = 'n'
else:
gender = self.predict(self.genderPredictor, sentence, grammaInSentenceIndex, [None, 'c'])
if ud_gramma.animacy == 'Animacy=Anim': animacy = 'y'
if ud_gramma.animacy == 'Animacy=Inan': animacy = 'n'
if ud_gramma.number == 'Number=Sing': number = 's'
if ud_gramma.number == 'Number=Plur': number = 'p'
if ud_gramma.number == 'Number=Ptan': number = 'i'
if ud_gramma.number == 'Number=Coll': number = 'i'
if ud_gramma.case == 'Case=Nom': case = self.predict(self.casePredictor, sentence, grammaInSentenceIndex, ['n', 'v'])
if ud_gramma.case == 'Case=Gen': case = self.predict(self.casePredictor, sentence, grammaInSentenceIndex, ['g', 'p'])
if ud_gramma.case == 'Case=Dat': case = 'd'
if ud_gramma.case == 'Case=Acc': case = 'a'
if ud_gramma.case == 'Case=Loc': case = 'l'
if ud_gramma.case == 'Case=Ins': case = 'i'
if pos == 'N':
nounType = self.predict(self.nounTypePredictor, sentence, grammaInSentenceIndex, ['c', 'p'])
if pos == 'A':
fullForm = self.predict(self.fullFormPredictor, sentence, grammaInSentenceIndex, ['s', 'f'])
if pos == 'V':
if ud_gramma.aspect == 'Aspect=Imp': aspect = 'i'
elif ud_gramma.aspect == 'Aspect=Perf': aspect = 'p'
else:
aspect = self.predict(self.aspectPredictor, sentence, grammaInSentenceIndex, [None, '*'])
if ud_gramma.mood == 'Mood=Ind': mood = 'i'
if ud_gramma.mood == 'Mood=Cnd': mood = 'i'
if ud_gramma.mood == 'Mood=Imp': mood = 'm'
if pos == 'V':
aspectual = self.predict(self.aspectualPredictor, sentence, grammaInSentenceIndex, [None, 'm', 'b'])
if ud_gramma.person == 'Person=1': person = '1'
if ud_gramma.person == 'Person=2': person = '2'
if ud_gramma.person == 'Person=3': person = '3'
if ud_gramma.tense == 'Tense=Past': tense = 's'
elif ud_gramma.tense == 'Tense=Pres': tense = 'p'
elif ud_gramma.tense == 'Tense=Fut': tense = 'f'
else:
tense = self.predict(self.tensePredictor, sentence, grammaInSentenceIndex, [None, '*'])
if pos == 'V':
if ud_gramma.verbForm == 'VerbForm=Fin': verbForm = None
elif ud_gramma.verbForm == 'VerbForm=Inf': verbForm = 'n'
elif ud_gramma.verbForm == 'VerbForm=Part': verbForm = 'p'
elif ud_gramma.verbForm == 'VerbForm=Trans': verbForm = 'g'
else:
verbForm = self.predict(self.verbFormPredictor, sentence, grammaInSentenceIndex, [None, 'x'])
if pos == 'V' and (verbForm == 'p' or verbForm == 'g'):
fullForm = self.predict(self.fullFormPredictor, sentence, grammaInSentenceIndex, ['s', 'f'])
if ud_gramma.voice == 'Voice=Act': voice = 'a'
if ud_gramma.voice == 'Voice=Mid': voice = 'p'
if ud_gramma.voice == 'Voice=Pass': voice = 's'
if ud_gramma.degree == 'Degree=Pos': degree = 'p'
if ud_gramma.degree == 'Degree=Cmp': degree = 'c'
if ud_gramma.degree == 'Degree=Sup': degree = 's'
# модель для переходности
if pos == 'V':
trans = self.predict(self.transPredictor, sentence, grammaInSentenceIndex, [None, 'y', 'n'])
if pos == 'P':
# модель для систаксического типа прилагательного
syntaxType = self.predict(self.syntaxTypePredictor, sentence, grammaInSentenceIndex, [None, 'n', 'a', 'p', 'r'])
# модель для разряда местоимения
categoryOfAdjective = self.predict(self.categoryOfAdjectivePredictor, sentence, grammaInSentenceIndex, [None, 'p', 'd', 'i', 's', 'q', 'x', 'z', 'n'])
# модель для признака у части речи X
if pos == 'X':
typeOfAnother = self.predict(self.typeOfAnotherPredictor, sentence, grammaInSentenceIndex, [
None,
'u',
'd',
'c',
'p',
'f',
'z',
'r',
's',
'g',
't',
'-',
])
if pos == 'S':
# модель для типа предлога
typeOfAdposition = self.predict(self.typeOfAdpositionPredictor, sentence, grammaInSentenceIndex, ['p', 't'])
# модель для структуры предлога
structureOfAdposition = self.predict(self.structureOfAdpositionPredictor, sentence, grammaInSentenceIndex, ['s', 'c'])
if pos == 'M':
# модель для разряда числительного
categoryOfNumeral = self.predict(self.categoryOfNumeralPredictor, sentence, grammaInSentenceIndex, ['c', 'l', 'o', '*'])
# модель для формы записи числительного
formOfNumeral = self.predict(self.formOfNumeralPredictor, sentence, grammaInSentenceIndex, ['l', 'd', 'r'])
gramma = Gramma(
ud_gramma.word,
ud_gramma.lemma if ud_gramma.lemma else "",
pos,
gender,
animacy,
number,
case,
aspect,
mood,
person,
poss,
reflex,
tense,
verbForm,
voice,
degree,
nameType,
trans,
invl,
additional,
fullForm,
nounType,
additionalCase,
aspectual,
categoryOfAdjective,
syntaxType,
categoryOfNumeral,
formOfNumeral,
typeOfAdposition,
structureOfAdposition,
typeOfAnother
)
return gramma
def predict(self, predictor, sentence, grammaInSentenceIndex, variants, debug=False):
if not self.use_prediction:
return variants[0]
prediction = predictor.predict(sentence, grammaInSentenceIndex)
if debug == True:
print("Prediction is: %s" % prediction)
if not prediction or prediction not in variants:
return variants[0]
else:
return prediction<file_sep>import collections
import os
TAGS_ORDER = [
'noun',
'propn',
'pron',
'det',
'adj',
'num',
'conj',
'adv',
'part',
'adp',
'aux',
'verb',
'intj',
'sym',
'punct',
'x',
'h', # непонятно, что это
'gender=masc',
'gender=fem',
'gender=neut',
'animacy=anim',
'animacy=inan',
'number=sing',
'number=coll',
'number=plur',
'number=ptan',
'case=nom',
'case=gen',
'case=dat',
'case=acc',
'case=loc',
'case=ins',
'aspect=imp',
'aspect=perf',
'mood=ind',
'mood=cnd',
'mood=imp',
'person=1',
'person=2',
'person=3',
'poss=yes',
'reflex=yes',
'tense=past',
'tense=pres',
'tense=fut',
'verbform=fin',
'verbform=inf',
'verbform=part',
'verbform=trans',
'voice=act',
'voice=mid',
'voice=pass',
'degree=pos',
'degree=cmp',
'degree=sup',
'nametype=geo',
'nametype=prs',
'nametype=giv',
'nametype=sur',
'nametype=com',
'nametype=pro',
'nametype=oth',
]
class UDSaver():
def save(self, filename, sentences):
with open(filename, 'w') as targetFile:
for sentence in sentences:
targetFile.write("BEGIN\n")
for gramma in sentence:
string = self.grammaToString(gramma)
targetFile.write(string)
targetFile.write("END\n")
targetFile.close()
def grammaToString(self, gramma):
tags = []
tags.append(gramma.pos)
if gramma.gender != None: tags.append(gramma.gender)
if gramma.animacy != None: tags.append(gramma.animacy)
if gramma.number != None: tags.append(gramma.number)
if gramma.case != None: tags.append(gramma.case)
if gramma.aspect != None: tags.append(gramma.aspect)
if gramma.mood != None: tags.append(gramma.mood)
if gramma.person != None: tags.append(gramma.person)
if gramma.poss != None: tags.append(gramma.poss)
if gramma.reflex != None: tags.append(gramma.reflex)
if gramma.tense != None: tags.append(gramma.tense)
if gramma.verbForm != None: tags.append(gramma.verbForm)
if gramma.voice != None: tags.append(gramma.voice)
if gramma.degree != None: tags.append(gramma.degree)
if gramma.nameType != None: tags.append(gramma.nameType)
if gramma.trans != None: tags.append(gramma.trans)
if gramma.invl != None: tags.append(gramma.invl)
tags.extend(gramma.additional)
tags = self.sortTags(tags)
return "%s\t%s\t%s\n" % (gramma.word, gramma.lemma, ",".join(tags))
def sortTags(self, tags):
tagsDict = {}
for tag in tags:
if not tag:
continue
index = TAGS_ORDER.index(tag.lower())
tagsDict[index] = tag
tagsDict = collections.OrderedDict(sorted(tagsDict.items()))
sortedTags = []
for key, value in tagsDict.items():
sortedTags.append(value)
return sortedTags
<file_sep>def split_files(source, targetTrain, targetTest, ratio = 0.8):
sentences = []
with open(source, 'r') as sourceFile:
sentence = []
for line in sourceFile:
if line == "BEGIN\n":
continue
elif line == "END\n":
sentences.append(sentence)
sentence = []
continue
sentence.append(line)
trainSentences = sentences[:int(len(sentences) * ratio)]
testSentences = sentences[int(len(sentences) * ratio):]
with open(targetTrain, 'w') as file:
for sentence in trainSentences:
file.write("BEGIN\n")
for line in sentence:
file.write(line)
file.write("END\n")
with open(targetTest, 'w') as file:
for sentence in testSentences:
file.write("BEGIN\n")
for line in sentence:
file.write(line)
file.write("END\n")
<file_sep>from src.common.errstats import ErrStats
def diff_files(filename1, filename2):
errstat = ErrStats()
with open(filename1, 'r') as file1:
file1lines = file1.readlines()
with open(filename2, 'r') as file2:
file2lines = file2.readlines()
total = 0
errors = 0
totalTags = 0 # подсчет ошибки по признакам, а не по словам
tagsErrors = 0
for index in range(len(file1lines)):
total += 1
str1 = file1lines[index].strip()
str2 = file2lines[index].strip()
if str1 == "" or str2 == "":
continue
if str1 != str2:
# print("Error in diff: %s => %s" % (str1, str2))
expectedTags = extract_tags(str1)
actualTags = extract_tags(str2)
if not expectedTags and not actualTags:
raise Exception("No expectedTags and not actualTags\n%s\n%s" % (str1, str2))
errstat.registerError(expectedTags, actualTags)
errors += 1
(extraTags, missingTags) = get_missing_and_extra_tags(expectedTags, actualTags)
totalTags += len(expectedTags)
tagsErrors += len(extraTags) + len(missingTags)
else:
expectedTags = extract_tags(str1)
if expectedTags:
totalTags += len(expectedTags)
errstat.printErrors()
print('Total lines: %s' % total)
print("Errors: %s" % errors)
print("Accuracy: %s" % round(100 - errors / total * 100, 2))
tagsAccuracy = round(100 - tagsErrors / totalTags * 100, 2)
# print("Total tags: %s. Tags errors: %s. Accuracy: %s" % (totalTags, tagsErrors, tagsAccuracy))
def extract_tags(string):
# добьётесь добиться VERB,Number=Plur,Aspect=Perf,Mood=Ind,Person=2,VerbForm=Fin,Voice=Act
pieces = string.split("\t")
if len(pieces) < 3:
return None
tags = pieces[2].strip().split(',')
return tags
def get_missing_and_extra_tags(expectedTags, actualTags):
if expectedTags and actualTags:
missingTags = list(set(expectedTags) - set(actualTags))
extraTags = list(set(actualTags) - set(expectedTags))
elif not expectedTags and actualTags and len(actualTags) > 0:
extraTags = actualTags
missingTags = []
elif not actualTags and expectedTags and len(expectedTags) > 0:
missingTags = expectedTags
extraTags = []
else:
raise Exception("No normal tags and no predicted tags")
return (extraTags, missingTags)<file_sep>from src.common.gramma import Gramma
from src.oc.predictor import OCPrecitor
from src.common.nnPredictor import NnPredictor
import sys
import re
class UD2OCConverter():
def __init__(self, use_prediction, use_nn):
self.use_nn = use_nn
if (use_nn):
self.posPredictor = NnPredictor('oc', 'pos')
self.casePredictor = NnPredictor('oc', 'case')
self.transPredictor = NnPredictor('oc', 'trans')
self.invlPredictor = NnPredictor('oc', 'invl')
self.verbFormPredictor = NnPredictor('oc', 'verbForm')
self.degreePredictor = NnPredictor('oc', 'degree')
# self.additionalPredictor = NnPredictor('oc', 'additional')
self.additionalPredictor = OCPrecitor('additional')
self.nameTypePredictor = OCPrecitor('nameType')
else:
self.posPredictor = OCPrecitor('pos')
self.casePredictor = OCPrecitor('case')
self.transPredictor = OCPrecitor('trans')
self.invlPredictor = OCPrecitor('invl')
self.verbFormPredictor = OCPrecitor('verbForm')
self.degreePredictor = OCPrecitor('degree')
self.additionalPredictor = OCPrecitor('additional')
self.nameTypePredictor = OCPrecitor('nameType')
self.use_prediction = use_prediction
def convertGramma(
self,
ud_gramma,
sentence,
grammaInSentenceIndex,
predictedPosTags = None,
predictedCaseTags = None,
predictedTransTags = None,
predictedInvlTags = None,
predictedVerbFormTags = None,
predictedDegreeTags = None,
predictedAdditionalTags = None
):
pos = 'UNKN'
gender = None
animacy = None
number = None
case = None
aspect = None
mood = None
person = None
poss = None
reflex = None
tense = None
verbForm = None
voice = None
degree = None
nameType = None
trans = None
invl = None
additional = []
if ud_gramma.gender == 'Gender=Masc': gender = 'masc'
if ud_gramma.gender == 'Gender=Fem': gender = 'femn'
if ud_gramma.gender == 'Gender=Neut': gender = 'neut'
if ud_gramma.animacy == 'Animacy=Anim': animacy = 'anim'
if ud_gramma.animacy == 'Animacy=Inan': animacy = 'inan'
if ud_gramma.number == 'Number=Sing': number = 'sing'
if ud_gramma.number == 'Number=Plur': number = 'plur'
if ud_gramma.number == 'Number=Ptan': number = 'Pltm'
if ud_gramma.number == 'Number=Coll': number = 'Sgtm'
if ud_gramma.case == 'Case=Nom': case = 'nomn' # self.casePredictor.predict(sentence, grammaInSentenceIndex) if self.use_prediction else 'nomn'
if ud_gramma.case == 'Case=Gen': case = 'gent' # self.casePredictor.predict(sentence, grammaInSentenceIndex) if self.use_prediction else 'gent'
if ud_gramma.case == 'Case=Dat': case = 'datv'
if ud_gramma.case == 'Case=Acc': case = 'accs' # self.casePredictor.predict(sentence, grammaInSentenceIndex) if self.use_prediction else 'accs'
if ud_gramma.case == 'Case=Loc': case = 'loct' # self.casePredictor.predict(sentence, grammaInSentenceIndex) if self.use_prediction else 'loct'
if ud_gramma.case == 'Case=Ins': case = 'ablt'
if ud_gramma.aspect == 'Aspect=Imp': aspect = 'impf'
if ud_gramma.aspect == 'Aspect=Perf': aspect = 'perf'
if ud_gramma.mood == 'Mood=Ind': mood = 'indc'
if ud_gramma.mood == 'Mood=Cnd': mood = 'indc'
if ud_gramma.mood == 'Mood=Imp': mood = 'impr'
if ud_gramma.person == 'Person=1': person = '1per'
if ud_gramma.person == 'Person=2': person = '2per'
if ud_gramma.person == 'Person=3': person = '3per'
if ud_gramma.tense == 'Tense=Past': tense = 'past'
if ud_gramma.tense == 'Tense=Pres': tense = 'pres'
if ud_gramma.tense == 'Tense=Fut': tense = 'futr'
if ud_gramma.voice == 'Voice=Act': voice = 'actv'
if ud_gramma.voice == 'Voice=Mid': voice = 'actv'
if ud_gramma.voice == 'Voice=Pass': voice = 'pssv'
if ud_gramma.nameType == 'NameType=Geo': nameType = 'Geox'
if ud_gramma.nameType == 'NameType=Prs': nameType = self.predict(self.nameTypePredictor, sentence, grammaInSentenceIndex, ['Patr', 'Name'])
if ud_gramma.nameType == 'NameType=Giv': nameType = self.predict(self.nameTypePredictor, sentence, grammaInSentenceIndex, ['Patr', 'Name'])
if ud_gramma.nameType == 'NameType=Sur': nameType = 'Surn'
if ud_gramma.nameType == 'NameType=Com': nameType = 'Orgn'
if ud_gramma.nameType == 'NameType=Pro': nameType = 'Trad'
if ud_gramma.nameType == 'NameType=Oth': nameType = 'Init'
if ud_gramma.verbForm == 'VerbForm=Inf': verbForm = 'INFN'
elif ud_gramma.verbForm == 'VerbForm=Part':
if self.use_nn:
verbForm = self.extractTagFromNNPrediction(
predictedVerbFormTags[grammaInSentenceIndex] if grammaInSentenceIndex < len(predictedVerbFormTags) else None,
['PRTF', 'PRTS']
)
else:
verbForm = self.predict(self.verbFormPredictor, sentence, grammaInSentenceIndex, ['PRTF', 'PRTS'])
elif ud_gramma.verbForm == 'VerbForm=Trans': verbForm = 'GRND'
else:
if self.use_nn:
verbForm = self.extractTagFromNNPrediction(
predictedVerbFormTags[grammaInSentenceIndex] if grammaInSentenceIndex < len(predictedVerbFormTags) else None,
[None, 'Fimp', 'V-sh']
)
else:
verbForm = self.predict(self.verbFormPredictor, sentence, grammaInSentenceIndex, [None, 'Fimp', 'V-sh'])
if self.use_nn:
degree = self.extractTagFromNNPrediction(
predictedDegreeTags[grammaInSentenceIndex] if grammaInSentenceIndex < len(predictedDegreeTags) else None,
[None, 'ADVB', 'Cmp2', 'V-ej', 'Supr']
)
else:
degree = self.predict(self.degreePredictor, sentence, grammaInSentenceIndex, [None, 'ADVB', 'Cmp2', 'V-ej', 'Supr'])
if ud_gramma.pos == 'NOUN': pos = 'NOUN'
if ud_gramma.pos == 'PROPN': pos = 'NOUN'
if ud_gramma.pos == 'PRON': pos = 'NPRO'
if ud_gramma.pos == 'DET': pos = 'NPRO'
if ud_gramma.pos == 'ADJ':
if self.use_nn:
pos = self.extractTagFromNNPrediction(
predictedPosTags[grammaInSentenceIndex] if grammaInSentenceIndex < len(predictedPosTags) else None,
['ADJF', 'ADJS', 'COMP']
)
else:
pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['ADJF', 'ADJS', 'COMP'])
if ud_gramma.pos == 'NUM': pos = 'NUMR'
if ud_gramma.pos == 'ADV': pos = 'ADVB'
if ud_gramma.pos == 'AUX': pos = 'VERB'
# if ud_gramma.pos == 'VERB' and ud_gramma.verbForm == 'VerbForm=Inf': pos = 'INFN'
# if ud_gramma.pos == 'VERB' and ud_gramma.verbForm == 'VerbForm=Part':
# if self.use_nn:
# pos = self.extractTagFromNNPrediction(
# predictedPosTags[grammaInSentenceIndex] if grammaInSentenceIndex < len(predictedPosTags) else None,
# ['VERB', 'INFN', 'PRTF', 'PRTS', 'GRND']
# )
# else:
# pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['VERB', 'INFN', 'PRTF', 'PRTS', 'GRND'])
# if ud_gramma.pos == 'VERB' and ud_gramma.verbForm == 'VerbForm=Trans': pos = 'GRND'
if ud_gramma.pos == 'VERB':
if self.use_nn:
pos = self.extractTagFromNNPrediction(
predictedPosTags[grammaInSentenceIndex] if grammaInSentenceIndex < len(predictedPosTags) else None,
['VERB', 'INFN', 'PRTF', 'PRTS', 'GRND']
)
else:
pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['VERB', 'INFN', 'PRTF', 'PRTS', 'GRND'])
if ud_gramma.pos == 'CONJ': pos = 'CONJ'
if ud_gramma.pos == 'ADP': pos = 'PREP'
if ud_gramma.pos == 'INTJ': pos = 'INTJ'
if ud_gramma.pos == 'PART': pos = 'PRCL'
if ud_gramma.pos == 'SYM': pos = 'PNCT'
if ud_gramma.pos == 'PUNCT': pos = 'PNCT'
if ud_gramma.pos == 'X':
pattern = re.compile("^[0-9.,\-\+]+$")
if False and pattern.match(ud_gramma.word):
pos = 'NUMB'
elif self.use_nn:
pos = self.extractTagFromNNPrediction(
predictedPosTags[grammaInSentenceIndex] if grammaInSentenceIndex < len(predictedPosTags) else None,
['UNKN', 'NUMB', 'LATN', 'ROMN']
)
else:
pos = self.predict(self.posPredictor, sentence, grammaInSentenceIndex, ['UNKN', 'NUMB', 'LATN', 'ROMN'])
if self.use_nn:
trans = self.extractTagFromNNPrediction(
predictedTransTags[grammaInSentenceIndex] if grammaInSentenceIndex < len(predictedTransTags) else None,
[None, 'tran', 'intr']
)
invl = self.extractTagFromNNPrediction(
predictedInvlTags[grammaInSentenceIndex] if grammaInSentenceIndex < len(predictedInvlTags) else None,
[None, 'incl', 'excl']
)
else:
trans = self.predict(self.transPredictor, sentence, grammaInSentenceIndex, [None, 'tran', 'intr'])
invl = self.predict(self.invlPredictor, sentence, grammaInSentenceIndex, [None, 'incl', 'excl'])
additinalTags = self.additionalPredictor.predict(sentence, grammaInSentenceIndex) if self.use_prediction else ""
additional = additinalTags.split(",") if additinalTags != "" else []
gramma = Gramma(
ud_gramma.word,
ud_gramma.lemma,
pos,
gender,
animacy,
number,
case,
aspect,
mood,
person,
poss,
reflex,
tense,
verbForm,
voice,
degree,
nameType,
trans,
invl,
additional
)
return gramma
def convert(self, ud_sentences):
oc_sentences = []
posTags = None if not self.use_nn else self.posPredictor.predict(ud_sentences)
caseTags = None if not self.use_nn else self.casePredictor.predict(ud_sentences)
transTags = None if not self.use_nn else self.transPredictor.predict(ud_sentences)
invlTags = None if not self.use_nn else self.invlPredictor.predict(ud_sentences)
verbFormTags = None if not self.use_nn else self.verbFormPredictor.predict(ud_sentences)
degreeTags = None if not self.use_nn else self.degreePredictor.predict(ud_sentences)
additionalTags = None # if not self.use_nn else self.additionalPredictor.predict(ud_sentences)
for sentenceIndex in range(len(ud_sentences)):
sys.stdout.write("convert %s/%s\r" % (sentenceIndex, len(ud_sentences)))
sys.stdout.flush()
ud_sentence = ud_sentences[sentenceIndex]
oc_sentence = []
for index in range(len(ud_sentence)):
ud_gramma = ud_sentence[index]
posTagsForSentence = (posTags[sentenceIndex] if posTags else [])
caseForSentence = (caseTags[sentenceIndex] if caseTags else [])
transForSentence = (transTags[sentenceIndex] if transTags else [])
invlForSentence = (invlTags[sentenceIndex] if invlTags else [])
verbFormForSentence = (verbFormTags[sentenceIndex] if verbFormTags else [])
degreeForSentence = (degreeTags[sentenceIndex] if degreeTags else [])
additionalForSentence = (additionalTags[sentenceIndex] if additionalTags else [])
oc_gramma = self.convertGramma(
ud_gramma,
ud_sentence,
index,
posTagsForSentence,
caseForSentence,
transForSentence,
invlForSentence,
verbFormForSentence,
degreeForSentence,
additionalForSentence
)
oc_sentence.append(oc_gramma)
oc_sentences.append(oc_sentence)
return oc_sentences
def predict(self, predictor, sentence, grammaInSentenceIndex, variants):
if not self.use_prediction:
return variants[0]
prediction = predictor.predict(sentence, grammaInSentenceIndex)
if not prediction or prediction not in variants:
return variants[0]
else:
return prediction
def predictTagsWithNN(self, predictor, sentences):
print("Predict tags")
predictedTags = predictor.predict(sentences)
return predictedTags
def extractTagFromNNPrediction(self, predictedTag, possibleTags):
if not self.use_prediction:
return possibleTags[0]
if not predictedTag or predictedTag not in possibleTags:
return possibleTags[0]
else:
return predictedTag
<file_sep>def merge_files(files, resultFile):
with open(resultFile, 'w') as result:
for file in files:
with open(file, 'r') as f:
for line in f:
result.write(line)
result.write("\n")
result.close()
<file_sep># Конвертация корпуса во внутренне представление
1. Подготовка папок для корпусов:
```
mkdir data
mkdir data/OpenCorpora
mkdir data/UD
mkdir data/NKRY
mkdir data/GIKRY
```
###### OpenCorpora
Корпус в разметке OpenCorpora надо разместить в папке `data/OpenCorpora`, а файл назвать `annot.opcorpora.xml`.
###### UD
Корпус в разметке UD надо разместить в папке `data/UD`, а файл назвать `text.txt`.
###### NKRY
Все файлы корпуса (файлы с текстами) разместить в папке `data/NKRY`
###### GIKRY
Все файлы корпуса (файлы с текстами) разместить в папке `data/GIKRY`
2. Подготовка папок для временных файлов:
```
mkdir tmp
mkdir tmp/gikry
mkdir tmp/ud
mkdir tmp/nkry
mkdir tmp/nkry/texts
mkdir tmp/oc
```
3. Запуск конвертации во внутреннее представление:
```
python main.py prepare ud
python main.py prepare oc
python main.py prepare nkry
python main.py prepare gikry
```
# Обучение моделей
1. Подготовка папок для файлов моделей:
```
mkdir model
mkdir model/gikry
mkdir model/ud
mkdir model/nkry
mkdir model/oc
mkdir model/oc/classifier
```
2. Обучение CRF-моделей
```
python main.py train nkry
python main.py train gikry
python main.py train oc
python main.py train ud
```
3. Обучение нейронной сети
```
python main.py train_classifier oc pos
python main.py train_classifier oc case
python main.py train_classifier oc trans
python main.py train_classifier oc invl
python main.py train_classifier oc verbForm
python main.py train_classifier oc degree
```
# Тестирование точности с выводом ошибок
```
python main.py reconvert ud
python main.py reconvert oc
python main.py reconvert nkry
python main.py reconvert gikry
```
# Точность преобразований
|Конвертация|Точность без моделей|Точность с CRF|Точность с RNN|
|-|-|-|-|
|OpenCorpora -> UD -> OpenCorpora|79.84%|94.54%|89.05%|
|UD -> OpenCorpora -> UD|88.8%|97.79%||
|GIKRY -> UD -> GIKRY|73.81%|94.20%||
|NKRY -> UD -> NKRY|81.75%|93.70%||
<file_sep>import pycrfsuite
from loader import loadOCGrammasFromFile
from trainer import Trainer
from features_builder import FeaturesBuilder
"""
Тестирование всех моделей на угадывание значений
Весь текст прогоняется через модель, и считаем процент угадываний
"""
# считываем строки из файла в формате OC и переводим в граммы
filename = '../tmp/opencorpora_parsed.txt'
sentences = loadOCGrammasFromFile(filename)
predictors = [
'pos',
'gender',
'animacy',
'number',
'case',
'aspect',
'mood',
'person',
'poss',
'reflex',
'tense',
'verbForm',
'voice',
'degree',
'nameType',
'trans',
'invl',
]
for predictor in predictors:
features_builder = FeaturesBuilder(predictor)
errors = 0
total = 0
tagger = pycrfsuite.Tagger()
tagger.open("./oc_model/crf_%s.model" % predictor)
for sentence in sentences:
(features, _) = features_builder.make_features_and_results(sentence)
results = tagger.tag(features)
for index in range(len(sentence)):
gramma = sentence[index]
result = results[index]
expectedResult = getattr(gramma, predictor)
if expectedResult == None:
expectedResult = ""
total += 1
if expectedResult != result:
# print("Error: %s %s" % (expectedResult, result))
errors += 1
print("Признак %s. Всего слов: %s. Ошибок: %s. Точность: %s" % (predictor, total, errors, round((100 - errors / total * 100), 2)))
<file_sep>import sys
"""
1) Парсим файл в UD
2) Переводим файл в OpenCorpora
3) Переводим файл обратно в UD
4) Сравниваем UD1 и UD2
"""
from src.oc.train import train_all_models as train_all_models_oc
from src.nkry.train import train_all_models as train_all_models_nkry
from src.gikry.train import train_all_models as train_all_models_gikry
from src.ud.train import train_all_models as train_all_models_ud
from src.oc.parser import parse_opencorpora
from src.oc.converter_oc2ud import OC2UDConverter
from src.oc.converter_ud2oc import UD2OCConverter
from src.nkry.converter_nkry2ud import NKRY2UDConverter
from src.nkry.converter_ud2nkry import UD2NKRYConverter
from src.gikry.converter_gikry2ud import GIKRY2UDConverter
from src.gikry.converter_ud2gikry import UD2GIKRYConverter
from src.common.loader import loadOCGrammasFromFile, loadNKRYGrammasFromFile, loadUDGrammasFromFile, loadGIKRYGrammasFromFile
from src.oc.saver import OCSaver
from src.nkry.saver import NKRYSaver
from src.gikry.saver import GIKRYSaver
from src.common.differ import diff_files
from src.common.merge import merge_files
from src.ud.parser import parse_ud
from src.ud.saver import UDSaver
from src.gikry.parser import parse_gikry
from src.common.gramma_differ import diff_sentences
from src.training.classifier.trainer import ClassifierTrainer
from src.common.split_files import split_files
from os import listdir
from os.path import isfile, join
from src.nkry.parser import parse_nkry
command = sys.argv[1] if len(sys.argv) > 1 else 'reconvert_oc'
secondArg = sys.argv[2] if len(sys.argv) > 2 else None
thirdArg = sys.argv[3] if len(sys.argv) > 3 else None
if (command == 'reconvert'):
if secondArg == 'oc':
print("Step 1. Save original file with saver")
saver = OCSaver()
# Конвертирование OC-грамем в UD-грамемы
original_oc_sentences = loadOCGrammasFromFile('tmp/oc/test.txt')
saver.save('tmp/oc/test_non_converted.txt', original_oc_sentences)
print("Step 2. Convert OC to UD")
oc2ud_converter = OC2UDConverter(True)
ud_sentences = oc2ud_converter.convert(original_oc_sentences)
# Конвертация обратно из UD-грамем в OC-грамемы
print("Step 3. Create UD2OC Converter")
ud2oc_converter = UD2OCConverter(True, False)
print("Step 4. Convert UD to OC")
oc_sentences = ud2oc_converter.convert(ud_sentences)
# Сохранение грамем в OC-файл
print("Step 5. Save converted OC file")
saver.save('tmp/oc/test_converted.txt', oc_sentences)
print("Step 6. Diff original and converted file")
# Сравнивание исходного OC-файла и получившегося OC-файла
diff_sentences(original_oc_sentences, oc_sentences)
diff_files('tmp/oc/test_non_converted.txt', 'tmp/oc/test_converted.txt')
elif secondArg == 'nkry':
print("Step 1. Save original file with saver")
saver = NKRYSaver()
# Конвертирование NKRY-грамем в UD-грамемы
original_nkry_sencentes = loadNKRYGrammasFromFile('tmp/nkry/test.txt')
saver.save('tmp/nkry/test_not_converted.txt', original_nkry_sencentes)
print("Step 2. Convert NKRY to UD")
nkry2ud_converter = NKRY2UDConverter(True)
ud_sentences = nkry2ud_converter.convert(original_nkry_sencentes)
# Конвертация обратно из UD-грамем в NKRY-грамемы
print("Step 3. Create UD2NKRY Converter")
ud2nkry_converter = UD2NKRYConverter(True)
print("Step 4. Convert UD to NKRY")
nkry_sentences = ud2nkry_converter.convert(ud_sentences)
# Сохранение грамем в OC-файл
print("Step 5. Save converted NKRY file")
saver.save('tmp/nkry/test_converted.txt', nkry_sentences)
print("Step 6. Diff original and converted file")
# Сравнивание исходного OC-файла и получившегося OC-файла
diff_sentences(original_nkry_sencentes, nkry_sentences)
diff_files('tmp/nkry/test_not_converted.txt', 'tmp/nkry/test_converted.txt')
elif secondArg == 'gikry':
print("Step 1. Load original file")
saver = GIKRYSaver()
original_gikry_sentences = loadGIKRYGrammasFromFile('tmp/gikry/test.txt')
print("Step 2. Save original grammas with saver")
saver.save('tmp/gikry/test_not_converted.txt', original_gikry_sentences)
print("Step 3. Convert GIKRY to UD")
gikry2ud_converter = GIKRY2UDConverter(True)
ud_sentences = gikry2ud_converter.convert(original_gikry_sentences)
print("Step 4. Convert UD to GIKRY")
ud2gikry_converter = UD2GIKRYConverter(True)
gikry_sentences = ud2gikry_converter.convert(ud_sentences)
print("Step 5. Save GIKRY sentences")
saver.save('tmp/gikry/test_converted.txt', gikry_sentences)
print("Step 6. Diff original and converted file")
diff_sentences(original_gikry_sentences, gikry_sentences)
diff_files('tmp/gikry/test_not_converted.txt', 'tmp/gikry/test_converted.txt')
elif secondArg == 'ud':
print("Step 1. Save original file with saver")
saver = UDSaver()
original_ud_sencentes = loadUDGrammasFromFile('tmp/ud/test.txt')
saver.save('tmp/ud/test_not_converted.txt', original_ud_sencentes)
# # Конвертирование UD-грамем в OC-грамемы
print("Step 2. Convert UD to OC")
ud2oc_converter = UD2OCConverter(True, False)
oc_sentences = ud2oc_converter.convert(original_ud_sencentes)
# # Конвертация обратно из UD-грамем в NKRY-грамемы
print("Step 3. Create OC2UD Converter")
od2ud_converter = OC2UDConverter(True)
print("Step 4. Convert OC to UD")
ud_sentences = od2ud_converter.convert(oc_sentences)
# # Сохранение грамем в UD-файл
print("Step 5. Save converted UD file")
saver.save('tmp/ud/test_converted.txt', ud_sentences)
print("Step 6. Diff original and converted file")
# Сравнивание исходного UD-файла и получившегося UD-файла
diff_sentences(original_ud_sencentes, ud_sentences)
diff_files('tmp/ud/test_not_converted.txt', 'tmp/ud/test_converted.txt')
elif command == 'prepare':
if secondArg == 'nkry':
# Конвертация оригинальных NKRY-файлов в внутренний формат
path = 'data/NKRY'
files = [f for f in listdir(path) if isfile(join(path, f))]
for file in files:
print("Parse NKRY file %s" % file)
filename = join(path, file)
text = parse_nkry(filename)
print("Write parsed data for %s" % file)
with open('tmp/nkry/texts/%s.txt' % file.replace('.xhtml', '.txt'), 'w') as result:
result.write(text)
result.close()
# Слияние всех полученных NKRY-файлов в один
tmpPath = 'tmp/nkry/texts'
files = [join(tmpPath, f) for f in listdir(tmpPath) if isfile(join(tmpPath, f))]
print("Merge %s files" % len(files))
merge_files(files, 'tmp/nkry/merged.txt')
split_files('tmp/nkry/merged.txt', 'tmp/nkry/train.txt', 'tmp/nkry/test.txt')
elif secondArg == 'gikry':
# Конвертация оригинальных NKRY-файлов в внутренний формат
path = 'data/GIKRY'
files = [f for f in listdir(path) if isfile(join(path, f))]
for file in files:
print("Parse GIKRY file %s" % file)
filename = join(path, file)
text = parse_gikry(filename)
print("Write parsed data for %s" % file)
with open("tmp/gikry/texts/%s.txt" % file, 'w') as result:
result.write(text)
result.close()
tmpPath = 'tmp/gikry/texts'
files = [join(tmpPath, f) for f in listdir(tmpPath) if isfile(join(tmpPath, f))]
print("Merge %s files" % len(files))
merge_files(files, 'tmp/gikry/merged.txt')
split_files('tmp/gikry/merged.txt', 'tmp/gikry/train.txt', 'tmp/gikry/test.txt')
elif secondArg == 'oc':
# Парсинг исходного файла opencorpora из XML в строчную структуру
print("Parse opencorpora file")
filename = "data/OpenCorpora/annot.opcorpora.xml"
text = parse_opencorpora(filename)
print("Write parsed data")
with open('tmp/oc/opencorpora_parsed.txt', 'w') as result:
result.write(text)
result.close()
split_files('tmp/oc/opencorpora_parsed.txt', 'tmp/oc/train.txt', 'tmp/oc/test.txt')
elif secondArg == 'ud':
print("Parse UD file")
filename = 'data/UD/text.txt' if thirdArg != 'small' else 'data/UD/text.small.txt'
print(filename)
text = parse_ud(filename)
print('Write parsed data')
with open('tmp/ud/parsed.txt', 'w') as result:
result.write(text)
result.close()
split_files('tmp/ud/parsed.txt', 'tmp/ud/train.txt', 'tmp/ud/test.txt')
else:
print("Неизвестная разметка %s, используйте nkry, oc" % secondArg)
elif command == 'train':
if secondArg == 'oc':
# Тренировка всех OC-моделей на подготовленном тексте, который парсился выше
train_all_models_oc('tmp/oc/train.txt')
elif secondArg == 'nkry':
train_all_models_nkry('tmp/nkry/train.txt')
elif secondArg == 'gikry':
train_all_models_gikry('tmp/gikry/train.txt')
elif secondArg == 'ud':
train_all_models_ud('tmp/ud/train.txt')
else:
print("Неизвестная разметка %s, используйте nkry, oc" % secondArg)
elif command == 'train_classifier':
tagToTrain = thirdArg
if not tagToTrain:
print("Specify tag for training")
quit()
if secondArg == 'oc':
# Тренировка нейронной сети на подготовленном тексте
textFilename = 'tmp/oc/train.txt'
sentences = loadOCGrammasFromFile(textFilename)
trainer = ClassifierTrainer(sentences, tagToTrain)
trainer.train('model/oc/classifier/%s/' % tagToTrain)
elif command == 'count':
markup = secondArg
testFile = 'tmp/%s/test.txt' % markup
trainFile = 'tmp/%s/train.txt' % markup
testSentences = []
trainSentences = []
if markup == 'oc':
testSentences = loadOCGrammasFromFile(testFile)
trainSentences = loadOCGrammasFromFile(trainFile)
elif markup == 'ud':
testSentences = loadUDGrammasFromFile(testFile)
trainSentences = loadUDGrammasFromFile(trainFile)
elif markup == 'nkry':
testSentences = loadNKRYGrammasFromFile(testFile)
trainSentences = loadNKRYGrammasFromFile(trainFile)
elif markup == 'gikry':
testSentences = loadGIKRYGrammasFromFile(testFile)
trainSentences = loadGIKRYGrammasFromFile(trainFile)
testWords = 0
trainWords = 0
for sentence in testSentences:
for word in sentence:
testWords += 1
for sentence in trainSentences:
for word in sentence:
trainWords += 1
print("Train words: %s. Test words: %s" % (trainWords, testWords))
else:
print("Unknown command %s" % command)
<file_sep>"""
Сборщик статистики по ошибкам
"""
import operator
class ErrStats():
def __init__(self):
self.errors = {}
def registerError(self, normalTags, predictedTags):
if normalTags and predictedTags:
missingTags = list(set(normalTags) - set(predictedTags))
extraTags = list(set(predictedTags) - set(normalTags))
elif not normalTags and predictedTags and len(predictedTags) > 0:
extraTags = predictedTags
missingTags = []
elif not predictedTags and normalTags and len(normalTags) > 0:
missingTags = normalTags
extraTags = []
else:
raise Exception("No normal tags and no predicted tags")
actualTags = []
for missingTag in missingTags:
actualTags.append("-%s" % missingTag)
for extraTag in extraTags:
actualTags.append("+%s" % extraTag)
string = ",".join(actualTags)
if not string in self.errors:
self.errors[string] = 0
self.errors[string] += 1
def printErrors(self):
sorted_d = sorted(self.errors.items(), key=operator.itemgetter(1))
for (error, num) in sorted_d:
print("Error: %s, number: %s" % (error, num))
<file_sep>import sys
from lxml import etree
import re
def parse_gikry(filename):
print("Start to parse file %s" % filename)
gikryFile = open(filename)
sentences = []
sentence = []
lIndex = 0
for line in gikryFile:
lIndex += 1
sys.stdout.write("Line num: %s \r" % lIndex)
sys.stdout.flush()
# пустая строка - разделитель предложений. Пустые строки могут идти подряд. Пустые предложения не пишем в итог
# строка со словом вида:
# 515092 0001 Председатель [председатель] Npmsn-y
# Встречаются ненужные строки вида:
# TEXTID=18949_1******************************77519988_1049.dat
line = line.strip()
if line.find("TEXTID") == 0:
continue
if (line == ""):
# пустая строка. Сохраняем предложение, если оно есть
if len(sentence) > 1: # там что-то кроме BEGIN
sentence.append("END")
sentences.append(sentence)
sentence = []
sentence.append("BEGIN")
continue
(word, lemma, tags) = parseWord(line)
tags = list(tags.strip())
tags = clearEmptyTags(tags)
tags = ",".join(tags)
sentence.append("%s\t%s\t%s" % (word.strip(), lemma.strip(), tags))
print()
print("fill lines")
print()
lines = []
wIndex = 0
for sentence in sentences:
for word in sentence:
wIndex += 1
lines.append(word)
sys.stdout.write("Word num: %s \r" % wIndex)
sys.stdout.flush()
print()
print('start to join text')
text = "\n".join(lines)
print('finish to fill lines')
return text
def parseWord(line):
# 515092 0001 Председатель [председатель] Npmsn-y
# 519999 P .
pucntM = re.search('\d+\s*P\t(.*)', line)
wordM = re.search(
'\d+\s+\d+\s+(.*)\t\[(.*)\]\s*\t([\?A-Za-z\-]+)',
line
)
if wordM:
return (wordM.group(1), wordM.group(2), wordM.group(3))
elif pucntM:
# это знак пунктуации
return (pucntM.group(1), pucntM.group(1), 'X')
else:
print("Unknown regexp for line \"%s\"" % line)
quit()
"""
Очищаем пустые теги в конце списка тегов. Пустые теги: "-"
"""
def clearEmptyTags(tags):
# ищем последний тег, который не пустой
normalIndex = -1
for index in range(len(tags)):
if tags[index] != '-':
normalIndex = index
if normalIndex >= 0:
return tags[0:normalIndex+1]
else:
return []
<file_sep>import sys
def parse_ud(filename):
print("Start to parse file %s" % filename)
udFile = open(filename)
lines = []
lines.append('BEGIN')
for line in udFile:
line = line.strip()
if line.find('==') == 0:
continue # техническая строка
if not line or line.strip() == '':
# Новое предложение
lines.append('END')
lines.append('BEGIN')
else:
items = line.split("\t")
word = items[0].strip()
lemma = items[1].strip()
PoS = items[2].strip()
tags1 = items[3].strip() if len(items) > 3 else ""
tags2 = items[4].strip() if len(items) > 4 else ""
tags = [PoS]
if tags1 != '_':
tags.extend(tags1.split('|'))
if tags2 != '_':
tags.extend(tags2.split('|'))
lines.append("%s\t%s\t%s" % (word, lemma, ",".join(tags)))
lines.append('END')
return "\n".join(lines)
<file_sep>import pycrfsuite
class Trainer():
def __init__(self, verbose=False):
self.trainer = pycrfsuite.Trainer(verbose=verbose)
def append(self, features, values):
self.trainer.append(features, values)
def train(self, filepath):
self.trainer.select('l2sgd')
self.trainer.train(filepath)
<file_sep>import sys
import xml.etree.ElementTree as ET
import src.oc.oc_tags as OCTags
import collections
"""
Парсинг XML-файла OpenCorpora в строчную структуру
"""
def parse_opencorpora(filename):
print("Start to parse file")
tree = ET.parse(filename)
print("Finish parse file")
root = tree.getroot()
lines = []
pIndex = 1
for text in root:
for paragraph in text.iter('paragraphs'):
sys.stdout.write("Paragraph num: %s \r" % pIndex)
sys.stdout.flush()
pIndex += 1
for sentence in paragraph:
lines.append("BEGIN")
for tokens in sentence.iter("tokens"):
for token in tokens:
tokenStr = parse_token(token)
lines.append(tokenStr)
lines.append("END")
print()
return "\n".join(lines)
"""
Парсинг <token id="2" text="Школа"><tfr rev_id="834910" t="Школа"><v><l id="380220" t="школа"><g v="NOUN"/><g v="inan"/><g v="femn"/><g v="sing"/><g v="nomn"/></l></v></tfr></token>
в Школа школа NOUN,inan,femn,sing,nomn
"""
def parse_token(token):
word = token.attrib['text']
v = token.find('tfr').find('v')
lemma = v.find('l').attrib['t']
tags = [g.attrib['v'] for g in v.iter('g')]
tags = sort_tags(tags)
# tags = normalize_tags(tags)
return word + "\t" + lemma + "\t" + ",".join(tags)
"""
Выкинуть ненужные теги и оставить нужные.
Массив тегов должен быть всегда одной длины, с пропусками значений, если они не найдены
POST - часть речи
ANim - категория одушевлённости
GNdr - род / род не выражен
NMbr - число
CAse - категория падежа
ASpc - категория вида
TRns - категория переходности
PErs - категория лица
TEns - категория времени
MOod - категория наклонения
INvl - категория совместности
VOic - категория залога
"""
def normalize_tags(tags):
normalized_tags = [""] * 12
for tag in tags:
if tag in OCTags.post:
normalized_tags[0] = tag
if tag in OCTags.anim:
normalized_tags[1] = tag
if tag in OCTags.gndr:
normalized_tags[2] = tag
if tag in OCTags.nmbr:
normalized_tags[3] = tag
if tag in OCTags.case:
normalized_tags[4] = tag
if tag in OCTags.aspc:
normalized_tags[5] = tag
if tag in OCTags.trns:
normalized_tags[6] = tag
if tag in OCTags.pers:
normalized_tags[7] = tag
if tag in OCTags.tens:
normalized_tags[8] = tag
if tag in OCTags.mood:
normalized_tags[9] = tag
if tag in OCTags.invl:
normalized_tags[10] = tag
if tag in OCTags.voic:
normalized_tags[11] = tag
return normalized_tags
TAGS_ORDER = [
'unkn',
'numb',
'latn',
'pnct',
'romn',
'symb',
'post',
'noun',
'adjf',
'adjs',
'adjx',
'comp',
'verb',
'infn',
'prtf',
'prts',
'grnd',
'numr',
'advb',
'npro',
'pred',
'prep',
'conj',
'prcl',
'intj',
'anim',
'anim',
'inan',
'gndr',
'masc',
'femn',
'neut',
'ms-f',
'nmbr',
'sing',
'plur',
'sgtm',
'pltm',
'fixd',
'case',
'nomn',
'gent',
'datv',
'accs',
'ablt',
'loct',
'voct',
'gen1',
'gen2',
'acc2',
'loc1',
'loc2',
'abbr',
'name',
'surn',
'patr',
'geox',
'orgn',
'trad',
'subx',
'supr',
'qual',
'apro',
'anum',
'poss',
'v-ey',
'v-oy',
'cmp2',
'v-ej',
'aspc',
'perf',
'impf',
'impx',
'trns',
'tran',
'intr',
'impe',
'uimp',
'mult',
'refl',
'pers',
'1per',
'2per',
'3per',
'tens',
'pres',
'past',
'futr',
'mood',
'indc',
'impr',
'invl',
'incl',
'excl',
'voic',
'actv',
'pssv',
'infr',
'slng',
'arch',
'litr',
'erro',
'dist',
'ques',
'dmns',
'prnt',
'v-be',
'v-en',
'v-ie',
'v-bi',
'fimp',
'prdx',
'coun',
'coll',
'v-sh',
'af-p',
'inmx',
'vpre',
'anph',
'init',
]
def sort_tags(tags):
tagsDict = {}
for tag in tags:
index = TAGS_ORDER.index(tag.lower())
tagsDict[index] = tag
tagsDict = collections.OrderedDict(sorted(tagsDict.items()))
sortedTags = []
for key, value in tagsDict.items():
sortedTags.append(value)
return sortedTags | 8103976b33ae8389be50a63ccc4535caab370432 | [
"Markdown",
"Python"
] | 36 | Python | Anna325/MD_Goncharova | 70598019d9e73932b90f4cc4ba323a03c4184dfe | 183e0d3e4b6155b5666d33d6cdc1948f8b5b5acc |
refs/heads/master | <file_sep>color
=====
Syntax highlighting for streamed terminal Go text.
```
cat file.go | color
```
or
```
cat $(find . -type f -name *.go) | color | less -r
```
![screen shot][1]
I started off wanting to write a very limited in scope Go app with the above
functionality for my first Go application only to find that it's pretty much
all been done by https://github.com/koron/beni. Except that beni only works on
files passed as arguments not the STDIN.
Clearly my contribution is not a big deal and I'll probably just do a quick PR
on beni to get this functionality added. But, it did give me a chance to work on
something Go related. Hopefully next time I'll think of an idea that hasn't
already been done by someone else.
[1]:./color.png
<file_sep>package main
import (
"bufio"
"github.com/koron/beni"
"os"
)
func main() {
stdin := bufio.NewReader(os.Stdin)
stdout := bufio.NewWriter(os.Stdout)
defer stdout.Flush()
beni.Highlight(stdin, stdout, "go", "base16", "Terminal256")
}
| efcd3063305c01c1d4b8fc26f5f6cc0a66655781 | [
"Markdown",
"Go"
] | 2 | Markdown | gophergala/color | 418da3903ac983adfc9183a2b0b9ff2e9222785a | 1870d1d834fccdba4278515cf91051ce8d06ef9a |
refs/heads/master | <file_sep>DO NOT USE.
This old proof-of-concept contains a vulnerability in the jquery file uploader, so DO NOT USE.
<file_sep># pip install -r requirements.txt
# AM: I've not tested this file yet!
Flask
Flask-Bootstrap
Flask-WTF
<file_sep>$(document).ready(function() {
json = $.parseJSON($("#filelist").val());
filetable = $("#filetable");
$.each(json, function(index, file) {
filetable.append("<input name='fileinputs' type='text' disabled value='" + file + "'/>");
});
});
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement
import uuid
import logging
import os
import urllib2
from flask import (Flask, request, render_template, jsonify, flash,
send_from_directory, url_for)
from werkzeug import secure_filename
from flask.ext.bootstrap import Bootstrap
from flask.ext.wtf import Form, TextField
from flask.ext.wtf.html5 import EmailField
app = Flask(__name__)
Bootstrap(app)
#app.config.from_object(__name__)
app.config['BOOTSTRAP_FONTAWESOME'] = True
app.config['SECRET_KEY'] = 'wtfkey'
app.config['UPLOAD_FOLDER'] = 'uploads'
@app.route('/')
def home():
return render_template('home.html')
class OtherForm(Form):
author = TextField('Author')
title = TextField('Title')
keywords = TextField('Keywords')
pub = TextField('Publication')
email = EmailField('Email')
#using generator allows us to order output and avoid csrf field
def basic_field_iter(self):
for f in [self.author, self.title, self.keywords]:
yield f
def adv_field_iter(self):
yield self.pub
yield self.email
@app.route('/addmeta', methods=['POST'])
def addmeta():
print 'here'
form = OtherForm()
return render_template(
'addmeta.html',
domain=request.form['domain'],
fileret=request.form.get('filelist'),
form=form)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'GET':
#Possibly not correct, but trying to mimic requests on working code
return ""
if request.method == 'POST':
#You can't use the data_file.content_length method as it is 0 usually
#Note that I've hard coded the server name, obviously you will need
#to fix this
data_file = request.files['files[]']
dir_id = str(uuid.uuid4())
temp_dir_name = str(app.config['UPLOAD_FOLDER']) + "/" + dir_id
try:
os.makedirs(temp_dir_name)
except OSError as ex:
flash("Caught Server Error: " + ex.strerror)
sec_file = secure_filename(data_file.filename)
file_name = os.path.join(temp_dir_name, sec_file)
data_file.save(file_name)
#Can also supply a thumbnail url, but I don't think we need to
return jsonify(
files=[dict(
name=sec_file,
size=os.stat(file_name).st_size, # content_length usually 0
type=data_file.content_type,
delete_url=url_for('getfiles', dir_id=dir_id,
filename=sec_file),
delete_type="DELETE",
url=url_for('getfiles', dir_id=dir_id, filename=sec_file))])
#Handle getting and deleting of files
@app.route('/files/<dir_id>/<filename>', methods=['GET', 'DELETE'])
def getfiles(dir_id, filename):
if request.method == 'GET':
return send_from_directory(app.config['UPLOAD_FOLDER'] + "/" + dir_id,
urllib2.unquote(filename))
if request.method == 'DELETE':
file_dir = app.config['UPLOAD_FOLDER'] + "/" + dir_id
try:
os.remove(file_dir + "/" + urllib2.unquote(filename))
if not os.listdir(file_dir):
os.rmdir(file_dir)
except OSError as ex:
flash("Caught Server Error: " + ex.strerror)
return ""
@app.route('/finalise', methods=['POST'])
def finalise():
return render_template('finalise.html', tag=uuid.uuid4())
@app.route('/deposit')
def deposit():
return render_template('deposit.html')
if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-d', '--debug', dest='debug',
help='Run app in debug mode', action='store_true', default=False)
(options, args) = parser.parse_args()
if options.debug:
print ' * Setting debug mode'
app.config['DEBUG'] = True
app.logger.setLevel(logging.ERROR)
app.run(host='0.0.0.0')
<file_sep>{% extends "ss-base.html" %}
{% set active_page = "deposit" %}
{% block body_content %}
{{ super() }}
<div class="container">
<!-- Main hero unit for a primary marketing message or call to action -->
<div class="hero-unit">
<h1>Deposit Accepted</h1>
<p/>
<br/>
<p>Your unique ID is {{ tag }}</p>
<!-- <p>Your public URL is {{ tag }}</p> -->
</div>
</div>
{% endblock %}
| 0c040aadeecf5bb82a0e69c385b4d443a3c19c29 | [
"HTML",
"Markdown",
"JavaScript",
"Python",
"Text"
] | 5 | Markdown | amouat/super-simple-store | 505f404c90c3826603a7abf51a914726629e4f4d | 2fe671203ac23b509dc1ea09e0a4132711e780c2 |
refs/heads/master | <file_sep><?php
class OemProApiSegmentService extends OemProApiService {
public function __construct(OemProApiClient &$client) {
parent::__construct('Segment', $client);
}
public function Create($listID, $fields = array()) {
$params = array(
'SubscriberListID' => intval($listID)
);
foreach($fields as $fieldID => $fieldValue) {
$params['Segment' . $fieldID] = $fieldValue;
}
return $this->call('Create', $params, true);
}
public function Update($segmentID, $listID, $fields = array()) {
$params = array(
'SegmentID' => intval($segmentID),
'SubscriberListID' => intval($listID)
);
foreach($fields as $fieldID => $fieldValue) {
$params['Segment' . $fieldID] = $fieldValue;
}
return $this->call('Update', $params, true);
}
protected function getErrorMessage($subCommand, $errorCode, $response) {
if($subCommand == 'Get') {
switch($errorCode) {
case 1: return 'Missing subscriber list ID';
}
} else if($subCommand == 'Update') {
switch($errorCode) {
case 1: return 'Missing segment ID';
case 2: return 'Missing segment name';
case 3: return 'Missing segment operator';
case 4: return 'Invalid segment id';
case 5: return 'Invalid segment operator';
}
} else if($subCommand == 'Create') {
switch($errorCode) {
case 1: return 'Missing subscriber list ID';
case 2: return 'Missing segment name';
case 3: return 'Missing segment operator';
}
}
return null;
}
}
?><file_sep><?php
class OemProApiSegmentsService extends OemProApiService {
public function __construct(OemProApiClient &$client) {
parent::__construct('Segments', $client);
}
public function Get($listID, $orderField, $orderType) {
return $this->call('Get', array(
'OrderField' => $orderField,
'OrderType' => $orderType,
'SubscriberListID' => intval($listID)
), true);
}
public function Delete($segmentIDs) {
return $this->call('Delete', array(
'Segments' => $segmentIDs
), true);
}
protected function getErrorMessage($subCommand, $errorCode, $response) {
if($subCommand == 'Get') {
switch($errorCode) {
case 1: return 'subscriber list ID';
}
}else if($subCommand == 'Delete') {
switch($errorCode) {
case 1: return 'Missing subscriber list ID';
case 2: return 'Missing segment name';
case 3: return 'Missing segment operator';
}
}
return null;
}
}
?><file_sep><?php
class OemProApiCampaignService extends OemProApiService {
public function __construct(OemProApiClient &$client) {
parent::__construct('Campaign', $client);
}
public function Get($campaignID) {
return $this->call('Get', array(
'CampaignID' => intval($campaignID)
), true);
}
public function Create($campaignName) {
return $this->call('Create', array(
'CampaignName' => $campaignName
), true);
}
protected function getErrorMessage($subCommand, $errorCode, $response) {
if($subCommand == 'Get') {
switch($errorCode) {
case 1: return 'Missing campaign ID';
case 99998: return 'Authentication failure or session expired';
case 99999: return 'Not enough privileges';
}
}else if($subCommand == 'Create') {
switch($errorCode) {
case 1: return 'Missing campaign name';
case 99998: return 'Authentication failure or session expired';
case 99999: return 'Not enough privileges';
}
}
return null;
}
}
?> | b7c6149ef2b50510b269d2e618217bf47a86e206 | [
"PHP"
] | 3 | PHP | tplessis/oempro-api-client-php | 8239a2f3fd581220512572966570b76156e1d661 | 4a126e7a2c284ff38486e0588eae67fb2d590e87 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use View;
use App\User;
use App\Order;
use Auth;
use DB;
class CustomerController extends Controller
{
public function __construct(){
$this->middleware('auth');
}
public function index(Request $request)
{
if(empty(Auth::check())){
return Redirect::to('/');
}
$fromDate = $request->get('from');
$toDate = $request->get('to');
// $customers = DB::table('user')->select('id', 'name','email','city','credit_limit')->where('user_type','=','1')->lists('name','id');
$datas = DB::table('user')
->leftJoin('order', 'user.id', '=', 'order.id_customer')
->where(function($query) use ($fromDate, $toDate){
$query->where('user.user_type', '=', '1');
if($fromDate!='' && $toDate==''){
$query->where('order.order_date', '>=', $fromDate);
}
if($fromDate=='' && $toDate!=''){
$query->where('order.order_date', '<=', $toDate);
}
if($fromDate!='' && $toDate!=''){
$query->where('order.order_date', '>=', $fromDate);
$query->where('order.order_date', '<=', $toDate);
}
})
->groupBy('user.id')
->select('user.name','user.email','user.city','user.credit_limit', 'user.id',DB::raw('count(order.id) as totalOrder'),DB::raw('sum(order_total) as totalAmount'))
->paginate(10);
return view('customer.index',compact('datas'));
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
if(empty(Auth::check())){
return Redirect::to('/');
}
return View::make('customer.create');
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store(Request $request)
{
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'name' => 'required',
'email' => 'required|email|unique:user,email',
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>',
'address1' => 'required',
'city' => 'required',
'country' => 'required',
'credit_limit' => array('required', 'regex:/^\d*(\.\d{2})?$/')
);
$msg = array('integer'=>"Only number value are allowed.");
$validator = Validator::make($request->all(), $rules,$msg);
// process the login
if ($validator->fails())
{
return Redirect::to('customer/create')
->withErrors($validator)
->withInput($request->except('password'));
}
else
{
// store
$user = new User;
$user->name = $request->get('name');
$user->email = $request->get('email');
$user->password = <PASSWORD>($request->get('password'));
$user->address1 = $request->get('address1');
$user->address2 = $request->get('address2');
$user->city = $request->get('city');
$user->country = $request->get('country');
$user->credit_limit = $request->get('credit_limit');
$user->user_type = 1;
$user->save();
// redirect
//Session::flash('message', 'Successfully created nerd!');
$request->session()->flash('alert-success', 'Customer was successful added!');
return Redirect::to('customer/index');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
if(empty(Auth::check())){
return Redirect::to('/');
}
$user = User::findOrFail($id);
return view('customer.edit', compact('user'));
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update(Request $request,$id)
{
$user = User::findOrFail($id);
$rules = array(
'name' => 'required',
'email' => 'required|email|unique:user,email,'.$user->id,
'password' => '<PASSWORD>',
'address1' => 'required',
'city' => 'required',
'country' => 'required',
'credit_limit' => array('required', 'regex:/^\d*(\.\d{2})?$/')
);
$this->validate($request, $rules);
$user->update($request->all());
//\Flash::success('User updated successfully.');
$request->session()->flash('alert-success', 'Customer was updated successfully.');
return redirect()->route('customer.index');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy(Request $request,$id)
{
User::find($id)->delete();
$request->session()->flash('alert-success', 'Customer was deleted successfully.');
return redirect()->route('customer.index');
}
}
<file_sep>/*
SQLyog Ultimate v9.51
MySQL - 5.6.21 : Database - laravel5_test1
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`laravel5_test1` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `laravel5_test1`;
/*Table structure for table `measure_units` */
DROP TABLE IF EXISTS `measure_units`;
CREATE TABLE `measure_units` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
/*Data for the table `measure_units` */
insert into `measure_units`(`id`,`name`) values (1,'Litre'),(2,'Gallon'),(3,'Kilogram'),(4,'Piece (for 1 item)'),(5,'Metre'),(6,'Tonne');
/*Table structure for table `migrations` */
DROP TABLE IF EXISTS `migrations`;
CREATE TABLE `migrations` (
`migration` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*Data for the table `migrations` */
/*Table structure for table `order` */
DROP TABLE IF EXISTS `order`;
CREATE TABLE `order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_user` int(11) DEFAULT NULL,
`id_customer` int(11) DEFAULT NULL,
`total_cost` float(10,2) DEFAULT NULL,
`tax` float(10,2) DEFAULT NULL,
`order_total` float(10,2) DEFAULT NULL,
`order_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
/*Data for the table `order` */
/*Table structure for table `order_line` */
DROP TABLE IF EXISTS `order_line`;
CREATE TABLE `order_line` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_order` int(11) DEFAULT NULL,
`id_product` int(11) DEFAULT NULL,
`qty` int(11) DEFAULT NULL,
`sale_price_per_unit` float(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
/*Data for the table `order_line` */
/*Table structure for table `password_resets` */
DROP TABLE IF EXISTS `password_resets`;
CREATE TABLE `password_resets` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) DEFAULT NULL,
`token` varchar(255) DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*Data for the table `password_resets` */
insert into `password_resets`(`id`,`email`,`token`,`created_at`) values (5,'<EMAIL>','5d4c4<PASSWORD> <KEY>04a','2016-05-21 11:51:51');
/*Table structure for table `products` */
DROP TABLE IF EXISTS `products`;
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`id_uom` int(11) NOT NULL,
`price_per_unit` decimal(10,2) NOT NULL,
`qty_in_stock` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*Data for the table `products` */
insert into `products`(`id`,`name`,`id_uom`,`price_per_unit`,`qty_in_stock`) values (1,'Toy',4,'100.00',10),(2,'Cup',4,'20.00',100);
/*Table structure for table `user` */
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL,
`email` varchar(128) DEFAULT NULL,
`password` varchar(128) DEFAULT NULL,
`remember_token` varchar(100) DEFAULT NULL,
`address1` varchar(128) DEFAULT NULL,
`address2` varchar(128) DEFAULT NULL,
`city` varchar(64) DEFAULT NULL,
`country` varchar(64) DEFAULT NULL,
`credit_limit` decimal(10,2) DEFAULT NULL,
`user_type` tinyint(1) DEFAULT NULL COMMENT '0 = user, 1 = customer',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*Data for the table `user` */
insert into `user`(`id`,`name`,`email`,`password`,`remember_token`,`address1`,`address2`,`city`,`country`,`credit_limit`,`user_type`,`created_at`,`updated_at`) values (3,'Ravi','<EMAIL>','$2y$1<KEY>','<KEY>',NULL,NULL,NULL,NULL,'11.20',NULL,'2016-05-21 10:20:45','2016-05-21 10:20:45'),(4,'Customer','<EMAIL>','<PASSWORD>',NULL,'test','test','Noida','INDIA','1001.00',1,'2016-05-24 11:03:11',NULL);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
<file_sep><?php
namespace App\Http\Controllers;
use Request;
use App\Product;
use App\Order;
use App\User;
use App\OrderLine;
use App\MeasureUnit;
use Auth;
use App\Http\Requests;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use View;
use Session;
use App\Http\Controllers\Controller;
use DB;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return Response
*/
public function __construct(){
$this->middleware('auth');
}
public function index()
{
//login check
if(empty(Auth::check())){
return Redirect::to('/');
}
$products = Product::paginate(10);
$measure_units = MeasureUnit::lists('name', 'id');
$measure_units = $measure_units->toArray();
return view('products.index',compact(['products', 'measure_units']));
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
//login check
if(empty(Auth::check())){
return Redirect::to('/');
}
$measure_units = MeasureUnit::lists('name', 'id');
$measure_units = $measure_units->toArray();
return view('products.create',compact('measure_units'));
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store(Request $request)
{
// validation rule
$rules = array(
'name' => 'required',
'id_uom' => 'required',
'price_per_unit' => 'required|numeric',
'qty_in_stock' => 'required|numeric'
);
$validator = Validator::make($request::all(), $rules);
if ($validator->fails())
{
return Redirect::to('products/create')
->withErrors($validator)->withInput();
}else{
$products = Request::all();
Product::create($products);
Session::flash('alert-success', 'Product added successfully!');
return Redirect::to('products');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//login check
if(empty(Auth::check())){
return Redirect::to('/');
}
$products = Product::findOrFail($id);
$measure_units = MeasureUnit::lists('name', 'id');
$measure_units = $measure_units->toArray();
return view('products.edit',compact(['products', 'measure_units']));
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update(Request $request, $id)
{
$productUpdate = $request::all();
$product = Product::find($id);
$rules = array(
'name' => 'required',
'id_uom' => 'required',
'price_per_unit' => 'required|numeric',
'qty_in_stock' => 'required|numeric'
);
$validator = Validator::make($request::all(), $rules);
//$this->validate($request, $rules);
if ($validator->fails())
{
return Redirect::to('products/'.$id.'/edit')
->withErrors($validator)->withInput();
}else{
$product->update($productUpdate);
Session::flash('alert-success', 'Product updated successfully!');
return Redirect::to('products');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id){
Product::find($id)->delete();
Session::flash('alert-success', 'Product deleted successfully!');
return Redirect::to('products');
}
public function order(){
//login check
if(empty(Auth::check())){
return Redirect::to('/');
}
$id_user = Auth::user()->id;
$userArr = User::find($id_user)->toArray();
$credit_limit = $userArr['credit_limit'];
$orderLine = new OrderLine();
$products = $orderLine->getCart($id_user);
//echo "<pre>";
//print_r($products);
$measure_units = MeasureUnit::lists('name', 'id');
$measure_units = $measure_units->toArray();
return view('products.order',compact(['products', 'measure_units', 'credit_limit']));
}
/**
* ajax request to get credit info
*/
public function creditcheck(Request $request){
$products = Request::all();
//echo "<pre>";
//print_r($products);die;
$available = 1;
$amt = 1;
$sum_amt = 0;
$sum_qty = 0;
$id_user = Auth::user()->id;
$tax = 0;
if(count($products) > 0 && isset($products['pid'])){
$userArr = User::find($id_user)->toArray();
$amount = $userArr['credit_limit'];
foreach($products['pid'] as $val){
$productArr = Product::find($val)->toArray();
if($products['qty_in_stock_'.$val] > $productArr['qty_in_stock']){
$available=0;
Session::flash('alert-warning', 'Quantity not available');
break;
}else{
$sum_amt = $sum_amt + ($products['qty_in_stock_'.$val] * $productArr['price_per_unit']);
$sum_qty = $sum_qty + $products['qty_in_stock_'.$val];
}
}
if($sum_amt > $amount){
$amt=0;
Session::flash('alert-warning', 'Insufficient amount');
return Redirect::to('products/order');
}
if($sum_qty == 0){
Session::flash('alert-warning', 'Quantity cannot be null.');
return Redirect::to('products/order');
}
//INSERT into order_line table
if($amt ==1 && $available == 1){
//insert into order table
$order_total = $tax + $sum_amt;
$orders = array('id_user'=>$id_user,'id_customer'=>$id_user,'total_cost'=>$sum_amt,'tax'=>$tax,'order_total'=>$order_total);
$orderData = Order::create($orders);
$id_order = $orderData->id;
//update order line table
DB::table('order_line')->whereIn('id', $products['orderline'])->update(array('id_order' => $id_order));
//update user credits
$amount = $amount - $sum_amt;
DB::table('user')->where('id', $id_user)->update(array('credit_limit' => $amount));
foreach($products['pid'] as $val){
$productArr = Product::find($val)->toArray();
//reduce quantity from product table
$qty_in_stock = $productArr['qty_in_stock'] - $products['qty_in_stock_'.$val];
$products_update = array('qty_in_stock'=>$qty_in_stock);
$product = Product::find($val);
$product->update($products_update);
}
Session::flash('alert-success', 'Order has been done successfully!');
}
}else{
Session::flash('alert-warning', 'Invalid request');
}
return Redirect::to('products/order');
}
public function addtocart() {
//login check
if(empty(Auth::check())){
return Redirect::to('/');
}
$products = Product::paginate(10);
$measure_units = MeasureUnit::lists('name', 'id');
$measure_units = $measure_units->toArray();
return view('products.addtocart',compact(['products', 'measure_units']));
}
public function addcart(Request $request){
//login check
if(empty(Auth::check())){
return Redirect::to('/');
}
$products = Request::all();
$customer_id = Auth::user()->id;
$pid = $products['pid'];
//fetch product detail
if(!empty($pid)){
$productDetail = Product::find($pid)->toArray();
}
$addcartstatusArray = DB::table('order_line')
->where(function($query) use ($customer_id, $pid){
if($customer_id!=''){
$query->where('order_line.id_customer', '=', $customer_id);
}
if($pid!=''){
$query->where('order_line.id_product', '=', $pid);
}
$query->where('order_line.id_order', '=', '0');
})
->lists('qty');
$newqty = 1;
if(!empty($addcartstatusArray)){
//update data in cart
$qty = $addcartstatusArray[0];
$newqty = $qty + 1;
DB::table('order_line')
->where('id_product', $pid)
->where('id_customer', $customer_id)
->update(['qty' => $newqty]);
}else{
//insert cart data
$productData = array();
$productData = array('id_product'=>$pid,'qty'=>1,'sale_price_per_unit'=>$productDetail['price_per_unit'],'id_customer'=>$customer_id,'id_order' => 0);
OrderLine::create($productData);
}
echo "1";
}
public function deletefromcard(){
$requestData = Request::all();
$id = $requestData['id'];
if(isset($id)){
DB::table('order_line')->where('id', '=', $id)->delete();
Session::flash('alert-success', 'Deleted successfully.');
}else{
Session::flash('alert-warning', 'Invalid product.');
}
return Redirect::to('products/order');
}
public function deletecart(){
DB::table('order_line')->where('id_customer', '=', Auth::user()->id)->delete();
Session::flash('alert-success', 'Deleted successfully.');
return Redirect::to('products/order');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use View;
use App\User;
use Auth;
class UserController extends Controller
{
public function __construct(){
$this->middleware('auth');
}
public function index(Request $request)
{
$q = $request->get('q');
$users = User::where('user_type', '=',0)
//->where('name', 'LIKE', '%'.$q.'%' or 'name', 'LIKE', '%'.$q.'%')
//->orWhere('$q',function ($query) {
// $query->where('name', 'LIKE', '%'.$q.'%')
// ->orWhere('name', 'LIKE', '%'.$q.'%');
// })
//->Orwhere('name', 'LIKE', '%'.$q.'%')
// ->where('user_type', '=',0)
->orderBy('name')->paginate(9);
return View::make('user.index', compact('users', 'q'));
//return View::make('user.index');
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
if(empty(Auth::check())){
return Redirect::to('/');
}
return View::make('user.create');
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store(Request $request)
{
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'name' => 'required',
'email' => 'required|email|unique:user,email',
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>'
);
$validator = Validator::make($request->all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('user/create')
->withErrors($validator)
->withInput($request->except('password'));
} else {
// store
$user = new User;
$user->name = $request->get('name');
$user->email = $request->get('email');
$user->password = <PASSWORD>($request->get('password'));
$user->user_type = 0;
$user->save();
// redirect
//Session::flash('message', 'Successfully created nerd!');
$request->session()->flash('alert-success', 'User was successful added!');
return Redirect::to('user/index');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
if(empty(Auth::check())){
return Redirect::to('/');
}
$user = User::findOrFail($id);
return view('user.edit', compact('user'));
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update(Request $request,$id)
{
$user = User::findOrFail($id);
$rules = array(
'name' => 'required',
'email' => 'required|email|unique:user,email,'.$user->id,
'password' => '<PASSWORD>'
);
$this->validate($request, $rules);
$user->update($request->all());
//\Flash::success('User updated successfully.');
$request->session()->flash('alert-success', 'User was updated successfully.');
return redirect()->route('user.index');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy(Request $request,$id)
{
User::find($id)->delete();
$request->session()->flash('alert-success', 'User was deleted successfully.');
return redirect()->route('user.index');
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
//dd( Auth::user());
return view('home');
});
Route::controllers([
'auth'=>'Auth\AuthController',
'password'=>'<PASSWORD>',
]);
// Authentication routes...
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');
// Registration routes...
Route::get('auth/register', 'Auth\AuthController@getRegister');
Route::post('auth/register', 'Auth\AuthController@postRegister');
// Password reset link request routes...
Route::get('password/email', 'Auth\PasswordController@getEmail');
Route::post('password/email', 'Auth\PasswordController@postEmail');
// Password reset routes...
Route::get('password/reset/{token}', 'Auth\PasswordController@getReset');
Route::post('password/reset', 'Auth\PasswordController@postReset');
//Route::get('/', array('as'=>'articles','uses'=>'ArticleController@Index'));//another way, route for controller
Route::get('user/index', 'UserController@index');
Route::post('user/store', 'UserController@store');
Route::resource('user', 'UserController');
Route::get('customer/index', 'CustomerController@index');
Route::post('customer/store', 'CustomerController@store');
Route::resource('customer', 'CustomerController');
Route::get('products/order', 'ProductController@order');
Route::get('products/deletefromcard', 'ProductController@deletefromcard');//for deleting item from cart
Route::get('products/deletecart', 'ProductController@deletecart');//for deleting cart
Route::get('products/addtocart', 'ProductController@addtocart');
Route::resource('products', 'ProductController');
Route::post('products/store', 'ProductController@store');
Route::post('products/creditcheck', 'ProductController@creditcheck');
Route::post('products/addcart', 'ProductController@addcart');
Route::get('order/index', 'OrderController@index');
Route::get('order/orderdetails', 'OrderController@orderdetails');
Route::get('order/deleteorder', 'OrderController@deleteorder');
Route::resource('order', 'OrderController');
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Order;
use App\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;
use Auth;
use DB;
class OrderController extends Controller
{
/**
* Display a listing of the resource.
*
* @return Response
*/
public function __construct(){
$this->middleware('auth');
}
public function index(Request $request)
{
if(empty(Auth::check())){
return Redirect::to('/');
}
$fromDate = $request->get('from');
$id = $request->get('id');
$toDate = $request->get('to');
$orders = DB::table('order')
->Join('user', 'user.id', '=', 'order.id_customer')
->where(function($query) use ($fromDate, $toDate,$id){
$query->where('user.user_type', '=', '1');
if($id!='' && $id>0) {
$query->where('order.id_customer','=',$id);
}
if($fromDate!='' && $toDate==''){
$query->where('order.order_date', '>=', $fromDate);
}
if($fromDate=='' && $toDate!=''){
$query->where('order.order_date', '<=', $toDate);
}
if($fromDate!='' && $toDate!=''){
$query->where('order.order_date', '>=', $fromDate);
$query->where('order.order_date', '<=', $toDate);
}
})
->select('order.id as id','total_cost', 'tax','order_total','order_date','name')
->paginate(10);
return view('orders.index',compact('orders','toDate','fromDate','id'));
}
public function orderdetails(Request $request)
{
if(empty(Auth::check())){
return Redirect::to('/');
}
$id = $request->get('id');
$orderLists = DB::table('order')
->Leftjoin('order_line', 'order.id', '=', 'order_line.id_order')
->Leftjoin('user', 'user.id', '=', 'order.id_customer')
->Leftjoin('products', 'products.id', '=', 'order_line.id_product')
->where(function($query) use ($id){
$query->where('user.user_type', '=', '1');
if($id!='' && $id > 0) {
$query->where('order.id','=',$id);
}
})
->select('user.name as customerName','total_cost', 'tax','order_total','order_date','products.name as productName','qty','sale_price_per_unit','id_product')
->paginate(10);
return view('orders.orderdetails', compact('orderLists'));
}
public function deleteorder(Request $request)
{
$id = $request->get('id');
$results = DB::table('order')
->Leftjoin('order_line', 'order.id', '=', 'order_line.id_order')
->Leftjoin('user', 'user.id', '=', 'order.id_customer')
->Leftjoin('products', 'products.id', '=', 'order_line.id_product')
->where(function($query) use ($id){
$query->where('user.user_type', '=', '1');
if($id!='' && $id > 0) {
$query->where('order.id','=',$id);
}
})
->select('user.name as customerName','user.id as userId','total_cost', 'tax','order_total','order_date','products.name as productName','qty','sale_price_per_unit','id_product','order_line.id as OLId','order.id')->get();
if(count($results)>0){
foreach($results as $result) {
$amount =$result->sale_price_per_unit;
$userId =$result->userId;
$prod = $result->id_product;
$prodQty = $result->qty;
$orderId = $result->id;
$OLId = $result->OLId;
//adding amountin user credit_limit
DB::table('user')
->where('id', $userId)
->update(['credit_limit' => DB::raw('credit_limit+'.(float)$amount)]);
if($this->isProductExits($prod)){
//adding product Qnty
DB::table('products')
->where('id', $prod)
->update(['qty_in_stock' => DB::raw('qty_in_stock+'.(int)$prodQty)]);
}
if($OLId>0){
DB::table('order_line')->where('id', '=', $OLId)->delete();
}
}
DB::table('order')->where('id', '=', $id)->delete();
}
$request->session()->flash('alert-success', 'Order was successful deleted!');
return Redirect::to('order/index');
die;
}
public function isProductExits($proid)
{
$products = DB::table('products')
->where(function($query) use ($proid){
$query->where('products.id', '=', $proid);
})
->lists('id');
if(count($products)>0){
return true;
}else{
return false;
}
}
}
<file_sep><?php
namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;
class OrderLine extends Model
{
protected $table = 'order_line';
protected $guarded = ['_token'];
public $timestamps = false;
public function getCart($userId){
$results= \DB::table('order_line as order_line')
->join('products as p', function($join) {
$join->on('p.id', '=', 'order_line.id_product');
})
->join('measure_units as mu', function($join) {
$join->on('mu.id', '=', 'p.id_uom');
})
->where(['id_customer'=>$userId,'id_order'=>0])
->select(['order_line.id','order_line.id_customer','order_line.id_order','order_line.id_product','qty',
'sale_price_per_unit','mu.name as unit_name','p.id as pid','p.name','p.price_per_unit'])
->get();
return $results;
}
}
| fe6ea86649d6058db413df57d20e5095506b12cf | [
"SQL",
"PHP"
] | 7 | PHP | ravikantmishra/test_laravel | 74c988ff38cad9801aa0e4f797d1e7c1c28e3c5a | 102413cd6d77dc0f2a74f2cf0b24413d2e19b3e3 |
refs/heads/master | <repo_name>xingziye/VCF-Hbase<file_sep>/setenv.sh
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/jre
export PATH=$PATH:$JAVA_HOME/bin
export HADOOP_HOME=/usr/local/hadoop
export HADOOP_MAPRED_HOME=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_HOME
export HADOOP_HDFS_HOME=$HADOOP_HOME
export YARN_HOME=$HADOOP_HOME
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin
export HADOOP_INSTALL=$HADOOP_HOME
export HBASE_HOME=/usr/local/hbase
export CLASSPATH=$CLASSPATH:$HBASE_HOME/lib
export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export HBASE_CONF_DIR=$HBASE_HOME/conf
export HADOOP_CLASSPATH=`${HBASE_HOME}/bin/hbase classpath`:/usr/lib/jvm/java-8-openjdk-amd64/lib/tools.jar
<file_sep>/src/TableModel.java
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
public class TableModel {
private static Configuration config;
public TableModel(Configuration conf) {
config = conf;
}
private static void createOrOverwrite(Admin admin, HTableDescriptor table) throws IOException {
if (admin.tableExists(table.getTableName())) {
System.out.println("Table exists. Deleting.");
admin.disableTable(table.getTableName());
admin.deleteTable(table.getTableName());
}
admin.createTable(table);
}
public void createSchemaTables(String tableName, String... columnFamilyNames) throws IOException {
try (Connection connection = ConnectionFactory.createConnection(config);
Admin admin = connection.getAdmin()) {
HTableDescriptor table = new HTableDescriptor(TableName.valueOf(tableName));
for (String cf : columnFamilyNames) {
table.addFamily(new HColumnDescriptor(cf).setCompressionType(Algorithm.NONE));
}
System.out.println("Creating table " + tableName);
createOrOverwrite(admin, table);
System.out.println("Done.");
}
}
public void insertData(String tableName, String key, String cf, String attr, String value) throws IOException {
try (Connection connection = ConnectionFactory.createConnection(config);
Table table = connection.getTable(TableName.valueOf(tableName))) {
Put p = new Put(Bytes.toBytes(key));
p.addColumn(Bytes.toBytes(cf), Bytes.toBytes(attr), Bytes.toBytes(value));
table.put(p);
System.out.println("data inserted");
}
}
}
<file_sep>/README.md
# VCF-Hbase
Annotate VCF file using Hbase framework.
## Environment
The code has been tested on a virtual machine with the following configurations:
* Ubuntu 16.04.4 LTS
* Java openjdk version "1.8.0_151"
* Hadoop 2.7.5
* Hbase 1.3.2
Both Hadoop and Hbase are configured in Pseudo-Distributed mode.
## Developing
We will take the assumption that Annotation Table resides in Hbase database and can be continually updated. User will use VCF file as input, and the output will be the annotated VCF.
### Table Schema
For the Annotation Table, we will design its schema and load some sample data for testing. This is done by `HbaseVCF.java` and `TableModel.java`.
The row key for Annotation Table has the design like this:
```
chrm.start.end.alt_base
```
And there will only be one column family `cosmic` and a single column qualifier `content` to store the annotation for this variant.
The benefit to have this schema design is that, first of all, it will have quick read access for the query in our problem. Ref base is not included as a part of row key, because it is already certain if we have specified both start and end position in a chromosome. With the query has the same structure as row key, we will be able to take the full advantage of NoSQL database system to fetch the content efficiently. Secondly, since everything in Hbase is sorted in order of row key, our data will be naturally grouped by chromosome and in its order of location.
Our data, for example, will have format like this:
Rowkey | ColumnFamly
------------ | :-----------:
| | Column
9.95121497.95121498.GA | ID=COSN212065;OCCURENCE=1(breast)
X.79951432.79951433.AA | ID=COSM1558810;OCCURENCE=1(lung)
X.107554022.107554023.AA | ID=COSM1650981,COSM1145489;OCCURENCE=1(lung)
... | ...
### Task Mapping
Since each VCF Table to be annotated is generally huge, it is necessary to annotate them in parallel. We can take the advantage of Hadoop MapReduce framework to speed up this process. `AnnotateVCF.java` will implement this task.
User can first put the input file into HDFS. In this sample implementation, the `AnnotateMapper` processes one line from input file at a time. The mapper will construct a query in the format mentioned above, send a query to Hbase, and get a result if the corresponding annotation exists. This operation can be further optimized in batch operation to process multiple lines at a time in future.
```java
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
...
Get g = new Get(Bytes.toBytes(rowKey));
g.addColumn(Bytes.toBytes(CF_DEFAULT), Bytes.toBytes(ATTR));
Result result = table.get(g);
...
context.write(mutation, annotation);
}
```
The KeyValue pair emits is simply the row key and its cell in Hbase, and they are the combination we desired for annotation. There is no need to furtherly process this KeyValue, we can omit the reducer and directly set the pair as the final output.
```java
job.setNumReduceTasks(0);
```
### Join Table
Consider that if both vcf file and annotation table are imported into Hbase database, we need to support a join operation to annotate our dataset. There are multiple ways to implement this operation. Although mapper-side join is more efficient for two sorted datasets, here we chose a reducer-side join algorithm as general solution.
The VCF table is using the same row key structure as above. `MultiTableInputFormat` allows us to put multiple tables as data source for mapper. Mapper will simply emit the row key and the corresponding column value: empty value for VCF table, and annotation text for Annotation table. Then we combine and reduce the result to see if the row key comes from both table. If so, we write the annotation text to the output file.
## Building
First build `HbaseVCF` to load the sample Annotation Table data:
```
$ javac HbaseVCF.java TableModel.java
$ java HbaseVCF
```
Then build Hadoop job to map input data to annotate:
```
$ hadoop com.sun.tools.javac.Main AnnotateVCF.java
$ jar cf av.jar AnnotateVCF*.class
$ hadoop jar av.jar AnnotateVCF -libjars $(hbase mapredcp | tr ':' ',') /input /output
```
The similar procedure for join two tables to annotate:
```
$ hadoop com.sun.tools.javac.Main JoinVCF.java
$ jar cf jv.jar JoinVCF*.class
$ hadoop jar jv.jar JoinVCF -libjars $(hbase mapredcp | tr ':' ',') /output
```
Notice there is no input directory.
## Reference
* [Apache HBase ™ Reference Guide](http://hbase.apache.org/book.html)
* [Apache Hadoop 2.7.5](http://hadoop.apache.org/docs/r2.7.5/)
* Google [Cloud Bigtable Documentation](https://cloud.google.com/bigtable/docs/)
* [HBase Tutorial](https://www.tutorialspoint.com/hbase/index.htm)
| a1dd69f354ed113f8c8e40d6e6555e2dd1904c3a | [
"Markdown",
"Java",
"Shell"
] | 3 | Shell | xingziye/VCF-Hbase | 350a0e994dd2563cba17c989e53833dc252eb2ab | c50075d8b0fe91cb94566032f573fbd990fad043 |
refs/heads/master | <file_sep>/*
Classic C code to understand MIDI files
MIDI Study Guide : https://ccrma.stanford.edu/~craig/14q/midifile/MidiFileFormat.html
*/
#include <stdio.h>
#include <stdlib.h>
struct headerChunk {
char fileID[4]; // indicates an actual MiDi file
short length; // header length
short format; // format [2 bytes] 0 : single track | 1 : multiple track | 2 : multiple song file format
short n; // number of tracks that follow
short division; // unit of time for delta timing
};
struct trackEvent {
short vTime; // a variable length value specifying the elapsed time (delta time) from the previous event to this event
short midiEvent; // any MIDI channel message such as note-on or note-off
};
struct trackChunk {
char trackID[4]; // marks the beginning of a track
int length; // track length
struct trackEvent event; // track event structure
};
int main() {
FILE *fp;
struct headerChunk head;
struct trackChunk track;
struct trackEvent evt;
fp = fopen("sample.mid", "rb");
if(fp == NULL) {
printf("\nError: failed to open mid file\nTerminating...\n");
return -1;
}
fread(&head.fileID[0], 1, sizeof(unsigned char), fp);
fread(&head.fileID[1], 1, sizeof(unsigned char), fp);
fread(&head.fileID[2], 1, sizeof(unsigned char), fp);
fread(&head.fileID[3], 1, sizeof(unsigned char), fp);
fread(&head.length, 1, sizeof(head.length), fp);
fread(&head.format, 1, sizeof(head.format), fp);
fread(&head.n, 1, sizeof(head.n), fp);
fread(&head.division, 1, sizeof(head.division), fp);
printf("File pointer position: %ld", ftell(fp));
printf("\nMIDI Headers:\nFile Descriptor : %s\nLength : %d\nFormat : %d\nN : %d\nDivision : %d", head.fileID, head.length, head.format, head.n, head.division);
return 0;
} | 8e4442f12d2c96e53c139fc044b20a6f81fef51d | [
"C"
] | 1 | C | Biswajee/MIDIReader | 74c85da10beb50ed52f07453041a2ec6cf89e21b | fd72d48bdcf8ab877a4673205b17ba702a33bf38 |
refs/heads/main | <repo_name>PiotrJustyna/FanoutHelperAPIV2<file_sep>/readme.md
# readme
Fanout Helper API V2 - this API serves as a sub-service of https://github.com/PiotrJustyna/FanoutAPIV2 and is one of FanoutAPIV2's fanout data sources. This API is also task-heavy. The key difference between this project and Fanout Helper API V1 is that the heavy tasking is being delegated to Orleans.
## parameters
Exposed are three parameters:
* `slaMs` - SLA expressed in milliseconds. This value controls the time after which the API controller is supposed to order its `CancellationTokenSource` to time out and cancel that source's cancellation tokens.
* `tasksPerRequest` - controls how many asynchronous tasks should be created per request.
* `taskDelayMs` - each task performs arbitrary work of a simple `Task.Delay`. `taskDelayMs` controls how long that delay should be. The value is expressed in milliseconds.
## example
`http://localhost:2345/helper?slaMs=2000&tasksPerRequest=1000&taskDelayMs=500`
The request orders the API to:
* terminate the request if it's not completed under 2000ms
* start 1000 worker tasks per request and await them trying to best utilize the given SLA (`slaMs`)
* artificially (and asynchronously) delay each worker tasks by 500ms in order to mimic real (e.g. I/O) work
## usage
1. To run the API in docker, execute: `run-api-docker.sh`.
2. Since FanoutAPIV1 is going to call this service, for the sake of simplicity, use FanoutAPIV1's load test script to test this service indirectly.
3. To access the API manually, use the following URL (while the API is running in docker, otherwise the port could be different): `http://localhost:2345/helper?slaMs=2000&tasksPerRequest=1000&taskDelayMs=500`<file_sep>/src/Controllers/HelperController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Interfaces;
using Microsoft.AspNetCore.Mvc;
using Orleans;
namespace FanoutHelperAPIV2.Controllers
{
[ApiController]
[Route("[controller]")]
public class HelperController : ControllerBase
{
private readonly IClusterClient _clusterClient;
private readonly Random _generator;
public HelperController(IClusterClient clusterClient)
{
_clusterClient = clusterClient;
_generator = new Random();
}
[HttpGet]
public async Task<ActionResult<Result>> Get(
int slaMs,
int tasksPerRequest,
int taskDelayMs,
CancellationToken cancellationToken)
{
var grain1 = _clusterClient.GetGrain<IWorker>(_generator.Next(0, Int32.MaxValue));
var grain2 = _clusterClient.GetGrain<IWorker>(_generator.Next(0, Int32.MaxValue));
var grain3 = _clusterClient.GetGrain<IWorker>(_generator.Next(0, Int32.MaxValue));
var grain4 = _clusterClient.GetGrain<IWorker>(_generator.Next(0, Int32.MaxValue));
var stopwatch = new Stopwatch();
stopwatch.Start();
var timeoutCancellationTokenSource = new CancellationTokenSource(slaMs);
var timeoutCancellationToken = timeoutCancellationTokenSource.Token;
var combinedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken,
timeoutCancellationToken);
var combinedCancellationToken = combinedCancellationTokenSource.Token;
// 2021-05-31 PJ:
// Link to the combinedCancellationToken.
// Also, reduce grain disposal time on the backend side.
var grainCancellationTokenSource = new GrainCancellationTokenSource();
var tasksPerParentTask = tasksPerRequest / 4;
var parentTasks = new List<Task<FanoutTaskStatus>>
{
grain1.ParentTask(
tasksPerParentTask,
taskDelayMs,
grainCancellationTokenSource.Token),
grain2.ParentTask(
tasksPerParentTask,
taskDelayMs,
grainCancellationTokenSource.Token),
grain3.ParentTask(
tasksPerParentTask,
taskDelayMs,
grainCancellationTokenSource.Token),
grain4.ParentTask(
tasksPerParentTask,
taskDelayMs,
grainCancellationTokenSource.Token),
};
var workTask = Task.WhenAll(parentTasks);
await Task.WhenAny(
workTask,
Task.Delay(slaMs, combinedCancellationToken));
FanoutTaskStatus result = parentTasks
.Select(x =>
x.IsCompletedSuccessfully
? new FanoutTaskStatus(x.Result.NumberOfSuccessfulTasks, x.Result.NumberOfFailedTasks)
: new FanoutTaskStatus(0, tasksPerParentTask))
.Aggregate((x, y) =>
new FanoutTaskStatus(
x.NumberOfSuccessfulTasks + y.NumberOfSuccessfulTasks,
x.NumberOfFailedTasks + y.NumberOfFailedTasks));
stopwatch.Stop();
if (result.NumberOfFailedTasks > 0)
{
return NoContent();
}
else
{
return Ok(new Result(
stopwatch.ElapsedMilliseconds,
result));
}
}
}
public record Result(
long ServerProcessingTimeMs,
FanoutTaskStatus CombinedTaskStatus);
} | 8a9c27842e3809685e76b4bb6997b11293b66745 | [
"Markdown",
"C#"
] | 2 | Markdown | PiotrJustyna/FanoutHelperAPIV2 | cf937ab3b7622cb209f36125ce9d1a7c4694cd77 | dc2e5a4567e96c6edbe92a4ad23a05313bdd9797 |
refs/heads/master | <repo_name>Frischifrisch/ASCIImoji<file_sep>/grunt/clean.js
module.exports = {
dist: {
src: "dist/**/*"
},
postbuild: {
src: ["dist/chrome-extension/key.pem", "docs/index.js"]
},
homepage: {
src: ["docs/images/**/*", "docs/index.**"]
},
homepagePostBuild: {
src: "docs/index.js"
},
key: {
src: "dist/chrome-extension/key.pem"
},
release: {
src: ["dist/chrome-extension"]
}
};
| fdf893b9bc930efb67c9cabda53e12c41de4e72d | [
"JavaScript"
] | 1 | JavaScript | Frischifrisch/ASCIImoji | c94d2a144e44c72cb2f65f09b9d72b35f8b0ff41 | b51c55821309d848b066447b0a3a4f5f4f3568ae |
refs/heads/master | <repo_name>ytken/TestProjectPTS<file_sep>/src/main/java/Output.java
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class Output {
public static final List<String> LABELS_LIST = Arrays.asList("mark01", "mark17", "mark23", "mark35", "markFV", "markFT", "markFX");
private String existsInLabels(String key){
for (String label : LABELS_LIST)
if (label.toLowerCase().equals(key))
return label;
return key;
}
// Вывод трех вариантов отчета в три различных файла, после формирования отчета выходит соответсвующее сообщение
void printTypeOne(Map<String, List<Integer>> result) throws IOException {
Map<String, Integer> outputList = new HashMap<>();
for (Map.Entry<String, List<Integer>> element : result.entrySet()) {
int sum = 0;
for (Integer i : element.getValue())
sum += i;
outputList.put(element.getKey(), sum);
}
String out = "{"; // Начало формирования Json строки типа 1
for (Map.Entry<String, Integer> element : outputList.entrySet()) {
out += "\"" + existsInLabels(element.getKey()) + "\":" + element.getValue() + ",";
}
out = out.substring(0,out.length()-1) + "}";
String fileOutput = "result01.json";
FileWriter writer = new FileWriter(fileOutput, false);
writer.write(out); // Конец формирования Json строки, вывод
writer.flush();
System.out.println("Итоговый отчет в форме 1 записан в файл " + fileOutput);
}
void printTypeTwo(Map<String, List<Integer>> result) throws IOException {
Map<String, Integer> outputList = new HashMap<>();
for (Map.Entry<String, List<Integer>> element : result.entrySet()) {
int sum = 0;
for (Integer i : element.getValue())
sum += i;
outputList.put(element.getKey(), sum);
}
String out = "{"; // Начало формирования Json строки типа 2
for (String label: LABELS_LIST) {
out += "\"" + label + "\":";
if (outputList.containsKey(label.toLowerCase()))
out += outputList.get(label.toLowerCase()) + ",";
else
out += "null,";
}
out = out.substring(0,out.length()-1) + "}";
String fileOutput = "result02.json";
FileWriter writer = new FileWriter(fileOutput, false);
writer.write(out); // Конец формирования Json строки, вывод
writer.flush();
System.out.println("Итоговый отчет в форме 2 записан в файл " + fileOutput);
}
void printTypeThree(Map<String, List<Integer>> result) throws IOException {
String out = "{";// Начало формирования Json строки типа 3
for (Map.Entry<String, List<Integer>> element : result.entrySet()) {
out += "\"" + existsInLabels(element.getKey()) + "\":[";
Collections.sort(element.getValue());
for (int i = element.getValue().size() - 1; i > 0 ; i--)
out += element.getValue().get(i) + " ";
out = out.substring(0,out.length() - 1) + "],";
}
out = out.substring(0, out.length() - 1) + "}";
String fileOutput = "result03.json";
FileWriter writer = new FileWriter(fileOutput, false);
writer.write(out); // Конец формирования Json строки, вывод
writer.flush();
System.out.println("Итоговый отчет в форме 3 записан в файл " + fileOutput);
}
}
| 3e791266f0bf7944813987535c4adc169260615d | [
"Java"
] | 1 | Java | ytken/TestProjectPTS | a1bd28b2d0b02aefc234bdf0f7d317ae4bd1a059 | fe9fdd5bad86508a732534ab8ffdfdfa8ba6a7b5 |
refs/heads/master | <file_sep>class Fabrication::Generator::ActiveRecord < Fabrication::Generator::Base
def self.supports?(klass)
defined?(ActiveRecord) && klass.ancestors.include?(ActiveRecord::Base)
end
def build_instance
if _klass.respond_to?(:protected_attributes)
self._instance = _klass.new(_attributes, without_protection: true)
else
self._instance = _klass.new(_attributes)
end
end
protected
def validate_instance
_instance.valid?
end
end
<file_sep>== This is a Rails based site for storing information about Problem Based Learning math problems as used at Trevor Day School
* Questions courtesy of Phillips Exeter Academy
* Creates/maintains a database of questions and topics (has_and_belongs_to_many relationship)
* Ruby version 2.0, Rails 4.0.0
* PostgresSQL database
* User authentication from Devise
* Object authorization from CanCan
* Image Management from CarrierWave/Rmagick
* Built on Nitrous.io
* Search functions using Ransack
* ...
<file_sep>class Fabrication::Generator::DataMapper < Fabrication::Generator::Base
def self.supports?(klass)
defined?(DataMapper) && klass.ancestors.include?(DataMapper::Hook)
end
def build_instance
self._instance = _klass.new(_attributes)
end
def validate_instance
_instance.valid?
end
protected
def persist
_instance.save
end
end
<file_sep>class Fabrication::Support
class << self
def fabricatable?(name)
Fabrication.manager[name] || class_for(name)
end
def class_for(class_or_to_s)
class_name = variable_name_to_class_name(class_or_to_s)
klass = constantize(class_name)
rescue NameError => original_error
raise Fabrication::UnfabricatableError.new(class_or_to_s, original_error)
end
def constantize(camel_cased_word)
names = camel_cased_word.split('::')
Object.const_get(camel_cased_word) if names.empty?
names.shift if names.size > 1 && names.first.empty?
names.inject(Object) do |constant, name|
if constant == Object
constant.const_get(name)
else
candidate = constant.const_get(name)
next candidate if constant.const_defined?(name, false)
next candidate unless Object.const_defined?(name)
constant = constant.ancestors.inject do |const, ancestor|
break const if ancestor == Object
break ancestor if ancestor.const_defined?(name, false)
const
end
constant.const_get(name, false)
end
end
end
def extract_options!(args)
args.last.is_a?(::Hash) ? args.pop : {}
end
def variable_name_to_class_name(name)
name.to_s.gsub(/\/(.?)/){"::#{$1.upcase}"}.gsub(/(?:^|_)(.)/){$1.upcase}
end
def find_definitions
puts "DEPRECATION WARNING: Fabrication::Support.find_definitions has been replaced by Fabrication.manager.load_definitions and will be removed in 3.0.0."
Fabrication.manager.load_definitions
end
def hash_class
@hash_class ||= defined?(HashWithIndifferentAccess) ? HashWithIndifferentAccess : Hash
end
def singularize(string)
string.singularize
rescue
string.end_with?('s') ? string[0..-2] : string
end
end
end
<file_sep>class Question < ActiveRecord::Base
has_and_belongs_to_many :topics
has_many :perf_types
has_many :students, :through => :perf_types
mount_uploader :qimage, QimageUploader
mount_uploader :aimage, AimageUploader
end
<file_sep>json.array!(@perf_types) do |perf_type|
json.extract! perf_type, :id, :ps, :pt, :as, :cq, :po, :io, :db, :question_id, :student_id
json.url perf_type_url(perf_type, format: :json)
end
<file_sep>class Fabrication::Generator::Base
def self.supports?(_klass); true end
def build(attributes=[], callbacks={})
process_attributes(attributes)
if callbacks[:initialize_with]
build_instance_with_constructor_override(callbacks[:initialize_with])
elsif callbacks[:on_init]
build_instance_with_init_callback(callbacks[:on_init])
else
build_instance
end
execute_callbacks(callbacks[:after_build])
_instance
end
def create(attributes=[], callbacks=[])
build(attributes, callbacks)
execute_callbacks(callbacks[:before_validation])
validate_instance
execute_callbacks(callbacks[:after_validation])
execute_callbacks(callbacks[:before_save])
execute_callbacks(callbacks[:before_create])
persist
execute_callbacks(callbacks[:after_create])
execute_callbacks(callbacks[:after_save])
_instance
end
def execute_callbacks(callbacks)
callbacks.each { |callback| _instance.instance_exec(_instance, _transient_attributes, &callback) } if callbacks
end
def to_params(attributes=[])
process_attributes(attributes)
_attributes.respond_to?(:with_indifferent_access) ? _attributes.with_indifferent_access : _attributes
end
def to_hash(attributes=[], callbacks=[])
process_attributes(attributes)
Fabrication::Support.hash_class.new.tap do |hash|
_attributes.map do |name, value|
if value && value.respond_to?(:id)
hash["#{name}_id"] = value.id
else
hash[name] = value
end
end
end
end
def build_instance_with_constructor_override(callback)
self._instance = instance_eval &callback
set_attributes
end
def build_instance_with_init_callback(callback)
self._instance = _klass.new(*callback.call)
set_attributes
end
def build_instance
self._instance = _klass.new
set_attributes
end
def set_attributes
_attributes.each do |k,v|
_instance.send("#{k}=", v)
end
end
def initialize(klass)
self._klass = klass
end
def method_missing(method_name, *args, &block)
_attributes[method_name] || super
end
def validate_instance; end
protected
attr_accessor :_klass, :_instance, :_transient_attributes
def _attributes
@_attributes ||= {}
end
def persist
_instance.save! if _instance.respond_to?(:save!)
end
def post_initialize; end
def process_attributes(attributes)
self._transient_attributes = Hash.new
attributes.each do |attribute|
_attributes[attribute.name] = attribute.processed_value(_attributes)
_transient_attributes[attribute.name] = _attributes[attribute.name] if attribute.transient?
end
_attributes.reject! { |k| _transient_attributes.keys.include?(k) }
end
end
<file_sep>class CreatePerfTypes < ActiveRecord::Migration
def change
create_table :perf_types do |t|
t.integer :ps
t.integer :pt
t.integer :as
t.integer :cq
t.integer :po
t.integer :io
t.integer :db
t.references :question, index: true
t.references :student, index: true
t.timestamps
end
end
end
<file_sep>class AddLevelToTopic < ActiveRecord::Migration
def change
add_column :topics, :lev1, :boolean
add_column :topics, :lev2, :boolean
end
end
<file_sep>json.extract! @student, :id, :lname, :fname, :clsname, :grade, :genderf, :created_at, :updated_at
<file_sep>module Fabrication
module Config
extend self
def configure; yield self end
def reset_defaults
@fabricator_path =
@path_prefix =
@active_support =
@sequence_start =
nil
end
def fabricator_path
@fabricator_path ||= ['test/fabricators', 'spec/fabricators']
end
alias fabricator_paths fabricator_path
def fabricator_dir
puts "DEPRECATION WARNING: Fabrication::Config.fabricator_dir has been replaced by Fabrication::Config.fabricator_path"
fabricator_path
end
def fabricator_path=(folders)
@fabricator_path = (Array.new << folders).flatten
end
def fabricator_dir=(folders)
puts "DEPRECATION WARNING: Fabrication::Config.fabricator_dir has been replaced by Fabrication::Config.fabricator_path"
fabricator_path = folders
end
attr_writer :sequence_start
def sequence_start; @sequence_start ||= 0 end
def path_prefix=(folders)
@path_prefix = (Array.new << folders).flatten
end
def path_prefix
@path_prefix ||= [defined?(Rails) ? Rails.root : "."]
end
alias path_prefixes path_prefix
attr_writer :register_with_steps
def register_with_steps?; @register_with_steps end
end
end
<file_sep>json.extract! @topic, :id, :topicName, :comments, :created_at, :updated_at
<file_sep>require 'test_helper'
class PerfTypesControllerTest < ActionController::TestCase
setup do
@perf_type = perf_types(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:perf_types)
end
test "should get new" do
get :new
assert_response :success
end
test "should create perf_type" do
assert_difference('PerfType.count') do
post :create, perf_type: { as: @perf_type.as, cq: @perf_type.cq, db: @perf_type.db, io: @perf_type.io, po: @perf_type.po, ps: @perf_type.ps, pt: @perf_type.pt, question_id: @perf_type.question_id, student_id: @perf_type.student_id }
end
assert_redirected_to perf_type_path(assigns(:perf_type))
end
test "should show perf_type" do
get :show, id: @perf_type
assert_response :success
end
test "should get edit" do
get :edit, id: @perf_type
assert_response :success
end
test "should update perf_type" do
patch :update, id: @perf_type, perf_type: { as: @perf_type.as, cq: @perf_type.cq, db: @perf_type.db, io: @perf_type.io, po: @perf_type.po, ps: @perf_type.ps, pt: @perf_type.pt, question_id: @perf_type.question_id, student_id: @perf_type.student_id }
assert_redirected_to perf_type_path(assigns(:perf_type))
end
test "should destroy perf_type" do
assert_difference('PerfType.count', -1) do
delete :destroy, id: @perf_type
end
assert_redirected_to perf_types_path
end
end
<file_sep>class CreateQtJoinTable < ActiveRecord::Migration
def change
create_join_table :questions, :topics do |t|
#t.integer :question_id
#t.integer :topic_id
# t.index [:question_id, :topic_id]
# t.index [:topic_id, :question_id]
end
end
end
<file_sep>require 'singleton'
class Fabrication::Schematic::Manager
include Singleton
def preinitialize
@initializing = true
clear
end
def initializing?; @initializing end
def schematics
@schematics ||= {}
end
def clear; schematics.clear end
def empty?; schematics.empty? end
def freeze
@initializing = false
end
def register(name, options, &block)
name = name.to_sym
raise_if_registered(name)
store(name, Array(options.delete(:aliases)), options, &block)
end
def [](name)
schematics[name.to_sym]
end
def build_stack
@build_stack ||= []
end
def to_params_stack
@to_params_stack ||= []
end
def load_definitions
preinitialize
Fabrication::Config.path_prefixes.each do |prefix|
Fabrication::Config.fabricator_paths.each do |folder|
Dir.glob(File.join(prefix, folder, '**', '*.rb')).sort.each do |file|
load file
end
end
end
rescue Exception => e
raise e
ensure
freeze
end
protected
def raise_if_registered(name)
(raise Fabrication::DuplicateFabricatorError, name) if self[name]
end
def store(name, aliases, options, &block)
schematic = schematics[name] = schematic_for(name, options, &block)
aliases.each { |as| schematics[as.to_sym] = schematic }
end
def resolve_class(name, parent, options)
Fabrication::Support.class_for(
options[:class_name] ||
(parent && parent.klass) ||
options[:from] ||
name
)
end
def schematic_for(name, options, &block)
parent = self[options[:from].to_s] if options[:from]
klass = resolve_class(name, parent, options)
if parent
parent.merge(&block).tap { |s| s.klass = klass }
else
Fabrication::Schematic::Definition.new(klass, &block)
end
end
end
<file_sep>To do:
7) save question goes to list rather than show
13) add difficulty rating to question
18) add a 'links to questions' field holding an array
20) clean up bootstrap css files - Joe
23) rspec test suite
26) admin can manage users
28) put signin info in navbar - Joe
29) add models for class and student - class has students
30) add search line for topics
31) list of questions containing topic
32) add search page for questions
33) full featured multi part search within questions
34) add subtopics to topics
35) crashes on last problem of page when updated (looking for non-existent next?)
36) back button stays on level of current problem
37) new problem defaults to highest page of current level
38) topics are assigned to a level
39) topic choices displayed at problem creation time are filtered by level
40) two difficulty values for each question (teacher/student)
41) keep level on 'edit next' even if different number of problems on each page
42) 'next' button on edit question needs to know about levels
Done:
1) commas between topic output in show view - done 7/13/2014
2) date created and date modified in show view - done 7/13/2014
3) twitter bootstrap - begun 7/11/14
4) devise - basuc setup 7/24/14
5) monospaced font in show question - done 7/30/14
6) default question and page number for new questions - done 7/20/14
8) filter question list output by page, topic, etc. - done (basic ransack) 7/28/14
9) list #of pages having each topic in topic view - done 7/11/14
10) facility to upload files - done 7/14/14
11) show # of files uploaded -done 7/23/14
14) add search function in menu bar - done (basic ransack) 7/28/14
15) button to remove graphic - done 7/23/14
16) devise hide answers if not signed in - done 7/26/14
17) devise security - admin, teacher full view - guests, students limited view - done 7/31/14
19) add teacher role to devise - done 8/1/14
25) flash messages don't work - fixed 8/3/14
12) ability to display full image instead of thumbnail - done
21) add sorting id field that is calculated from page and num - done
22) hide image display when no image - done
24) put show/answer into a bordered box - done
27) add level (which course) - done
answer graphs to be added - 16.2, 16.4, 18.1
<file_sep>class PerfType < ActiveRecord::Base
belongs_to :question
belongs_to :student
end
<file_sep>require 'spec_helper'
describe HighVoltage::Constraints::RootRoute, '.matches?' do
it 'returns true when the view file exists' do
request = double(path: 'index')
Dir.stub(:glob).and_return(['about.html.erb'])
result = HighVoltage::Constraints::RootRoute.matches?(request)
expect(result).to be_true
end
it 'returns false when the view files does not exist' do
request = double(path: 'index')
File.stub(:glob).and_return([])
result = HighVoltage::Constraints::RootRoute.matches?(request)
expect(result).to be_false
end
end
<file_sep>Dummy::Application.config.secret_key_base = '<KEY>'
<file_sep>require 'spec_helper'
describe HighVoltage::PageFinder do
it 'produces the name of an existing template' do
expect(find('existing')).to eq 'pages/existing'
end
it 'produces the name of a nested template' do
expect(find('dir/nested')).to eq 'pages/dir/nested'
end
it 'uses a custom content path' do
with_content_path('other_pages/') do
expect(find('also_exists')).to eq 'other_pages/also_exists'
end
end
it 'exposes the content path' do
with_content_path('another_thing/') do
expect(page_finder.content_path).to eq 'another_thing/'
end
end
it 'provides the page_id' do
subclass = Class.new(HighVoltage::PageFinder) do
def page_name
"the page is #{page_id}"
end
end
expect(subclass.new('sweet page').page_name).to eq 'the page is sweet page'
end
private
def find(page_id)
page_finder(page_id).find
end
def page_finder(page_id = 'whatever')
HighVoltage::PageFinder.new(page_id)
end
def with_content_path(path)
original_content_path = HighVoltage.content_path
HighVoltage.content_path = path
yield
HighVoltage.content_path = original_content_path
end
end
<file_sep>class QuestionsController < ApplicationController
before_action :set_question, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, :except => [:show, :index, :search]
load_and_authorize_resource
def search
end
# GET /questions
# GET /questions.json
def index
if @cur_page.nil?
cp = Question.find_by_num("-1")
if cp.nil?
@cur_page = 1
else
@cur_page = cp.page.abs
end
end
if @cur_level.nil?
cp = Question.find_by_num("-1")
if cp.nil?
@cur_level = 1
else
@cur_level = cp.level
end
end
@q = Question.search(params[:q])
@q.page_eq = @cur_page unless params[:q]
@q.level_eq = @cur_level unless params[:q]
@questions = @q.result(distinct: true)
end
# GET /questions/1
# GET /questions/1.json
def show
end
# GET /questions/new
def new
@question = Question.new
end
# GET /questions/1/edit
def edit
end
# POST /questions
# POST /questions.json
def create
@question = Question.new(question_params)
respond_to do |format|
if @question.save
@nextnum = @question.num + 1
format.html { redirect_to @question, notice: 'Question was successfully created.' }
format.json { render action: 'index', status: :created, location: @question }
else
format.html { render action: 'new' }
format.json { render json: @question.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /questions/1
# PATCH/PUT /questions/1.json
def update
params[:question][:topic_ids] ||=[]
respond_to do |format|
if @question.update(question_params)
format.html { redirect_to @question, notice: 'Question was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @question.errors, status: :unprocessable_entity }
end
end
end
# DELETE /questions/1
# DELETE /questions/1.json
def destroy
@question.destroy
respond_to do |format|
format.html { redirect_to questions_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_question
@question = Question.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def question_params
params.require(:question).permit(:num, :page, :level, :qtext, :shortAnswer, :answer, :notes, :presenter1, :presenter2,
:qimage, :remove_qimage, :aimage, :remove_aimage, {:topic_ids => []}, :page_cont)
end
end
<file_sep>class Fabricate
def self.times(count, name, overrides={}, &block)
count.times.map { Fabricate(name, overrides, &block) }
end
def self.build_times(count, name, overrides={}, &block)
count.times.map { Fabricate.build(name, overrides, &block) }
end
def self.attributes_for(name, overrides={}, &block)
fail_if_initializing(name)
schematic(name).to_attributes(overrides, &block)
end
def self.to_params(name, overrides={}, &block)
fail_if_initializing(name)
schematic(name).to_params(overrides, &block)
end
def self.build(name, overrides={}, &block)
fail_if_initializing(name)
schematic(name).build(overrides, &block).tap do |object|
Fabrication::Cucumber::Fabrications[name] = object if Fabrication::Config.register_with_steps?
end
end
def self.create(name, overrides={}, &block)
fail_if_initializing(name)
schematic(name).fabricate(overrides, &block)
end
def self.sequence(name=Fabrication::Sequencer::DEFAULT, start=nil, &block)
Fabrication::Sequencer.sequence(name, start, &block)
end
def self.schematic(name)
Fabrication.manager.load_definitions if Fabrication.manager.empty?
Fabrication.manager[name] || raise(Fabrication::UnknownFabricatorError.new(name))
end
private
def self.fail_if_initializing(name)
raise Fabrication::MisplacedFabricateError.new(name) if Fabrication.manager.initializing?
end
end
<file_sep>class Student < ActiveRecord::Base
has_many :perf_types
has_many :questions, :through => :perf_types
end
<file_sep># encoding: utf-8
require 'rubygems'
require 'bundler/setup'
require 'bundler/gem_tasks'
require 'rake'
require 'rspec/core/rake_task'
require 'appraisal'
RSpec::Core::RakeTask.new(:spec)
desc 'Default'
task :default => [:all]
desc 'Test the engine under all supported Rails versions'
task all: ['appraisal:install'] do |t|
exec 'rake appraisal spec'
end
<file_sep>class Fabrication::Schematic::Attribute
attr_accessor :klass, :name, :params, :value
def initialize(klass, name, value, params={}, &block)
self.klass = klass
self.name = name
self.params = params
self.value = value.nil? ? block : value
end
def params
@params ||= {}
end
def transient!
params[:transient] = true
end
def transient?
params[:transient]
end
def processed_value(processed_attributes)
if process_count
(1..process_count).map { |i| execute(processed_attributes, i, &value) }
elsif value_proc?
execute(processed_attributes, &value)
else
value
end
end
def value_static?; !value_proc? end
def value_proc?; Proc === value end
private
def execute(*args, &block)
Fabrication::Schematic::Runner.new(klass).instance_exec(*args, &block)
end
def process_count
count || rand
end
def count
params[:count]
end
def rand
Kernel.rand((1..params[:rand])) if params[:rand]
end
end
<file_sep>json.array!(@students) do |student|
json.extract! student, :id, :lname, :fname, :clsname, :grade, :genderf
json.url student_url(student, format: :json)
end
<file_sep>require 'test_helper'
class PerfTypesHelperTest < ActionView::TestCase
end
<file_sep>class PerfTypesController < ApplicationController
before_action :set_perf_type, only: [:show, :edit, :update, :destroy]
# GET /perf_types
# GET /perf_types.json
def index
@perf_types = PerfType.all
end
# GET /perf_types/1
# GET /perf_types/1.json
def show
end
# GET /perf_types/new
def new
@perf_type = PerfType.new
end
# GET /perf_types/1/edit
def edit
end
# POST /perf_types
# POST /perf_types.json
def create
@perf_type = PerfType.new(perf_type_params)
respond_to do |format|
if @perf_type.save
format.html { redirect_to @perf_type, notice: 'Perf type was successfully created.' }
format.json { render action: 'show', status: :created, location: @perf_type }
else
format.html { render action: 'new' }
format.json { render json: @perf_type.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /perf_types/1
# PATCH/PUT /perf_types/1.json
def update
respond_to do |format|
if @perf_type.update(perf_type_params)
format.html { redirect_to @perf_type, notice: 'Perf type was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @perf_type.errors, status: :unprocessable_entity }
end
end
end
# DELETE /perf_types/1
# DELETE /perf_types/1.json
def destroy
@perf_type.destroy
respond_to do |format|
format.html { redirect_to perf_types_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_perf_type
@perf_type = PerfType.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def perf_type_params
params.require(:perf_type).permit(:ps, :pt, :as, :cq, :po, :io, :db, :question_id, :student_id)
end
end
<file_sep>json.extract! @question, :id, :num, :page, :qtext, :answer, :notes, :created_at, :updated_at
<file_sep>class Fabrication::Schematic::Definition
GENERATORS = [
Fabrication::Generator::ActiveRecord,
Fabrication::Generator::DataMapper,
Fabrication::Generator::Sequel,
Fabrication::Generator::Mongoid,
Fabrication::Generator::Base
]
attr_accessor :klass
def initialize(klass, &block)
self.klass = klass
process_block(&block)
end
def process_block(&block)
Fabrication::Schematic::Evaluator.new.process(self, &block) if block_given?
end
def attribute(name)
attributes.detect { |a| a.name == name }
end
def append_or_update_attribute(attribute_name, value, params={}, &block)
attribute = Fabrication::Schematic::Attribute.new(klass, attribute_name, value, params, &block)
if index = attributes.index { |a| a.name == attribute.name }
attribute.transient! if attributes[index].transient?
attributes[index] = attribute
else
attributes << attribute
end
end
attr_writer :attributes
def attributes
@attributes ||= []
end
attr_writer :callbacks
def callbacks
@callbacks ||= {}
end
def generator
@generator ||= GENERATORS.detect { |gen| gen.supports?(klass) }
end
def sorted_attributes
attributes.select(&:value_static?) + attributes.select(&:value_proc?)
end
def build(overrides={}, &block)
if Fabrication.manager.to_params_stack.any?
to_params(overrides, &block)
else
begin
Fabrication.manager.build_stack << self
merge(overrides, &block).instance_eval do
generator.new(klass).build(sorted_attributes, callbacks)
end
ensure
Fabrication.manager.build_stack.pop
end
end
end
def fabricate(overrides={}, &block)
if Fabrication.manager.build_stack.any?
build(overrides, &block)
elsif Fabrication.manager.to_params_stack.any?
to_params(overrides, &block)
else
merge(overrides, &block).instance_eval do
generator.new(klass).create(sorted_attributes, callbacks)
end
end
end
def to_params(overrides={}, &block)
Fabrication.manager.to_params_stack << self
merge(overrides, &block).instance_eval do
generator.new(klass).to_params(sorted_attributes)
end
ensure
Fabrication.manager.to_params_stack.pop
end
def to_attributes(overrides={}, &block)
merge(overrides, &block).instance_eval do
generator.new(klass).to_hash(sorted_attributes, callbacks)
end
end
def initialize_copy(original)
self.callbacks = {}
original.callbacks.each do |type, callbacks|
self.callbacks[type] = callbacks.clone
end
self.attributes = original.attributes.clone
end
def merge(overrides={}, &block)
clone.tap do |definition|
definition.process_block(&block)
overrides.each do |name, value|
definition.append_or_update_attribute(name.to_sym, value)
end
end
end
def generate_value(name, params)
if params[:count]
name = Fabrication::Support.singularize(name.to_s)
proc { Fabricate.build(params[:fabricator] || name) }
else
proc { Fabricate(params[:fabricator] || name) }
end
end
end
<file_sep>module Fabrication
VERSION = '2.11.3'
end
<file_sep>class AddShortAnswerPresenterLevelToQuestion < ActiveRecord::Migration
def change
add_column :questions, :shortAnswer, :string
add_column :questions, :presenter1, :string
add_column :questions, :presenter2, :string
add_column :questions, :level, :integer
end
end
<file_sep>New for 2.2.0:
+ Deprecate caching because page and action caching was removed in Rails 4
+ Refactor test suite to use rspec `expect` syntax consistently.
+ Added Rails 4.1 to test suite.
+ Remove Ruby 1.9.2 from test suite.
+ Remove Capybara from test suite.
+ Support dependency injection for Rails engine to define routes on
New for 2.1.0:
+ Extract configuration options into a module
+ Add ability to configure whether layout is cached with action_caching
+ Add ability to configure a `home_page` for root routing to High Voltage
+ Update README with new block style config
New for 2.0.0:
+ Extract PagesController into a module
+ Update README with module usage instructions
New for 1.2.4:
+ Add page and action caching
+ Remove redundant link style `page_path(id: 'about')` from README
+ Clean up Appraisals for Travis-CI
+ Remove Ruby 1.8.7 from test suite
New for 1.2.3:
+ Updates for Rails 4 compatibility.
+ Fix for Rails 4 circular dependency error.
+ Add ability to load High Voltage outside of rails. Require `attribute_accessors`
New for 1.2.2:
+ Bug fix for RootRoute constraint. Support haml, slim, etc.
+ README updated for root routes.
New for 1.2.1:
+ Ability to disable HighVoltage routes.
+ New RootRoute constraint.
+ Updated README, with new TravisCI url.
<file_sep>json.array!(@questions) do |question|
json.extract! question, :id, :num, :page, :qtext, :answer, :notes
json.url question_url(question, format: :json)
end
<file_sep>class AddPblImageToQuestions < ActiveRecord::Migration
def change
add_column :questions, :qimage, :string
add_column :questions, :aimage, :string
end
end
<file_sep>class Topic < ActiveRecord::Base
has_and_belongs_to_many :questions
alias_attribute :topicname, :topicName
end
<file_sep>module Fabrication
module Syntax
# Extends Fabrication to provide make/make! class methods, which are
# shortcuts for Fabricate.build/Fabricate.
#
# Usage:
#
# require 'fabrication/syntax/make'
#
# User.make(:name => 'Johnny')
#
#
module Make
def make(*args, &block)
overrides = Fabrication::Support.extract_options!(args)
klass = name.underscore.to_sym
fabricator_name = args.first.is_a?(Symbol) ? "#{klass}_#{args.first}" : klass
Fabricate.build(fabricator_name, overrides, &block)
end
def make!(*args, &block)
overrides = Fabrication::Support.extract_options!(args)
klass = name.underscore.to_sym
fabricator_name = args.first.is_a?(Symbol) ? "#{klass}_#{args.first}" : klass
Fabricate(fabricator_name, overrides, &block)
end
end
end
end
Object.extend Fabrication::Syntax::Make
<file_sep>class CreateQuestions < ActiveRecord::Migration
def change
create_table :questions do |t|
t.integer :num
t.integer :page
t.text :qtext
t.text :notes
t.timestamps
end
end
end
<file_sep>class AddInitsToStudent < ActiveRecord::Migration
def change
add_column :students, :inits, :string
end
end
<file_sep>ENV['RAILS_ENV'] = 'test'
require File.expand_path('../dummy/config/environment.rb', __FILE__)
require 'pry'
require 'rails/test_help'
require 'rspec/expectations'
require 'rspec/rails'
Rails.backtrace_cleaner.remove_silencers!
Dir[File.dirname(__FILE__) + '/support/**/*.rb'].each { |file| require file }
RSpec.configure do |config|
config.after(:each) do
HighVoltage.set_default_configuration
Rails.application.reload_routes!
end
config.expect_with :rspec do |c|
c.syntax = :expect
end
config.include RSpec::Matchers
config.mock_with :rspec
config.order = 'random'
end
<file_sep>class Fabrication::Generator::Sequel < Fabrication::Generator::Base
def initialize(klass)
super
load_instance_hooks
end
def self.supports?(klass)
defined?(Sequel) && klass.ancestors.include?(Sequel::Model)
end
def set_attributes
_attributes.each do |key, value|
if (reflection = _klass.association_reflections[key]) && value.is_a?(Array)
_instance.associations[key] = value
_instance.after_save_hook do
value.each { |o| _instance.send(reflection.add_method, o) }
end
else
_instance.send("#{key}=", value)
end
end
end
def persist
_instance.save
end
def validate_instance
_instance.valid?
end
private
def load_instance_hooks
klass = _klass.respond_to?(:cti_base_model) ? _klass.cti_base_model : _klass
klass.plugin :instance_hooks unless klass.new.respond_to? :after_save_hook
end
end
| 9fbd2be15e3c3b166b97fbc4c5ff4f5bc663f319 | [
"Text",
"RDoc",
"Ruby",
"Markdown"
] | 41 | Ruby | elindow/PBL_New | 7df28c38db1d35e943b2ba2cae1ad1cd7d374eb2 | 57277db571eafed4bb28ee6b2b664defe94f5915 |
refs/heads/master | <repo_name>Pluxopolis/plxMySlippry<file_sep>/lang/fr.php
<?php
$LANG = array(
# admin.php
'L_PICTURE' => 'Image',
'L_INFORMATION' => 'Informations',
'L_ACTIVE' => 'Active',
'L_ORDER' => 'Ordre',
'L_NEW_IMAGE' => 'Nouvelle image',
'L_UPDATE' => 'Modifier la liste des images',
'L_URL_IMAGE' => 'Url de l\'image',
'L_ONCLICK_IMAGE' => 'Lien à ouvrir en cliquant sur l\'image (optionnel)',
'L_DESCRIPTION_IMAGE' => 'Description de l\'image',
'L_DELETE' => 'Supprimer du diaporama',
# config.php
'L_JQUERY' => 'Utiliser la librairie jQuery du plugin ?',
'L_YES' => 'Oui',
'L_NO' => 'Non',
'L_TRANSITION' => 'Effect de transition',
'L_SPEED' => 'Vitesse de défilement en ms (ex:800)',
'L_MAXWIDTH' => 'Largeur maxi du diaporama (en px)',
'L_OPEN_IN_NEW_WINDOW' => 'Ouvrir les liens des images du diaporama dans une nouvelle fenêtre',
'L_SAVE' => 'Enregistrer',
);
?><file_sep>/lang/en.php
<?php
$LANG = array(
'L_PICTURE' => 'Picture',
'L_INFORMATION' => 'Information',
'L_ACTIVE' => 'Active',
'L_ORDER' => 'Ordrer',
'L_NEW_IMAGE' => 'New image',
'L_UPDATE' => 'Update image list',
'L_URL_IMAGE' => 'Image url',
'L_ONCLICK_IMAGE' => 'Open link after onclick image (optional)',
'L_DESCRIPTION_IMAGE' => 'Image description',
'L_DELETE' => 'Remove from slideshow',
# config.php
'L_JQUERY' => 'Load jQuery library?',
'L_YES' => 'Yes',
'L_NO' => 'No',
'L_TRANSITION' => 'Effect transition',
'L_SPEED' => 'The time the transition takes to complete in ms (ex:800)',
'L_MAXWIDTH' => 'Diaporam max width (in px)',
'L_OPEN_IN_NEW_WINDOW' => 'Open clicked image in a new window',
'L_SAVE' => 'Enregistrer',
);
?><file_sep>/lang/en-help.php
<?php if(!defined('PLX_ROOT')) exit; ?>
<pre style="font-size:12px">
Activation du plugin
- aller dans le menu Paramètres > Plugins
- cocher le plugin MySlippry et dans le déroulant "Pour la sélection", sélectionner le menu "Activer"
Configuration du diaporama MySlippry
- Aller dans le menu Paramètres > Plugins, et cliquer sur le lien Configuration du plugin MySlippry
Pour ajouter des images au diaporama
- aller dans le gestionnaire des médias
- cocher les images à ajouter dans le diaporama
- dans le déroulant "Pour la sélection", sélectionner le menu MySlippry > Ajouter au diaporama
Activation et personnalisation des images du diaporama
- allez dans le menu MySlippry (dans le bandeau des menus de l'administration)
- renseigner les champs titre et description des images
- activer l'affichage en choisissant la valeur "Oui" dans la colonne "Active"
- cliquer sur le bouton "Modifier la liste des images" pour enregistrer les modifications
Affichage du diaporama sur la page d'accueil de son site
- éditer le fichier header.php de son theme
- ajouter la ligne suivante à l'endroit où vous souhaitez afficher le diaporama
<div style="color:#000;padding:0 10px 15px 10px;border:1px solid #dedede">
<?php echo plxUtils::strCheck('<?php eval($plxShow->callHook("MySlippry")) ?>') ?>
</div>
Affichage du diaporama dans une page statique
- éditer le contenu d'une page statique et allant dans la gestion des pages statiques: menu "Pages statiques" dans l'administration
- ajouter les lignes suivantes à l'endroit où vous souhaitez afficher le diaporama
<div style="color:#000;padding:0 10px 15px 10px;border:1px solid #dedede">
<?php
echo plxUtils::strCheck('
<?php
global $plxShow;
eval($plxShow->callHook("MySlippry"));
?>
');
?>
</div>
<strong>Slippry</strong>: jQuery Image Slider Plugin.
<a href="http://slippry.com/">http://slippry.com/</a>
</pre><file_sep>/plxMySlippry.php
<?php
/**
* Plugin plxMySlippry
* @author <NAME>
**/
include(dirname(__FILE__).'/lib/class.plx.slippry.php');
class plxMySlippry extends plxPlugin {
public $slippry = null; # objet slippry
public function __construct($default_lang) {
# appel du constructeur de la classe plxPlugin (obligatoire)
parent::__construct($default_lang);
# droits pour accèder à la page config.php et admin.php du plugin
$this->setConfigProfil(PROFIL_ADMIN);
$this->setAdminProfil(PROFIL_ADMIN);
$this->addHook('AdminMediasTop', 'AdminMediasTop');
$this->addHook('AdminMediasPrepend', 'AdminMediasPrepend');
$this->slippry = new slippry($default_lang);
$this->slippry->getSlides();
# déclaration des hooks
if($this->slippry->aSlides) {
$this->addHook('ThemeEndHead', 'ThemeEndHead');
$this->addHook('ThemeEndBody', 'ThemeEndBody');
$this->addHook('MySlippry', 'MySlippry');
}
}
public function AdminMediasTop() {
echo '<?php
$arr = array("MySlippry" => array("slippry_add" => "Ajouter au diaporama"));
$selectionList = array_merge($selectionList, $arr);
?>';
}
public function AdminMediasPrepend() {
if(isset($_POST['selection']) AND $_POST['selection']=='slippry_add' AND isset($_POST['idFile'])) {
$this->slippry->editSlides($_POST);
header('Location: medias.php');
exit;
}
}
public function MySlippry() {
$s = "";
foreach($this->slippry->aSlides as $i => $slide) {
if($slide['active']) {
if($slide['onclick']!='') {
$href = $slide['onclick'];
$onclick = $this->getParam('openwin') ? 'window.open(this, \'_blank\');return false' : '';
} else {
$href = '#slide'.intval($i);
$onclick = 'return false;';
}
$s .= '<li><a onclick="'.$onclick.'" href="'.$href.'"><img src="'.plxUtils::strCheck($slide['url']).'" alt="'.plxUtils::strCheck($slide['description']).'" /></a></li>'."\n";
}
}
if($s!="") {
echo '<div class="sy-box" />'."\n";
echo '<ul id="slippry" class="sy-list">'."\n".$s."</ul>\n";
echo "</div>";
}
}
public function ThemeEndHead() {
echo '<link rel="stylesheet" href="'.PLX_PLUGINS.'plxMySlippry/slippry/slippry.css" media="screen" />';
if(intval($this->getParam('maxwidth'))>0) {
echo '<style>div.sy-box { max-width: '.$this->getParam('maxwidth').'px !important;</style>'."\n";
}
}
public function ThemeEndBody() {
if($this->getParam('jquery')) {
echo "\n".'<script>if (typeof jQuery == "undefined") { document.write(\'<script src="'.PLX_PLUGINS.'plxMySlippry\/slippry\/jquery-3.1.1.min.js"><\/script>\'); }</script>';
}
echo '<script src="'.PLX_PLUGINS.'plxMySlippry/slippry/slippry.min.js"></script>'."\n";
echo '
<script>
$(function() {
var slippry = $("#slippry").slippry({
transition: "'.$this->getParam('transition').'",
speed: '.$this->getParam('speed').',
})});
</script>
';
}
}
?><file_sep>/config.php
<?php if(!defined('PLX_ROOT')) exit; ?>
<?php
# Control du token du formulaire
plxToken::validateFormToken($_POST);
if(!empty($_POST)) {
$plxPlugin->setParam('jquery', $_POST['jquery'], 'numeric');
$plxPlugin->setParam('speed', $_POST['speed'], 'numeric');
$plxPlugin->setParam('transition', $_POST['transition'], 'string');
$plxPlugin->setParam('maxwidth', $_POST['maxwidth'], 'numeric');
$plxPlugin->setParam('openwin', $_POST['openwin'], 'numeric');
$plxPlugin->saveParams();
header('Location: parametres_plugin.php?p=plxMySlippry');
exit;
}
$parms = array();
$parms['jquery'] = $plxPlugin->getParam('jquery')!='' ? $plxPlugin->getParam('jquery') : true;
$parms['speed'] = $plxPlugin->getParam('speed')!='' ? $plxPlugin->getParam('speed') : '800';
$parms['transition'] = $plxPlugin->getParam('transition')!='' ? $plxPlugin->getParam('transition') : 'fade';
$parms['maxwidth'] = $plxPlugin->getParam('maxwidth')!='' ? $plxPlugin->getParam('maxwidth') : '';
$parms['openwin'] = $plxPlugin->getParam('openwin')!='' ? $plxPlugin->getParam('openwin') : false;
?>
<style>
form.inline-form label {
width: 300px;
}
</style>
<form class="inline-form" action="parametres_plugin.php?p=plxMySlippry" method="post" id="form_plxMySlippry">
<fieldset>
<p>
<label for="id_jquery"><?php $plxPlugin->lang('L_JQUERY') ?></label>
<?php plxUtils::printSelect('jquery',array('1'=>$plxPlugin->getLang('L_YES'),'0'=>$plxPlugin->getLang('L_NO')),$parms['jquery']) ?>
</p>
<p>
<label for="id_speed"><?php $plxPlugin->lang('L_SPEED') ?></label>
<?php plxUtils::printInput('speed',$parms['speed'],'text','4-4') ?>
</p>
<p>
<label for="id_transition"><?php $plxPlugin->lang('L_TRANSITION') ?></label>
<?php plxUtils::printSelect('transition',array('fade'=>'fade','horizontal'=>'horizontal','vertical'=>'vertical','kenburns'=>'kenburns'),$parms['transition']) ?>
</p>
<p>
<label for="id_maxwidth"><?php $plxPlugin->lang('L_MAXWIDTH') ?></label>
<?php plxUtils::printInput('maxwidth',$parms['maxwidth'],'text','4-4') ?>
</p>
<p>
<label for="id_jquery"><?php $plxPlugin->lang('L_OPEN_IN_NEW_WINDOW') ?></label>
<?php plxUtils::printSelect('openwin',array('1'=>$plxPlugin->getLang('L_YES'),'0'=>$plxPlugin->getLang('L_NO')),$parms['openwin']) ?>
</p>
<p class="in-action-bar">
<?php echo plxToken::getTokenPostMethod() ?>
<input type="submit" name="submit" value="<?php $plxPlugin->lang('L_SAVE') ?>" />
</p>
</fieldset>
</form> | b884f6d65371e52453ab9168a754c700fe0ff0d7 | [
"PHP"
] | 5 | PHP | Pluxopolis/plxMySlippry | 0856dce58c2417c2edc0ad00fb508314c582043a | 072f9a7019869751cd57330d0c6b7373276352b0 |
refs/heads/master | <repo_name>qifx/PictureAndVideoViewer<file_sep>/PictureAndVideoViewer/ContentViewController.swift
//
// PageViewController.swift
// PDFDemo
//
// Created by qifx on 16/4/12.
// Copyright © 2016年 qifx. All rights reserved.
//
import UIKit
import AVFoundation
protocol PageChangedDelegate: NSObjectProtocol {
func pageChangedTo(index: Int)
}
public class ContentViewController: UIViewController, UIScrollViewDelegate {
//setted data
var index: Int
public var si: SourceItem
weak var delegate: PictureViewerDelegate?
var scrollView: UIScrollView!
var mainView: UIView!
var iv: UIImageView?
var downloadingView: UIView?
var player: AVPlayer?
var playerLayer: AVPlayerLayer!
weak var pageChangedDelegate: PageChangedDelegate?
var showButtons: Bool = false
init(index: Int, si: SourceItem) {
self.index = index
self.si = si
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.black
if scrollView == nil {
scrollView = UIScrollView(frame: view.bounds)
scrollView.delegate = self
scrollView.scrollsToTop = false
scrollView.contentSize = CGSize(width: view.bounds.width, height: view.bounds.height)
scrollView.bounces = true
scrollView.bouncesZoom = true
scrollView.isPagingEnabled = true
scrollView.isScrollEnabled = false
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.isDirectionalLockEnabled = true
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 2.0
scrollView.zoomScale = 1.0
scrollView.backgroundColor = UIColor.black
view.addSubview(scrollView)
}
// Do any additional setup after loading the view.
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if mainView == nil {
mainView = UIView(frame: scrollView.bounds)
mainView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tapped(gesture:))))
mainView.center = scrollView.center
scrollView.addSubview(mainView)
}
if si.data != nil {
//show picture
iv = UIImageView(frame: scrollView.bounds)
iv!.contentMode = .scaleAspectFit
iv!.image = UIImage(data: si.data!)
mainView.addSubview(iv!)
} else if si.localUrl != nil {
player = AVPlayer(url: si.localUrl!)
playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = mainView.bounds
playerLayer.videoGravity = AVLayerVideoGravityResizeAspect
mainView.layer.addSublayer(playerLayer)
} else {
downloadingView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
downloadingView!.center = CGPoint(x: scrollView.center.x, y: scrollView.center.y)
downloadingView!.backgroundColor = UIColor.black
mainView.addSubview(downloadingView!)
let progress = KDCircularProgress(frame: downloadingView!.bounds)
progress.startAngle = -90
progress.progressThickness = 0.2
progress.trackThickness = 0.3
progress.clockwise = true
progress.gradientRotateSpeed = 2
progress.roundedCorners = true
progress.glowMode = .forward
progress.glowAmount = 0.9
progress.set(colors: UIColor.white)
progress.tag = 10086
downloadingView!.addSubview(progress)
}
}
override public func viewDidAppear(_ animated: Bool) {
pageChangedDelegate?.pageChangedTo(index: index)
if iv == nil && player == nil {
let progressName = Notification.Name.init(rawValue: "DownloadVideoProgress\(si.id)")
let endName = Notification.Name.init(rawValue: "DownloadVideoEnd\(si.id)")
let errorName = Notification.Name.init(rawValue: "DownloadVideoError\(si.id)")
NotificationCenter.default.addObserver(self, selector: #selector(self.updatePercent(noti:)), name: progressName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.downloadEnd), name: endName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.downloadError), name: errorName, object: nil)
delegate?.needDownloadSource(index: index, item: si, downloadProgressNotificationName: progressName, downloadEndNotificationName: endName, downloadErrorNotificationName: errorName)
} else if player != nil {
self.downloadingView?.removeFromSuperview()
self.downloadingView = nil
player?.play()
}
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
player?.pause()
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tapped(gesture: UITapGestureRecognizer) {
dismiss(animated: true, completion: nil)
}
func updatePercent(noti: Notification) {
guard let percent = noti.userInfo?["percent"] as? Double, let progressView = downloadingView?.viewWithTag(10086) as? KDCircularProgress else {
return
}
progressView.progress = percent
}
func downloadEnd() {
self.downloadingView?.removeFromSuperview()
self.downloadingView = nil
self.player = AVPlayer(url: self.si.localUrl!)
self.playerLayer = AVPlayerLayer(player: self.player)
self.playerLayer.frame = self.mainView.bounds
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect
self.mainView.layer.addSublayer(self.playerLayer)
self.player!.play()
}
func downloadError() {
let ac = UIAlertController(title: "Download end with error", message: "Can not download video from \(si.remoteUrl!)", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .cancel, handler: nil)
ac.addAction(ok)
present(ac, animated: true, completion: nil)
}
//UIScrollViewDelegate
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
if si.data != nil {
return mainView
} else {
return nil
}
}
public func scrollViewDidZoom(_ scrollView: UIScrollView) {
var centerX = scrollView.center.x
var centerY = scrollView.center.y
centerX = scrollView.contentSize.width > scrollView.frame.size.width ? scrollView.contentSize.width * 0.5 : centerX
centerY = scrollView.contentSize.height > scrollView.frame.size.height ? scrollView.contentSize.height * 0.5 : centerY
mainView.center = CGPoint(x: centerX, y: centerY)
}
}
<file_sep>/PictureAndVideoViewer/PictureViewerController.swift
//
// PageContainerViewController.swift
// PDFDemo
//
// Created by qifx on 16/4/12.
// Copyright © 2016年 qifx. All rights reserved.
//
import UIKit
public struct SourceItem {
public init(id: String, type: String, localUrl: URL?, remoteUrl: URL?, data: Data?) {
self.id = id
self.type = type
self.localUrl = localUrl
self.remoteUrl = remoteUrl
self.data = data
}
public var id: String
public var type: String
public var localUrl: URL?
public var remoteUrl: URL?
public var data: Data?
}
public protocol PictureViewerDelegate: class {
func needDownloadSource(index: Int, item: SourceItem, downloadProgressNotificationName: Notification.Name, downloadEndNotificationName: Notification.Name, downloadErrorNotificationName: Notification.Name)
}
public class PictureViewerController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIGestureRecognizerDelegate, PageChangedDelegate {
//setted data, video URL or UIImage Data
public var fileDic: Dictionary<Int, SourceItem>
public var currentFileIndex: Int
public weak var pictureViewerDelegate: PictureViewerDelegate?
/// Init
///
/// - Parameters:
/// - fileDic: video URL or UIImage Data
/// - currentFileIndex: current file index
public init(fileDic: Dictionary<Int, SourceItem>, currentFileIndex: Int) {
self.fileDic = fileDic
self.currentFileIndex = currentFileIndex
super.init(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal, options: nil)
}
required public init?(coder: NSCoder) {
self.fileDic = Dictionary<Int, SourceItem>()
self.currentFileIndex = 0
super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
}
override public func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
view.backgroundColor = UIColor.black
if viewControllers != nil && viewControllers!.count > 0 {
return
}
if let firstViewController = vcAtIndex(currentFileIndex) {
setViewControllers([firstViewController], direction: .forward, animated: true, completion: nil)
}
// Do any additional setup after loading the view.
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: PageChangedDelegate
func pageChangedTo(index: Int) {
currentFileIndex = index
}
//MARK: UIPageViewControllerDataSource
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if currentFileIndex == 0 {
return nil
}
return vcAtIndex(currentFileIndex-1)
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if currentFileIndex == (fileDic.count - 1) {
return nil
}
return vcAtIndex(currentFileIndex+1)
}
func vcAtIndex(_ index: Int) -> ContentViewController! {
let obj = fileDic[index]
let contentVC = ContentViewController(index: index, si: obj!)
contentVC.pageChangedDelegate = self
contentVC.delegate = pictureViewerDelegate
return contentVC
}
}
<file_sep>/README.md
# PictureAndVideoViewer
An iOS Framework for show pictures and videos in list<br/>
You should Know Two Object in the framework.<br/>
1.SourceItem<br/>
When init a ViewController, you should transfer some SourceItem to the new VC. It's a data struct.<br/>
2.PictureViewerDelegate<br/>
When the video not on device, the frame work tell you to download remote video by PictureViewerDelegate.
| 9d5485a30c356f0247048011d0caf73e6f6ef1b6 | [
"Swift",
"Markdown"
] | 3 | Swift | qifx/PictureAndVideoViewer | 326516dce68d86a740f6a6a7471984653df6f73b | 4695f5d490a6f2107de0ad3f2d2c7132aa00a138 |
refs/heads/master | <repo_name>550406066/js-<file_sep>/README.md
#js下拉框组件
>基本功能全部实现了,扩展功能提供一个自己的想法。
完成了下拉框的基本功能,兼容现代浏览器,数据是使用ajax请求的easy-mock的数据,可以动态搜索匹配,
因为不了解测试代码所以没有测试组件功能,使用console.time()测试了组件搜索用时,对于扩
展要求2中我的想法是:1.当用户输入停止时再进行匹配,设置一个搜索阈值。2.将后端的数据存储在LocalStorage中减少请求次数。
项目预览:





<file_sep>/js/index.js
var pullDown=function(){
this.html='<div class="main">\
<input type="text" id="makeEnter" class="makeEnter" placeholder="请选择或输入"/>\
<ul id="optionList" class="optionList">\
</ul>\
<div id="icon" class="icon iconfont icon-xiala pull-down-icon"></div>\
</div>'
this.TempArr = [];
this.ajaxUrl={
demoUrl:"https://easy-mock.com/mock/5b0d5a9d2179ff1c604e3bf3/scroll_copy_copy/"
}
}
pullDown.prototype={
getData:function(){
var _this=this
$.ajax({
type: "GET",
url:_this.ajaxUrl.demoUrl,
data:{},
dataType:"json",
success:function(data){
if(data.code==0){
var dataLenth=data.data
if(dataLenth.length!=0){
for(var i=0;i<dataLenth.length;i++){
$("#optionList").append(" <li>"+dataLenth[i].county+"</li>")
}
_this.bind();
}else{
}
}
console.log(data)
}
})
},
setfocus : function () {
$("#optionList").css({ "display": "block" });
},
setinput:function() {
var select = $("#optionList");
var TempArr=this.TempArr;
var makeEnterVal=$("#makeEnter").val()
select.html("");
console.time('setinput'); // 启动计时, 该时刻命名为 setinput (可以自定)
// ... 要执行的代码块
for (i = 0; i < TempArr.length; i++) {
//若找到以txt的内容开头的,添option
if (TempArr[i].substring(0, makeEnterVal.length).indexOf(makeEnterVal) == 0) {
len =makeEnterVal.length
var selectVal = TempArr[i].substr(0, len)
var option = $("<li></li>").html("<span class='selectVal'>" + selectVal + "</span>" + TempArr[i].substring(len, TempArr[i].length));
// var option = $("<li></li>").html("<em>"+TempArr[i]+"</em>");
// var option = $("<li></li>").text(TempArr[i]);
select.append(option);
console.timeEnd('setinput'); // 定时结束, 浏览器控制台将输出代码块的执行时间
}
}
if( $("#optionList").html()===""){
select.append("<span class='no-data'>未找到数据···</span>")
}
},
bind:function(){
var _this=this
$("#optionList li").each(function (index, el) {
_this.TempArr[index] = $(this).text();
});
$("body").off("click","#makeEnter").on("click","#makeEnter",function(){
_this.setfocus()
})
$("body").off("click","#icon").on("click","#icon",function(){
if( $("#optionList").css("display")=="block"){
$("#optionList").css({ "display": "none" })
}else{
$("#optionList").css({ "display": "block" });
}
})
$("body").off("click","#optionList li").on("click","#optionList li",function(){
$(this).parent().prev("#makeEnter").val($(this).text());
$("#optionList").css({ "display": "none" });
});
$("body").off("input","#makeEnter").on("input","#makeEnter",function(){
_this.setinput()
})
},
init:function(){
this.getData();
$("body").append(this.html)
}
}
var pullDown=new pullDown()
pullDown.init() | c33408a469f117298f3517a99eccd5b12c9641bd | [
"Markdown",
"JavaScript"
] | 2 | Markdown | 550406066/js- | 79ba910c595c7c7a861fdd346f48e606c80acc9c | b4008c9b1ec8ee498505752c5cb76766e7eabd25 |
refs/heads/master | <file_sep>import Serialport, { parsers } from 'serialport'
const serialport: typeof Serialport = (window as any).require('serialport')
const Delimiter: typeof parsers.Delimiter = (window as any).require('@serialport/parser-delimiter')
type CreateProps = {
path: string;
baud: number;
onOpen: () => void;
onClose: () => void;
onData: (data: string | Buffer) => void
}
export default class Serial {
sp: Serialport
onClose: () => void;
parser: parsers.Delimiter;
constructor({path, onOpen, onClose, onData, baud}: CreateProps) {
try{
const port = new serialport(path, {baudRate: baud, autoOpen: false})
port.on('open', onOpen)
port.on('close', onClose)
this.parser = port.pipe(new Delimiter({ delimiter: '!!!!' }))
this.parser.on('data', onData)
this.sp = port;
this.onClose = onClose;
}
catch{
onClose()
}
}
isOpen(){
return this.sp.isOpen
}
open(){
this.sp.open((err) => err && setTimeout(this.onClose, 1000))
}
close(){
this.sp.close()
}
write(data: number[]) {
this.sp.drain()
for(let i = 0; i < data.length; i += 4){
this.sp.write(data.slice(i, i+4))
}
}
attachListener(dataHandler: (data: string | Buffer) => void){
this.parser.on('data', dataHandler)
console.log("Attaching...")
console.log(this.parser.listeners('data'))
}
detachListener(dataHandler: (data: string | Buffer) => void){
this.parser.removeListener('data', dataHandler)
console.log("Detaching...")
console.log(this.parser.listeners('data'))
}
_emit(msg: string | Buffer){
this.sp.emit('data', msg)
}
}
export async function list() {
return await serialport.list()
}
export function IntTo16Bit(i: number) {
var buf = new ArrayBuffer(2);
new DataView(buf).setInt16(0, i)
return Array.from(new Uint8Array(buf))
}
export function IntTo32Bit(i: number) {
var buf = new ArrayBuffer(4);
new DataView(buf).setInt32(0, i)
return Array.from(new Uint8Array(buf))
}
export function FloatTo32Bit(f: number) {
var buf = new ArrayBuffer(4)
new DataView(buf).setFloat32(0, f)
return Array.from(new Uint8Array(buf))
}
export function _32BitToFloat(data: Buffer) {
const buf = new ArrayBuffer(4);
const view = new DataView(buf);
for(var i = 0; i < data.length; i++){
const b = data[3 - i];
view.setUint8(i, b);
}
return view.getFloat32(0);
}
export function _32BitToInt(data: Buffer) {
const buf = new ArrayBuffer(4);
const view = new DataView(buf);
for(var i = 0; i < data.length; i++){
const b = data[3-i];
view.setUint8(i, b);
}
return view.getInt32(0);
}<file_sep>import { homedir } from "os";
import { mkdir, writeFileSync, existsSync, mkdirSync } from "fs";
import { join } from "path"
onmessage = function(message) {
const {data} = message
const {json, outFile} = data
const logDir = join(homedir(), 'Motor_Controller_Logs')
!existsSync(logDir) && mkdirSync(logDir)
const oPath = join(logDir, outFile)
const keys = Object.keys(json)
const nKeys = keys.length
const max = Math.max(...Object.values(json).map(v => v.length))
const outArr = new Array(max + 1).fill("0").map(() => new Array(nKeys).fill("0"));
outArr[0] = keys
Object.values(json).forEach((val, idx) => {
val.forEach((v, i) => {
outArr[i+1][idx] = v
})
})
outArr.slice(1).forEach(row => row[0] = '\n' + row[0])
writeFileSync(oPath, outArr)
postMessage(oPath);
}<file_sep>const faults: {[key in Faults]: {state: boolean, description: string}} = {
'HIGH VDC': {
state: false,
description: ""
},
'DFSDM TIMEOUT': {
state: false,
description: ""
},
'HIGH IA': {
state: false,
description: ""
},
'HIGH IB': {
state: false,
description: ""
},
'HIGH IC': {
state: false,
description: ""
},
'IABC SPI': {
state: false,
description: ""
},
'RDC CRC': {
state: false,
description: ""
},
'RDC FAULT REG': {
state: false,
description: ""
},
'HIGH MOTOR TEMP': {
state: false,
description: ""
},
'HIGH IGBT TEMP': {
state: false,
description: ""
},
'IGBT THERMISTOR': {
state: false,
description: ""
},
'ADC': {
state: false,
description: ""
},
'GATE DRIVER': {
state: false,
description: ""
},
'LOW BATTERY': {
state: false,
description: ""
},
'HARD FAULT': {
state: false,
description: "It's b0rked."
}
}
let faultFlag: boolean = false;
export function getFaults(){
return faults
}
export function getFaultFlag(){
return faultFlag
}
export function clearFaults(){
Object.keys(faults).forEach((f: Faults) => {
faults[f].state = false;
})
faultFlag = false;
}
export function parseFaults(reg: number){
let mask;
let flag = false;
Object.keys(faults).forEach((f: Faults, i) => {
mask = 1 << i;
if((reg & mask) != 0){
faults[f].state = true
flag = true;
}
else{
faults[f].state = false;
}
})
faultFlag = flag;
}
type Faults =
'HIGH VDC' |
'DFSDM TIMEOUT' |
'HIGH IA' |
'HIGH IB' |
'HIGH IC' |
'IABC SPI' |
'RDC CRC' |
'RDC FAULT REG' |
'HIGH MOTOR TEMP' |
'HIGH IGBT TEMP' |
'IGBT THERMISTOR' |
'ADC' |
'GATE DRIVER' |
'LOW BATTERY' |
'HARD FAULT'<file_sep>type ParameterType = 'float' | 'int'
export type Parameter = {
name: string;
description: string;
type: ParameterType;
unit: string;
value: string;
validation: (param: string) => boolean
valid: boolean
}
export type Parameters = Parameter[]
const parameters: Parameters = [
{
name: 'Pmax',
description: 'Maxiumum operating power',
type: 'int',
unit: 'kW',
value: '100',
validation: (val) => isInt(val),
valid: true
},
{
name: 'Tmax',
description: 'Maxiumum torque',
type: 'int',
unit: 'N*m',
value: '255',
validation: isInt,
valid: true
},
{
name: 'Ld',
description: 'Stator d-axis inductance',
type: 'float',
unit: 'H',
value: '79e-6',
validation: isFloat,
valid: true
},
{
name: 'Lq',
description: 'Stator q-axis inductance',
type: 'float',
unit: 'G',
value: '79e-6',
validation: isFloat,
valid: true
},
{
name: 'L0',
description: 'Stator zero-sequence inductance',
type: 'float',
unit: 'H',
value: '0',
validation: isFloat,
valid: true
},
{
name: 'Rs',
description: 'Stator resistance per phase',
type: 'float',
unit: 'Ohm',
value: '8e-3',
validation: isFloat,
valid: true
},
{
name: 'psim',
description: 'Permanent magnet flux linkage',
type: 'float',
unit: 'Wb',
value: '0.0355',
validation: isFloat,
valid: true
},
{
name: 'p',
description: 'Number of pole pairs',
type: 'int',
unit: '−',
value: '10',
validation: isInt,
valid: true
},
{
name: 'motorTemp_max',
description: 'Maxiumum motor temperature',
type: 'int',
unit: 'C',
value: '120',
validation: isInt,
valid: true
},
{
name: 'motorTemp_corner',
description: 'Corner motor temperature',
type: 'int',
unit: 'C',
value: '100',
validation: isInt,
valid: true
},
{
name: 'rpm_max',
description: 'Maximum rotational speed of the motor',
type: 'int',
unit: 'RPM',
value: '6500',
validation: isInt,
valid: true
},
{
name: 'ke_ll_rpm',
description: 'Back emf constant',
type: 'float',
unit: 'Vrmsll/rpm',
value: '0.0478',
validation: isFloat,
valid: true
},
{
name: 'fsw',
description: 'PMSM drive switching frequency',
type: 'int',
unit: 'Hz',
value: '16e3',
validation: isInt,
valid: true
},
{
name: 'bw_idq_hz',
description: '???',
type: 'int',
unit: 'Hz',
value: '1600',
validation: isInt,
valid: true
},
{
name: 'n_rpm',
description: 'Number of points per dimension in the current reference lookup table',
type: 'int',
unit: '−',
value: '14',
validation: isInt,
valid: true
},
{
name: 'n_tq',
description: 'Number of points per dimension in the torque reference lookup table',
type: 'int',
unit: '−',
value: '6',
validation: isInt,
valid: true
},
{
name: 't_ramp',
description: 'Ramp time?',
type: 'float',
unit: 's',
value: '0.05',
validation: isFloat,
valid: true
},
{
name: 'igbtTemp_max',
description: 'Maxiumum IGBT temperature',
type: 'int',
unit: 'C',
value: '150',
validation: isInt,
valid: true
},
{
name: 'igbtTemp_corner',
description: 'Corner IGBT temperature',
type: 'int',
unit: 'C',
value: '100',
validation: isInt,
valid: true
},
{
name: 'wi',
description: 'HF injection frequency',
type: 'float',
unit: 'rad/s',
value: '628.32',
validation: isFloat,
valid: true
},
{
name: 'wt',
description: 'Test rotational frequency',
type: 'float',
unit: 'rad/s',
value: '6.2832',
validation: isFloat,
valid: true
},
{
name: 'Vhf_mag',
description: 'Magnitude of injection voltage',
type: 'int',
unit: 'Vrms',
value: '20',
validation: isInt,
valid: true
},
{
name: 'Tq_trigger',
description: 'Torque value to trigger data logging',
type: 'int',
unit: 'Nm',
value: '100',
validation: isInt,
valid: true
},
{
name: 'rpm_trigger',
description: 'RPM value to trigger data logging',
type: 'int',
unit: 'rpm',
value: '1000',
validation: isInt,
valid: true
}
]
export function isFloat(f: string) {
const floatRegex = /^-?\d+(?:[.,]?\d*?)?(?:e-?\d*?)?$/;
if (!floatRegex.test(f))
return false;
const val = Number(f);
if (isNaN(val))
return false;
return true;
}
export function isInt(i: string) {
const intRegex = /^-?\d+(?:e?\d*)?$/;
if (!intRegex.test(i))
return false;
const intVal = Number(i);
return !isNaN(intVal);
}
export default parameters;<file_sep>import Worker from 'worker-loader!./worker.js';
export default async function runWorker({json, outFile}) {
return new Promise((resolve, reject) => {
const worker = new Worker();
worker.onmessage = ({data}) => {
resolve(data)
worker.terminate()
}
worker.onerror = (err) => reject(err)
worker.postMessage({json, outFile})
})
}<file_sep>import { _32BitToFloat, _32BitToInt } from "./serial";
import json_to_csv from "./json_to_csv/json_to_csv";
import { parseFaults } from "./faults";
const log: {[key: string]: string[]} = {}
export function parse_log_message(data: string | Buffer, callback?: () => void){
let idx = 0;
if(data[0] === 0x11){
for(let i = 1; i < data.length; i = i + 4){
try{
const param = id_to_param[idx++]
if (param === 'faults'){
const value = _32BitToInt(data.slice(i, i+4) as Buffer)
parseFaults(value)
}
else {
const value = _32BitToFloat(data.slice(i,i+4) as Buffer)
if(Object.keys(log).includes(param)){
log[param].push(value.toString())
}
else{
log[param] = [value.toString()]
}
}
}
catch(error){
console.log(error)
}
}
}
callback && callback()
}
export function get_fields(){
return Object.keys(log);
}
export function get_log(field: string | null){
return field && field !== 'faults' ?
log[field].slice(Math.max(0, log[field].length - 6000), log[field].length) :
[];
}
export function clear_log(){
for (const prop of Object.getOwnPropertyNames(log)) {
delete log[prop];
}
}
export async function save_log(){
Object.keys(log).length > 0 && await json_to_csv(log, getTimestamp() + '.csv')
}
function getTimestamp(){
let currentdate = new Date();
let month = (currentdate.getMonth() + 1).toString()
month = month.length < 2 ? "0" + month : month
let day = currentdate.getDate().toString()
day = day.length < 2 ? "0" + day : day
let minutes = currentdate.getMinutes().toString()
minutes = minutes.length < 2 ? "0" + minutes : minutes
let seconds = currentdate.getSeconds().toString()
seconds = seconds.length < 2 ? "0" + seconds : minutes
const datetime = currentdate.getFullYear() + "_"
+ month + "_"
+ day + "-"
+ currentdate.getHours() + "_"
+ minutes + "_"
+ seconds;
return datetime
}
const id_to_param = [
"id_ref",
"iq_ref",
"id",
"iq",
"Vdc",
"vd_ref",
"vq_ref",
"TqRef",
"TqLim",
"TqRequest",
"rpm",
"motorTemp",
"igbtTemp",
"power",
"faults",
"ia",
"ib",
"ic",
"theta",
]<file_sep>To run:
With yarn installed:
```
yarn
yarn start
```
With npm installed:
```
npm
npm start
```
<file_sep>import runWorker from "./workers/workerThread";
export default async function json_to_csv(json: {[key: string]: string[]}, outFile: string){
const hrstart = process.hrtime()
const result = await runWorker({json, outFile})
const hrend = process.hrtime(hrstart)
process.env.NODE_ENV === 'development' && console.log(`Wrote ${result}.\nExecution time: ${hrend[0]}s, ${hrend[1] / 1000000}ms`)
}<file_sep># Motor Controller GUI
Graphical User Interface for G13's Motor Controller Project
## Contact
<NAME>
<EMAIL><file_sep>import styled from 'styled-components'
export const StyledLabel = styled.p<{ valid: boolean }>`
color: ${ ({ valid }) => valid ? '#4b90ca' : 'rgba(255, 64, 64, 1)'};
display: inline-block;
width: 450px;
margin-right: 10px;
&:hover {
cursor: default;
}
`
export const StyledUnit = styled.p<{ valid: boolean }>`
color: ${ ({ valid }) => valid ? '#4b90ca' : 'rgba(255, 64, 64, 1)'};
display: inline-block;
min-width: 80px;
text-align: end;
font-size: 12px;
cursor: default;
`
export const StyledInput = styled.input<{ valid: boolean }>`
background-color: ${ ({ valid }) => valid ? '#545454' : 'rgba(255, 64, 64, 1)'};
margin-right: 10px;
width: 100%;
border: 0;
padding: 6px;
box-sizing: border-box;
&:disabled{
color: grey;
}
`
export const Button = styled.button<{ disabled?: boolean, height?: string }>`
width: 130px;
height: ${ ({ height }) => height ? 'height' : '45px'};
padding: 10px 25px;
border-radius: 30px;
font-size: 11px;
background-color: ${ ({ disabled }) => disabled ? 'grey' : '#4b90ca'};
border: 0;
transition-property: transform;
transition-duration: 0.3s;
color: ${ ({ disabled }) => disabled ? '#333333' : 'black'};
&:focus {
outline: none;
}
&: hover {
transform: ${ ({ disabled }) => disabled ? '' : 'scale(1.1)'};
pointer: ${ ({disabled}) => disabled ? '' : 'pointer'};
` | 5489ca61ea9a163f227097b51ef3b7cce24ec161 | [
"JavaScript",
"TypeScript",
"Markdown"
] | 10 | TypeScript | uofm-capstone-2020/motor_controller_gui | 744b4a27063b3b66a5e55a48b494684e90c60abe | bb216d419f8a9ffd4fd872fb1ea7c895c475f3a8 |
refs/heads/master | <repo_name>cclcmj/MJ-LeetCode<file_sep>/初级算法/链表/合并两个有序链表/App.java
package app;
/**
*合并两个有序链表
*
*将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
*示例:
*输入:1->2->4, 1->3->4
*输出:1->1->2->3->4->4
*/
public class App {
public static void main(String[] args) throws Exception {
ListNode l1 = new ListNode(1);
ListNode temp = l1;
for(int i = 2;i < 5; i++) {
temp.next = new ListNode(i);
temp = temp.next;
}
ListNode l2 = new ListNode(1);
temp = l2;
for(int i = 2;i < 5; i++) {
temp.next = new ListNode(i);
temp = temp.next;
}
ListNode result = (new App()).mergeTwoLists(l1,l2);
temp = result;
while(temp != null) {
System.out.println(temp.val);
temp = temp.next;
}
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);//头节点
ListNode posR = result;
while(l1 != null || l2 != null) {
if((l1 != null && l2 != null && l1.val <= l2.val) || (l1 != null && l2 == null)) {
posR.next = l1;
l1 = l1.next;
}else if((l1 != null && l2 != null && l2.val < l1.val) || (l2 != null && l1 == null)){
posR.next = l2;
l2 = l2.next;
}
posR = posR.next;
}
return result.next;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}<file_sep>/初级算法/数组/删除排序数组中的重复项/Demo2.java
class Demo2 {
public static void main(String args[]) {
if(nums.length==0)return 0;
int i=0;
int j=1;
int length=nums.length;
while(j<nums.length){
System.out.println("i="+i+";"+"j="+j+";"+"length="+length+";");
if(nums[i]==nums[j]){
length=length-1;
j++;
}else{
nums[i+1]=nums[j];
i++;
j++;
}
}
return length;
}
}<file_sep>/初级算法/数组/两数之和/LeetCodeTesk.java
/*
*给定一个整数数组 nums 和一个目标值 target,
*请你在该数组中找出和为目标值的那两个整数,
*并返回他们的数组下标。
*
*你可以假设每种输入只会对应一个答案。
*但是,你不能重复利用这个数组中同样的元素。
*
*示例:
*给定 nums = [2, 7, 11, 15], target = 9
*因为 nums[0] + nums[1] = 2 + 7 = 9
*所以返回 [0, 1]
*/
class LeetCodeTesk{
public static void main(String[] args){
int[] result = new int[2];
int[] nums = {2, 7, 11, 15};
int target = 9;
//开始
for(int i=0;i<nums.length;i++){
for(int j=0;j<nums.length;j++){
if(i==j)continue;
if((nums[i]+nums[j])==target){
result[0]=nums[i];
result[1]=nums[j];
i=j=nums.length;
}
}
}
//return
for(int n=0;n<result.length;n++)
System.out.print(result[n]+",");
}
}<file_sep>/初级算法/数组/有效的数独/LeetCodeTesk.java
/*
*判断一个 9x9 的数独是否有效。
*只需要根据以下规则,验证已经填入的数字是否有效即可。
*1.数字 1-9 在每一行只能出现一次。
*2.数字 1-9 在每一列只能出现一次。
*3.数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
*
*数独部分空格内已填入了数字,空白格用 '.' 表示。
*/
import java.util.HashMap;
import java.util.ArrayList;
class LeetCodeTesk{
public static void main(String[] args){
char[][] board = {
{'5','3','.','.','7','.','.','.','.'},
{'6','.','.','1','9','5','.','.','.'},
{'.','9','8','.','.','.','.','6','.'},
{'8','.','.','.','6','.','.','.','3'},
{'4','.','.','8','.','3','.','.','1'},
{'7','.','.','.','2','.','.','.','6'},
{'.','6','.','.','.','.','2','8','.'},
{'.','.','.','4','1','9','.','.','5'},
{'.','.','.','.','8','.','.','7','9'},
};
//开始
boolean booleanResult = true;
HashMap<Integer, Integer> [] rows = new HashMap[9];
HashMap<Integer, Integer> [] columns = new HashMap[9];
HashMap<Integer, Integer> [] boxes = new HashMap[9];
for (int i = 0; i < 9; i++) {
rows[i] = new HashMap<Integer, Integer>();
columns[i] = new HashMap<Integer, Integer>();
boxes[i] = new HashMap<Integer, Integer>();
}
//元素遍历
int box,n;
for(int r=0;r<9;r++){
for(int c=0;c<9;c++){
System.out.print(c+",");
if(board[r][c]=='.')
continue;
n = board[r][c];
box = (r/3)*3+c/3;
rows[r].put(n,rows[r].getOrDefault(n,0)+1);
columns[c].put(n,columns[c].getOrDefault(n,0)+1);
boxes[box].put(n,boxes[box].getOrDefault(n,0)+1);
//判断
//System.out.println(rows[r].get(n)+","+columns[c].get(n)+","+boxes[box].get(n));
if(rows[r].get(n)==2||columns[c].get(n)==2||boxes[box].get(n)==2){
booleanResult = false;
c=10;
r=10;
}
}
System.out.println(r+":");
}
//return
System.out.println(booleanResult);
/*
//输出数组所有元素
for(int n=0;n<result.length;n++)
System.out.print(result[n]+",");
*/
}
}<file_sep>/初级算法/链表/删除链表的倒数第N个节点/TestDemo.java
package tesk.LinkedList;
import java.util.ArrayList;
import java.util.List;
/*
*删除链表的倒数第N个节点
*给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
*
*示例:
*给定一个链表: 1->2->3->4->5, 和 n = 2.
*当删除了倒数第二个节点后,链表变为 1->2->3->5.
*
*说明:
*给定的 n 保证是有效的。
*进阶:
*你能尝试使用一趟扫描实现吗?
*/
class TestDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode head = new ListNode(1);
ListNode temp = head;
for(int i = 2;i < 6;i++) {
temp.next = new ListNode(i);
temp = temp.next;
}
head.showAll();
new TestDemo().removeNthFromEnd(head, 2).showAll();
}
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode prev = head;
ListNode last = head;
head = new ListNode(0);//增加头节点
head.next = prev;
prev = last = head;
int k = 0;
if(head.next == null) head = null;
else {
while(k != n) {
last = last.next;
k++;
}
while(last.next != null) {
prev = prev.next;
last = last.next;
}
prev.next = prev.next.next;
}
return head.next;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
void showAll() {
ListNode temp = this;
while(temp != null) {
System.out.print(temp.val + ",");
temp = temp.next;
}
}
}
<file_sep>/初级算法/字符串/反转字符串/LeetCodeTesk.java
/*
*反转字符串
*编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
*不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
*你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
*
*示例 1:
*输入:["h","e","l","l","o"]
*输出:["o","l","l","e","h"]
*
*示例 2:
*输入:["H","a","n","n","a","h"]
*输出:["h","a","n","n","a","H"]
*/
class LeetCodeTesk{
public static void main(String[] args){
char[] s = {'h','e','l','l','o'};
//开始
for(int i = 0;i < s.length/2;i++) {
char temp = s[i];
s[i] = s[s.length - i -1];
s[s.length - i - 1] = temp;
}
//return
for(int i = 0;i < s.length;i++) {
System.out.print(s[i]+",");
}
/*
//输出布尔变量
System.out.println(booleanResult);
*/
/*
//输出数组所有元素
for(int n=0;n<result.length;n++)
System.out.print(result[n]+",");
*/
}
}<file_sep>/初级算法/数组/买卖股票的最佳时机--贪心算法/Demo1.java
class Solution {
public int maxProfit(int[] prices) {
int i,j,c;i=0;j=1;c=0;
while(j<prices.length){
System.out.println("i="+i+";"+"j="+j+";"+";"+"c="+c+";");
System.out.println(prices[j]+","+prices[i]);
if(prices[j]>prices[i]){
c=c+prices[j]-prices[i];
}
i++;
j++;
}
return c;
}
}<file_sep>/初级算法/数组/旋转数组/Solution1.java
class Solution {
public void rotate(int[] nums, int k) {
for(int j=0;j<k;j++){
int l=nums[nums.length-1];
System.out.println("l="+l+";");
int i=nums.length-1;
for(;i>0;i--){
nums[i]=nums[i-1];
}
nums[0]=l;
}
}
}<file_sep>/初级算法/链表/回文链表/App.java
package app;
/**
*回文链表
*请判断一个链表是否为回文链表。
*
*示例 1:
*输入: 1->2
*输出: false
*
*示例 2:
*输入: 1->2->2->1
*输出: true
*
*进阶:
*你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
*/
public class App {
public static void main(String[] args) throws Exception {
ListNode l1 = new ListNode(2);
ListNode temp = l1;
for(int i = 2;i < 5; i++) {
temp.next = new ListNode(i);
temp = temp.next;
}
for(int i = 4;i > 0; i--) {
temp.next = new ListNode(i);
temp = temp.next;
}
temp = l1;
while(temp != null) {
System.out.print(temp.val + ",");
temp = temp.next;
}
System.out.println(new App().isPalindrome(l1));
}
public boolean isPalindrome(ListNode head) {
StringBuffer result = new StringBuffer("");
ListNode pos = head;
while(pos != null) {
result.append(String.valueOf(pos.val) + ",");
pos = pos.next;
}
String[] strs = result.toString().split(",");
for(int i = 0;i < strs.length/2; i++) {
if(!strs[i].equals(strs[strs.length-1-i]))
return false;
}
return true;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}<file_sep>/初级算法/字符串/实现strStr()/TestDemo.java
package tesk.string;
/*
* 实现strStr()
*实现 strStr() 函数。
*给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。
*如果不存在,则返回 -1。
*
*示例 1:
*输入: haystack = "hello", needle = "ll"
*输出: 2
*示例 2:
*输入: haystack = "aaaaa", needle = "bba"
*输出: -1
*
*说明:
*当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
*对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
*/
class TestDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
String haystack = "mississippi";
String needle = "issip";
System.out.println(TestDemo.strStr(haystack,needle));
}
public static int strStr(String haystack,String needle) {
int result = -1;
char[] nee = needle.toCharArray();
char[] hay = haystack.toCharArray();
int i = 0,j = 0;
while(i < hay.length && j < nee.length) {
if(hay[i] == nee[j]) {
i++;j++;
}else if(j != 0) {
i = i - j + 1;j = 0;
}else
i++;
System.out.println(i + "," + j);
}
if(nee.length == 0) result = 0;
else if(j == nee.length) result = i - j;
return result;
}
}
<file_sep>/初级算法/数组/两个数组的交集2——用hashmap/LDemo.java
import java.util.HashMap;
/*
*给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]
说明:
输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
我们可以不考虑输出结果的顺序。
进阶:
如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小很多,哪种方法更优?
如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
*/
class LDemo{
public static void main(String args[]){
int nums1[]={4,9,5};
int nums2[]={9,4,9,8,4};
HashMap<Integer,Integer> num=new HashMap<Integer,Integer>();
ArrayList<Integer> resultList = new ArrayList<Integer>();
//将nums1数组中的元素导入hashmap,键为元素,值为出现的次数
for(int i=0;i<nums1.length;i++){
Integer v=num.get(nums1[i]);
num.put(nums1[i],v==null?1:v+1);
}
//nums2数组与HashMap中得键一一对比,存在且值大于0则值-1并放入结果集合中
for(int i=0;i<nums2.length;i++){
if(num.containsKey(nums2[i]) && num.get(nums2[i])>0){
num.put(nums2[i],num.get(nums2[i])-1);
resultList.add(nums2[i]);
}
}
//返回结果数组
int[] resultArray = new int[resultList.size()];
for(int i=0;i<resultList.size();i++){
resultArray[i]=resultList.get(i);
}
//return resultArray;
}
}
}
} | be4a5284d3ba49047d8555bda44ea40e42b8fe45 | [
"Java"
] | 11 | Java | cclcmj/MJ-LeetCode | 931324a62a9cc50a659d0ca6cbd9b5fd5454c0c2 | a96ae75154169594520136339f2b77f341f5824c |
refs/heads/master | <file_sep>const hasRequiredProperties = (required, data) => {
const keys = Object.keys(data);
const errors = [];
for (value of required) {
if (!keys.includes(value)) {
errors.push({
[value]: 'can\'t be blank'
});
}
}
return errors;
}
module.exports = {
hasRequiredProperties
}
<file_sep>require('models/User');
require('models/Article');
require('models/Comment');
require('config/passport');
<file_sep># real-world-api
Realworld implemention in JS
<file_sep>const express = require('express');
const bodyParser = require('body-parser');
const logger = require('morgan');
const cors = require('cors');
const mongoose = require('mongoose');
const errorhandler = require('errorhandler');
const session = require('express-session');
const connectToDatabase = require('config/database');
const { nodeEnv, databaseUrl, secreKey } = require('config/environment').env;
const app = express();
// middlewares
app.use(logger('dev'));
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(session({
secret: secreKey,
cookie: { maxAge: 60000 },
resave: false,
saveUninitialized: false
}));
// connect to the database
connectToDatabase(mongoose, databaseUrl);
require('models');
app.use(require('routes'));
app.get('/*', (req, res) => {
return res.sendFile('index.html', {
root: 'public'
});
});
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
if (nodeEnv !== 'production') {
app.use(errorhandler())
//set mongoose to debug mode
mongoose.set('debug', true)
// development error handler
app.use((err, req, res, next) => {
console.log(err.stack);
return res.status(err.status || 500)
.json({
'errors': {
message: err.message,
error: err
}
});
});
}
app.use((err, req, res, next) => {
return res.status(err.status || 500)
.json({
'errors': {
message: err.message,
error: {}
}
});
});
module.exports = app;
<file_sep>const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const { sign } = require('jsonwebtoken');
const { randomBytes, pbkdf2Sync } = require('crypto');
const Schema = mongoose.Schema;
const { secretKey } = require('config/environment').env;
const UserSchema = new Schema({
username: {
type: String,
lowercase: true,
unique: true,
required: [true, "can't be blank"], match: [/^[a-zA-Z0-9]+$/, 'is invalid'],
index: true
},
email: {
type: String,
lowercase: true,
unique: true,
required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'],
index: true
},
bio: String,
image: {
type: String,
default: 'https://static.productionready.io/images/smiley-cyrus.jpg'
},
favorites: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Article'
}],
following: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}],
hash: String,
salt: String
},
{ timestamps: true }
);
UserSchema.plugin(uniqueValidator, { message: 'is already taken' });
UserSchema.methods.validPassword = function (password) {
const hash = pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
return this.hash = hash;
}
UserSchema.methods.setPassword = function (password) {
this.salt = randomBytes(16).toString('hex');
this.hash = pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
}
UserSchema.methods.generateJwtToken = function () {
const today = new Date();
const expiration = new Date(today);
expiration.setDate(today.getDate() + 60);
return sign(
{ id: this.id, username: this.username, exp: parseInt(expiration.getTime() / 1000) },
secretKey
);
}
UserSchema.methods.toAuthJSON = function () {
const { username, email, bio, image } = this;
return { username, email, bio, image, token: this.generateJwtToken() };
}
UserSchema.methods.toProfileJSONFor = function (user) {
return {
username: this.username,
bio: this.bio,
image: this.image,
following: user ? user.isFollowing(this._id) : false
}
}
UserSchema.methods.favorite = function (id) {
if (!this.favorites.includes(id)) {
this.favorites = [...this.favorites, id];
}
return this.save();
}
UserSchema.methods.unfavorite = function (id) {
this.favorites.remove(id);
return this.save();
}
UserSchema.methods.isFavorite = function (id) {
return this.favorites.some(favoriteId => favoriteId.toString === id.toString());
}
UserSchema.methods.follow = function (id) {
if (!this.following.includes(id)) {
this.favorites = [...this.favorites, id];
}
return this.save();
}
UserSchema.methods.unfollow = function (id) {
this.following.remove(id);
return this.save();
}
UserSchema.methods.isFollowing = function (id) {
return this.following.some(followId => followId.toString() === id.toString());
}
module.exports = mongoose.model('User', UserSchema);
<file_sep>const passport = require('passport');
const Strategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const User = mongoose.model('User');
const localStrategy = new Strategy(
{ usernameField: 'user[email]', passwordField: '<PASSWORD>]' },
(email, password, done) => {
return User.findOne({ email })
.then(user => {
if (!user || !user.validPassword(password)) {
return done(null, false, {
error: 'Invalid email or password'
})
}
return done(null, user)
})
.catch(done)
});
passport.use(localStrategy);
<file_sep>
module.exports = {
env: {
databaseUrl: process.env.DATABASE_URL || 'mongodb://localhost/warsha-real-world',
nodeEnv: process.env.NODE_ENV || 'development',
secretKey: process.env.SECRET_ENCRYPTION_KEY || '<KEY>'
}
}
<file_sep>/* eslint-disable no-console */
module.exports = (mongoose, databaseUrl) => {
mongoose.connect(databaseUrl, {
useMongoClient: true,
});
mongoose.Promise = global.Promise;
mongoose.connection.on('connected', () => {
console.log('Connecton to mongo database established');
});
mongoose.connection.on('error', (err) => {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', () => {
console.log('Mongoose disconnected');
});
process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log('Mongoose disconnected through app termination');
process.exit(0);
});
});
};
<file_sep>const Router = require('express').Router();
const { create, login, findById, update } = require('./users.controllers');
const Auth = require('../Auth');
Router.route('/user')
.get(Auth.required, findById)
.put(Auth.required, update)
Router.post('/users/login', login);
Router.post('/users', create);
module.exports = Router;
<file_sep>const MainRouter = require('express').Router();
const UserRouter = require('./users/users.routes');
MainRouter.use(UserRouter);
module.exports = MainRouter;
| 579a3a93685e190567a8d49fee8c3f4577ff7c65 | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | nyambati/real-world-api | 4c3459d1a98be98c1125be2070073579d53699c5 | d891aa5d301b09ea3bf07417a57b743c7f2ec952 |
refs/heads/1.16.1 | <repo_name>Commoble/potionofbees<file_sep>/src/main/java/com/github/commoble/potionofbees/client/ClientModEventHandler.java
package com.github.commoble.potionofbees.client;
import com.github.commoble.potionofbees.PotionOfBeesMod;
import com.github.commoble.potionofbees.RegistryObjects;
import com.github.commoble.potionofbees.SplashPotionOfBeesEntity;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.EntityRendererManager;
import net.minecraft.client.renderer.entity.SpriteRenderer;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
@EventBusSubscriber(modid=PotionOfBeesMod.MODID, value=Dist.CLIENT, bus=Bus.MOD)
public class ClientModEventHandler
{
@SubscribeEvent
public static void onClientSetup(FMLClientSetupEvent event)
{
RenderingRegistry.registerEntityRenderingHandler(RegistryObjects.getSplashPotionOfBeesEntityType(), ClientModEventHandler::getSplashPotionOfBeesRenderer);
}
public static SpriteRenderer<SplashPotionOfBeesEntity> getSplashPotionOfBeesRenderer(EntityRendererManager manager)
{
return new SpriteRenderer<>(manager, Minecraft.getInstance().getItemRenderer());
}
}
<file_sep>/src/main/java/com/github/commoble/potionofbees/WorldUtil.java
package com.github.commoble.potionofbees;
import java.util.Optional;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.SpawnReason;
import net.minecraft.entity.passive.BeeEntity;
import net.minecraft.potion.EffectInstance;
import net.minecraft.potion.Effects;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.World;
public class WorldUtil
{
public static void spawnAngryBees(World world, Vector3d vec)
{
AxisAlignedBB targetBox = new AxisAlignedBB(vec,vec).grow(PotionOfBeesMod.BEE_SEARCH_RADIUS);
Optional<LivingEntity> foundTarget =
world.getEntitiesWithinAABB(LivingEntity.class, targetBox, WorldUtil::isValidBeeTarget).stream()
.reduce((entityA, entityB) -> entityB.getDistanceSq(vec) < entityA.getDistanceSq(vec) ? entityB : entityA);
int bees = 3 + world.rand.nextInt(5) + world.rand.nextInt(5);
int maxTime = 3000;
int ticksToExist = maxTime/bees;
for (int i=0; i<bees; i++)
{
BlockPos spawnPos = new BlockPos(vec.x, vec.y, vec.z);
Entity ent = EntityType.BEE.spawn(world, null, null, spawnPos, SpawnReason.EVENT, false, false);
if (ent instanceof BeeEntity)
{
BeeEntity bee = (BeeEntity)ent;
bee.setPosition(vec.x, vec.y, vec.z);
bee.addPotionEffect(new EffectInstance(Effects.SPEED, maxTime, 1, false, false));
bee.addPotionEffect(new EffectInstance(RegistryObjects.EVANESCENCE_EFFECT, ticksToExist, 0, false, false));
foundTarget.ifPresent(target -> { // make bee angry at target
bee.setAttackTarget(target);
bee.targetSelector.addGoal(0, new AttackThingsThatAreNotBeesGoal(bee));
});
}
}
}
public static boolean isValidBeeTarget(LivingEntity ent)
{
return (ent.getType() != EntityType.BEE) && (!ent.isInvulnerable());
}
}
<file_sep>/src/main/java/com/github/commoble/potionofbees/Registrator.java
package com.github.commoble.potionofbees;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.IForgeRegistryEntry;
public class Registrator<T extends IForgeRegistryEntry<T>>
{
public IForgeRegistry<T> registry;
public Registrator(IForgeRegistry<T> registry)
{
this.registry = registry;
}
public T register(String registryKey, T entry)
{
ResourceLocation loc = new ResourceLocation(PotionOfBeesMod.MODID, registryKey);
return this.register(loc, entry);
}
public T register(ResourceLocation location, T entry)
{
entry.setRegistryName(location);
this.registry.register(entry);
return entry;
}
}
<file_sep>/src/main/java/com/github/commoble/potionofbees/RegistryObjects.java
package com.github.commoble.potionofbees;
import net.minecraft.entity.EntityType;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.IForgeRegistryEntry;
import net.minecraftforge.registries.ObjectHolder;
public class RegistryObjects
{
// RegistryObjects seem broken in 1.15 atm, using ObjectHolders for now
// public static final RegistryObject<PotionOfBeesItem> POTION_OF_BEES_ITEM = makeRegistryObject(ResourceLocations.POTION_OF_BEES, ForgeRegistries.ITEMS);
// public static final RegistryObject<PotionOfBeesItem> SPLASH_POTION_OF_BEES_ITEM = makeRegistryObject(ResourceLocations.SPLASH_POTION_OF_BEES, ForgeRegistries.ITEMS);
@ObjectHolder("potionofbees:potion_of_bees")
public static final PotionOfBeesItem POTION_OF_BEES_ITEM = null;
@ObjectHolder("potionofbees:splash_potion_of_bees")
public static final SplashPotionOfBeesItem SPLASH_POTION_OF_BEES_ITEM = null;
@ObjectHolder("potionofbees:evanescence")
public static final EvanescenceEffect EVANESCENCE_EFFECT = null;
// public static final RegistryObject<EvanescenceEffect> EVANESCENCE_EFFECT = makeRegistryObject(ResourceLocations.EVANESCENCE, ForgeRegistries.POTIONS);
// RegistryObjects/ObjectHolders for EntityTypes seem to be broken as of the moment this is being typed
// public static final RegistryObject<EntityType<? extends SplashBeePotionEntity>> BEE_POTION_ENTITY_TYPE = makeRegistryObject(ResourceLocations.SPLASH_BEE_POTION, ForgeRegistries.ENTITIES);
public static <T extends IForgeRegistryEntry<T>, U extends T> RegistryObject<U> makeRegistryObject(final ResourceLocation location, IForgeRegistry<T> registry)
{
return RegistryObject.of(location, registry);
}
@SuppressWarnings("unchecked")
public static EntityType<? extends SplashPotionOfBeesEntity> getSplashPotionOfBeesEntityType()
{
return (EntityType<? extends SplashPotionOfBeesEntity>) ForgeRegistries.ENTITIES.getValue(ResourceLocations.SPLASH_POTION_OF_BEES);
}
}
<file_sep>/src/main/java/com/github/commoble/potionofbees/AttackThingsThatAreNotBeesGoal.java
package com.github.commoble.potionofbees;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.ai.goal.NearestAttackableTargetGoal;
import net.minecraft.entity.passive.BeeEntity;
public class AttackThingsThatAreNotBeesGoal extends NearestAttackableTargetGoal<LivingEntity>
{
public static boolean isThingNotBee(LivingEntity ent)
{
return (ent.getType() != EntityType.BEE);
}
AttackThingsThatAreNotBeesGoal(BeeEntity p_i225719_1_)
{
super(p_i225719_1_, LivingEntity.class, 10, true, false, AttackThingsThatAreNotBeesGoal::isThingNotBee);
}
/**
* Returns whether the EntityAIBase should begin execution.
*/
@Override
public boolean shouldExecute()
{
return this.canSting() && super.shouldExecute();
}
@Override
protected void findNearestTarget()
{
this.nearestTarget = this.goalOwner.world.func_225318_b(
this.targetClass,
this.targetEntitySelector,
this.goalOwner,
this.goalOwner.getPosX(),
this.goalOwner.getPosY(),
this.goalOwner.getPosZ(),
this.getTargetableArea(this.getTargetDistance()));
}
/**
* Returns whether an in-progress EntityAIBase should continue executing
*/
@Override
public boolean shouldContinueExecuting()
{
boolean canSting = this.canSting();
if (canSting && this.goalOwner.getAttackTarget() != null)
{
return super.shouldContinueExecuting();
}
else
{
this.target = null;
return false;
}
}
private boolean canSting()
{
BeeEntity beeentity = (BeeEntity) this.goalOwner;
return beeentity.isAggressive() && !beeentity.hasStung();
}
}
<file_sep>/README.md
TODO add readme
more info here
https://www.curseforge.com/minecraft/mc-mods/potion-of-bees
<file_sep>/src/main/java/com/github/commoble/potionofbees/SplashPotionOfBeesItem.java
package com.github.commoble.potionofbees;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.Stats;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvents;
import net.minecraft.world.World;
public class SplashPotionOfBeesItem extends Item
{
public SplashPotionOfBeesItem(Properties properties)
{
super(properties);
}
/**
* Called to trigger the item's "innate" right click behavior. To handle when
* this item is used on a Block, see {@link #onItemUse}.
*/
@Override
public ActionResult<ItemStack> onItemRightClick(World worldIn, PlayerEntity playerIn, Hand handIn)
{
ItemStack itemstack = playerIn.getHeldItem(handIn);
worldIn.playSound((PlayerEntity) null, playerIn.getPosX(), playerIn.getPosY(), playerIn.getPosZ(), SoundEvents.ENTITY_EXPERIENCE_BOTTLE_THROW,
SoundCategory.NEUTRAL, 0.5F, 0.4F / (random.nextFloat() * 0.4F + 0.8F));
if (!worldIn.isRemote)
{
SplashPotionOfBeesEntity potionEntity = SplashPotionOfBeesEntity.asThrownEntity(worldIn, playerIn);
potionEntity.setItem(itemstack);
// ProjectileEntity::shoot
potionEntity.func_234612_a_(playerIn, playerIn.rotationPitch, playerIn.rotationYaw, -20.0F, 0.7F, 1.0F);
worldIn.addEntity(potionEntity);
}
playerIn.addStat(Stats.ITEM_USED.get(this));
if (!playerIn.abilities.isCreativeMode)
{
itemstack.shrink(1);
}
return ActionResult.resultSuccess(itemstack);
}
}
| d4d077d2e50a77ec3595fc8384b9f67259ecfac4 | [
"Markdown",
"Java"
] | 7 | Java | Commoble/potionofbees | 7c2800bcf564b10d83e03ba961070b00ccfe7a33 | 898f62b12dcf65ca97e8fcbad39aee19dfce931f |
refs/heads/master | <repo_name>kidoju/Kidoju-Help-deprecated<file_sep>/src/main.js
require('../web/viewer.css');
require('../web/compatibility.js');
// require('pdfjs-dist/web/compatibility.js');
require('../web/l10n.js');
window.pdfjsDistBuildPdf = require('../build/pdf.js');
// window.pdfjsDistBuildPdf = require('pdfjs-dist/build/pdf.js');
// require('../web/debugger.js');
require('./viewer.js');<file_sep>/README.md
# Kidoju-Help
> A help system based on Mozilla PDF.js for Kidoju
## Background
This project is based on [Mozilla PDF.js](https://mozilla.github.io/pdf.js/)
## Upgrade
Upgrading PDF.js consists in:
1. [downloading PDF.js](https://mozilla.github.io/pdf.js/getting_started/#download)
2. Copying the content to the ```build/``` and ```web/``` directories
3. Generating the ```viewer/``` and ```src/``` directories by running ```grunt```
The only file that is not generated is ```src/main.js```:
```js
require('../web/viewer.css');
require('../web/compatibility.js'); // require('pdfjs-dist/web/compatibility.js');
require('../web/l10n.js');
window.pdfjsDistBuildPdf = require('../build/pdf.js'); // require('pdfjs-dist/web/pdf.js');
// require('../web/debugger.js');
require('./viewer.js');
```
## Improvements
[pdfjs-dist](https://github.com/mozilla/pdfjs-dist) is generally more up-to-date than [PDF.js](https://github.com/mozilla/pdf.js).
Therefore, it would be nice to replace in ```src/main.js```:
```js
...
require('pdfjs-dist/web/compatibility.js');
...
window.pdfjsDistBuildPdf = require('pdfjs-dist/web/pdf.js');
...
```
Unfortunately all required files are not maintained within ```src/main.js```, especially ```viewer.html```, ```viewer.js``` and ```viewer.css```.
| 33e3cb9c0f87a848ce40f9d988e47a60018650e9 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | kidoju/Kidoju-Help-deprecated | 8b5f65eb4c5603210fb3d32a1ad8a3e507da3356 | 052b63953b9c49a2b8d8db4f51e7b0757653bef5 |
refs/heads/master | <file_sep><<<<<<< Updated upstream
### JDS SURVEY
=======
### JDS SURVEY
>>>>>>> Stashed changes
<file_sep><?php
/**
* The welcome page is the home page
* TODO : make a recursive function, taking any number of box in the database, calculating how much rows are needed.
*/
// DO NOT REMOVE This is for automated testing to validate we see that page
echo viewHelper::getViewTestTag('index');
?>
<?php
// Boxes are defined by user. We still want the default boxes to be translated.
gT('Create survey');
gT('Create a new survey');
gT('List surveys');
gT('List available surveys');
gT('Global settings');
gT('Edit global settings');
gT('ComfortUpdate');
gT('Stay safe and up to date');
gT('Label sets');
gT('Edit label sets');
gT('Themes');
?>
<!-- Welcome view -->
<div class="container-fluid welcome full-page-wrapper">
<!-- Logo & Presentation -->
<?php if($bShowLogo):?>
<div class="row">
<div class="jumbotron" id="welcome-jumbotron">
<img alt="logo" src="<?php echo LOGO_URL;?>" id="lime-logo" class="profile-img-card img-responsive center-block" />
<p class="hidden-xs custom custom-margin top-25" ><?php echo PRESENTATION; // Defined in AdminController?></p>
</div>
</div>
<?php endif;?>
<!-- Message when first start -->
<?php if($countSurveyList==0 && Permission::model()->hasGlobalPermission('surveys','create') ):?>
<script type="text/javascript">
$(window).load(function(){
$('#welcomeModal').modal('show');
});
</script>
<div class="modal fade" id="welcomeModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title"><?php echo sprintf(gT("Welcome to %s!"), 'LimeSurvey'); ?></h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row" id="selector__welcome-modal--simplesteps">
<p><?php eT("Some piece-of-cake steps to create your very own first survey:"); ?></p>
<ol>
<li><?php echo sprintf(gT('Create a new survey clicking on the %s icon.'),
"<i class='icon-add text-success'></i>"); ?></li>
<li><?php eT('Create a new question group inside your survey.'); ?></li>
<li><?php eT('Create one or more questions inside the new question group.'); ?></li>
<li><?php echo sprintf(gT('Done. Test your survey using the %s icon.'), "<i class='icon-do text-success'></i>"); ?></li>
</ol>
</div>
<div class="row"><hr/></div>
<?php if(Permission::model()->hasGlobalPermission('surveys','create')) { ?>
<div class="row" id="selector__welcome-modal--tutorial">
<p><?php eT('Or, try out our interactive tutorial tour'); ?> </p>
<p class="text-center"><button class="btn btn-primary btn-lg" id="selector__welcome-modal--starttour"><?php eT("Start the tour"); ?></button></p>
</div>
<?php } ?>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal"><?php eT('Close');?></button>
<a href="<?php echo $this->createUrl("admin/survey/sa/newsurvey") ?>" class="btn btn-primary"><?php eT('Create a new survey');?></a>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<?php endif;?>
<?php
//Check for IE and show a warning box
if (preg_match('~MSIE|Internet Explorer~i', $_SERVER['HTTP_USER_AGENT']) || (strpos($_SERVER['HTTP_USER_AGENT'], 'Trident/7.0') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'rv:11.0') !== false)) {
?>
<div class="container">
<div class="alert alert-danger" role="alert" id="warningIE11">
<div class="container-fluid">
<div class="row">
<h4 class="col-xs-12"><?=gT("Warning!")?></h4>
</div>
<div class="row">
<div class="col-xs-12">
<?php eT("You are using Microsoft Internet Explorer."); ?><br/><br/>
<?php eT("LimeSurvey 3.x or newer does not support Internet Explorer for the LimeSurvey administration, anymore. However most of the functionality should still work."); ?><br/>
<?php eT("If you have any issues, please try using a modern browser first, before reporting it.");?>
</div>
</div>
</div>
</div>
</div>
<?php
}
App()->getClientScript()->registerScript('WelcomeCheckIESafety', "
if(!/(MSIE|Trident\/)/i.test(navigator.userAgent)) {
$('#warningIE11').remove();
}
", LSYii_ClientScript::POS_POSTSCRIPT);
?>
<!-- Last visited survey/question -->
<?php if( $bShowLastSurveyAndQuestion && ($showLastSurvey || $showLastQuestion)): // bShowLastSurveyAndQuestion is the homepage setting, showLastSurvey & showLastQuestion are about if infos are available ?>
<div class="row text-right">
<div class="col-lg-9 col-sm-9 ">
<div class='pull-right'>
<?php if($showLastSurvey):?>
<span id="last_survey" class="rotateShown">
<?php eT("Last visited survey:");?>
<a href="<?php echo $surveyUrl;?>" class=""><?php echo viewHelper::flatEllipsizeText($surveyTitle, true, 60);?></a>
</span>
<?php endif; ?>
<?php if($showLastQuestion):?>
<span id="last_question" class="rotateHidden">
<?php eT("Last visited question:");?>
<a href="<?php echo $last_question_link;?>" class=""><?php echo viewHelper::flatEllipsizeText($last_question_name, true, 60); ?></a>
</span>
<?php endif; ?>
</div>
<br/><br/>
</div>
</div>
<?php endif;?>
<!-- Rendering all boxes in database -->
<?php $this->widget('ext.PanelBoxWidget.PanelBoxWidget', array(
'display'=>'allboxesinrows',
'boxesbyrow'=>$iBoxesByRow,
'offset'=>$sBoxesOffSet,
'boxesincontainer' => $bBoxesInContainer
));
?>
<?php if( $bShowSurveyList ): ?>
<div class="col-sm-12 list-surveys">
<h2><?php eT('Survey list'); ?></h2>
<?php
$this->widget('ext.admin.survey.ListSurveysWidget.ListSurveysWidget', array(
'model' => $oSurveySearch,
'bRenderSearchBox' => $bShowSurveyListSearch,
));
?>
</div>
<?php endif; ?>
<!-- Boxes for smartphones -->
<div class="row hidden-sm hidden-md hidden-lg ">
<div class="panel panel-primary panel-clickable" id="panel-7" data-url="/limesurvey/LimeSurveyNext/index.php/admin/survey/sa/listsurveys" style="opacity: 1; top: 0px;">
<div class="panel-heading">
<div class="panel-title"><?php eT('List surveys');?></div>
</div>
<div class="panel-body">
<a href='<?php echo $this->createUrl("admin/survey/sa/listsurveys") ?>'>
<span class="icon-list" style="font-size: 4em"></span>
<span class="sr-only"><?php eT('List surveys');?></span>
</a><br><br>
<a href='<?php echo $this->createUrl("admin/survey/sa/listsurveys") ?>'><?php eT('List surveys');?></a>
</div>
</div>
<div class="panel panel-primary panel-clickable" id="panel-8" data-url="/limesurvey/LimeSurveyNext/index.php/admin/globalsettings" style="opacity: 1; top: 0px;">
<div class="panel-heading">
<div class="panel-title"><?php eT('Edit global settings');?></div>
</div>
<div class="panel-body">
<a href='<?php echo $this->createUrl("admin/globalsettings") ?>'>
<span class="icon-settings" style="font-size: 4em"></span>
<span class="sr-only"><?php eT('Edit global settings');?></span>
</a><br><br>
<a href='<?php echo $this->createUrl("admin/globalsettings") ?>'><?php eT('Edit global settings');?></a>
</div>
</div>
</>
</div>
<!-- Notification setting -->
<input type="hidden" id="absolute_notification" />
<file_sep>var idDropdown ="";
function selectFilterByCode(qID, gID, sID, filterqID){
console.log("Survey Kependudukan Daerah");
console.log("Survey ID "+sID);
console.log("Group ID "+gID);
console.log("Question ID "+qID);
idDropdown = "#answer"+sID+"X"+gID+"X"+qID;
}
$(document).ready(function(){
console.log(idDropdown);
for (let i = 1; i <= 10; i++) {
// console.log(i);
$("#answer136271X1X335A1_AA1 option[value='"+i+"']").remove();
$("#answer136271X1X335A1_AA2 option[value='"+i+"']").remove();
$("#answer136271X1X335A1_AA3 option[value='"+i+"']").remove();
}
var Provinsi = {
A:'JAWA BARAT',
B:'JAWA TENGAH',
C:'JAWA TIMUR'
};
var Kota = {
A1:'BANDUNG',
A2:'TASIK',
A3:'SUMEDANG',
A4:'MAJALENGKA',
A5:'BEKASI',
B1:'CIREBON',
B2:'SEMARANG',
B3:'JOGJAKARTA',
B4:'BEREBES',
B5:'CILACAP',
C1:'SURABAYA',
C2:'MALANG',
C3:'KUDUS',
C4:'JEPARA',
C5:'BANYUWANGI',
}
$.each(Provinsi,function(i, val){
console.log(val +" "+ i);
// $('#answer136271X1X335A1_AA1').append(`<option value="${optionValueProvinsi[i]}">${val}</option>`);
});
});<file_sep>FROM php:7-fpm
# install and enable pdo_mysql module
RUN docker-php-ext-install mysqli pdo pdo_mysql && docker-php-ext-enable pdo_mysql
# install composer
RUN cd ~
RUN curl -sS https://getcomposer.org/installer | php
RUN mv composer.phar /usr/local/bin/composer
RUN ln -s /usr/local/bin/composer /usr/bin/composer
# add source code and config files
ADD ./php.ini /usr/local/etc/php/php.ini
ADD ./public /var/www/html/public
# set file permission
RUN chmod -R 777 /var/www/html/public/assets
RUN chmod -R 777 /var/www/html/public/tmp
RUN chmod -R 777 /var/www/html/public/upload
RUN chmod -R 777 /var/www/html/public/application/config
# set working directory
WORKDIR /var/www/html/public
# install dependencies via composer
RUN apt-get update && apt-get install -y \
zlib1g-dev \
libzip-dev
RUN docker-php-ext-install zip
RUN composer update<file_sep># Crowdsource Survey App
## Run the Application
Create `.env` file
```sh
cp .env-sample .env
```
If you are working in local development, you can uncomment these lines from `docker-compose.yml` file to mount local filesystem to container's
```yaml
...
vol_php_public:
...
# driver: local
# driver_opts:
# type: none
# device: $PWD/php/public
# o: bind
...
```
Then, build images and run containers
```sh
docker-compose up -d
```
Finally, you can access from your browser at http://localhost:8181
## Modifikasi Desain form
* pada mode administrator, klik Themes pada layar.
* maka akan keluar beberapa themes yang sudah terinstall di framework
* pada tampilan themes, ada beberapa tab diantaranya : Survey Themes, Admin Themes, dan Question Themes
* **Survey Themes** : untuk tampilan survey yang akan dilihat oleh client
* **Admin Survey** : untuk tampilan admin
* untuk memodifikasi themes bisa klik *themes editor*, atau jika hanya merubah beberapa tampilan saja pilih *themes options*
<file_sep>var idDropdown ="";
function selectFilterByCode(qID, gID, sID, filterqID){
console.log("Survey ID "+sID);
console.log("Group ID "+gID);
console.log("Question ID "+qID);
idDropdown = "#answer"+sID+"X"+gID+"X"+qID;
}
$(document).ready(function(){
console.log(idDropdown);
$("#answer22769X18X333").children('option:gt(0)').hide();
$("#answer22769X18X332").change(function() {
$("#answer22769X18X333").children('option').hide();
$("#answer22769X18X333").children("option[value^=" + $(this).val() + "]").show()
})
});<file_sep>FROM mysql:5.7
# set timezone
ENV TZ=Asia/Jakarta
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
# Copy conf files
COPY image-files/ /
# Expose port
EXPOSE 3306<file_sep>function selectFilterByCode(qId, gId, sId) {
console.log("SURVEYID "+ sId);
console.log("QUESTIONID "+ qId);
console.log("GROUPID "+ gId);
console.log("xxxx");
}
function getData(data) {
console.log("skadjskansdkadakkkanadkjadskja");
$.getJSON("{TEMPLATEURL}/scripts/Provinsi.json", function( data ) {
});
}
$(document).ready(function(){
selectFilterByCode();
$("#answer418893X4X21").change(function(){
getData();
alert($("#answer418893X4X21").val());
});
}); | 57dac1c964b3fceaa0ee65da89138dfdea5d04c0 | [
"Markdown",
"JavaScript",
"Dockerfile",
"PHP"
] | 8 | Markdown | sandisunandar99/crowdsource-app | 7444c7f1feaa165f22b24b8dd6581bd51d92ce8e | c4220d164ab018a1e04823a131cb2d8c9dc1cf22 |
refs/heads/master | <file_sep>#!/bin/bash
# done just once
if ! $(wp core is-installed --allow-root); then
# install wordpress
wp core install --url='{placeholder}.localhost' --title='{placeholder}' --admin_user=admin --admin_password=<PASSWORD> --admin_email='<EMAIL>' --skip-email --allow-root
# clean up
wp rewrite structure '/%postname%/' --hard --allow-root
wp plugin uninstall hello --deactivate --allow-root
wp plugin uninstall akismet --deactivate --allow-root
fi
if [ ! -d /var/www/html/wp-content/plugins/mailhog-wp-smtp/ ]; then
# dependencies
wp plugin install 'https://github.com/Kubitomakita/mailhog-wp-smtp/archive/master.zip' --activate --allow-root
fi
<file_sep>version: '2'
services:
wordpress:
image: dawidurbanski/wordpress
links:
- db:mysql
- mailhog
ports:
- 80:80
domainname: {placeholder}.localhost
hostname: {placeholder}
volumes:
- ./config/wp.sh:/var/www/html/wp.sh
- ./config/uploads.ini:/usr/local/etc/php/conf.d/uploads.ini
- ./plugins:/var/www/html/wp-content/plugins
- ./themes/{placeholder}:/var/www/html/wp-content/themes/{placeholder}
environment:
WORDPRESS_DB_PASSWORD: <PASSWORD>
depends_on:
- mailhog
- db
mailhog:
image: mailhog/mailhog
ports:
- 1025:1025
- 8025:8025
db:
image: mysql
ports:
- 3306:3306
environment:
MYSQL_ROOT_PASSWORD: <PASSWORD>
| 545ae727f729cf5290c6c784525baf88b811adce | [
"YAML",
"Shell"
] | 2 | Shell | DawidUrbanski/wordpress-docker-app | 37604526a2b0744c001e9a705a0c6a9982a569ea | d2b307e911566ac38a30f67d6bda274cdc67599a |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
Node *head = NULL;
void push(int data);
int pop(void);
void display(void);
void deleteStack(void);
int main()
{
int choice, value;
puts("------Menu------");
puts("1. Push");
puts("2. Pop");
puts("3. Display");
puts("4. Clear");
puts("5. exit");
while(1)
{
printf("\nEnter your selection: ");
scanf("%d",&choice);
puts("");
switch(choice)
{
case 1: printf("Enter a value: ");
scanf("%d",&value);
push(value);
break;
case 2: value = pop();
printf("Popped value: %d\n",value);
break;
case 3: display();
break;
case 4: deleteStack();
break;
case 5: exit(0);
default: puts("Invalid input");
}
}
return 0;
}
void push(int data)
{
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
if(head ==NULL)
{
head = newNode;
newNode->next = NULL;
}
else
{
newNode->next = head;
head = newNode;
}
printf("\nThe value %d has been has been successfully pushed\n",data);
}
int pop()
{
if(head == NULL)
{
puts("The List is Empty ");
return 0;
}
else
{
int value;
Node* temp = (Node*)malloc(sizeof(Node));
temp = head;
value = temp->data;
head = temp->next;
free(temp);
return value;
}
}
void display()
{
if(head ==NULL)
puts("The list is empty");
else
{
Node* temp = (Node*)malloc(sizeof(Node));
temp = head;
while(temp->next != NULL)
{
printf("%d,",temp->data);
temp = temp->next;
}
printf("%d\n",temp->data);
temp = temp->next;
free(temp);
}
}
void deleteStack()
{
if(head==NULL)
{
puts("The list is already empty");
return;
}
Node* current = (Node*)malloc(sizeof(Node));
Node* next= (Node*)malloc(sizeof(Node));
current = head;
next = current->next;
while(next!=NULL)
{
free(current);
current = next;
next = next->next;
}
head = NULL;
puts("The stack has successfully been deleted");
}
<file_sep>
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node* next;
struct Node* prev;
}Node;
Node* head;
Node* tail;
Node* getNewNode(int data);
void addToHead();
void addToEnd(int data);
void addToPosition(int data, int position);
void removePosition();
void reverse();
void display();
void displayReverse();
void removePosition(int n);
int main()
{
head = NULL;
addToEnd(1);
addToEnd(2);
addToEnd(3);
display();
addToHead(4);
addToHead(5);
addToHead(6);
display();
addToPosition(7, 0);
addToPosition(8, 1);
addToPosition(9, 2);
display();
displayReverse();
reverse();
display();
removePosition(0);
display();
removePosition(1);
removePosition(6);
display();
printf("%d\n",head->data);
return 0;
}
void addToHead(int data)
{
Node* newNode = getNewNode(data);
Node* last = head->prev;
newNode->next = head;
head->prev=newNode;
newNode->prev = last;
last->next = newNode;
head = newNode;
}
Node* getNewNode(int data)
{
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->next = NULL;
newNode->prev = NULL;
newNode->data = data;
return newNode;
}
void addToEnd(int data)
{
Node* newNode = getNewNode(data);
if(head==NULL)
{
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode;
newNode->prev = tail;
newNode->next = head;
head->prev=newNode;
tail = newNode;
}
}
void addToPosition(int data, int position)
{
Node* newNode = getNewNode(data);
Node* temp=head;
if(position == 0)
{
addToHead(data);
return;
}
for(int i =0; i<position-1;i++)
{
temp= temp->next;
}
temp->next->prev = newNode;
newNode->next = temp->next;
temp->next = newNode;
newNode->prev = temp;
}
void reverse()
{
if(head==NULL)
return;
Node* temp = head;
Node* next;
do
{
next= temp->next;
temp->next = temp->prev;
temp->prev = next;
temp = next;
}
while(temp!=head);
head = temp->next;
}
void display()
{
if(head==NULL)
return;
Node * temp =head;
do
{
printf("%d ",temp->data);
temp = temp->next;
}
while(temp!=head);
puts("");
return;
}
void displayReverse()
{
if(head==NULL)
return;
Node* temp = head;
do
{
printf("%d ",temp->prev->data);
temp = temp->prev;
}
while (temp!=head);
puts("");
return;
}
void removePosition(int n)
{
Node* temp = head;
if(n==0){
head = temp->next;
temp->prev->next = temp->next;
free(temp);
return;
}
for(int i =0;i<n;i++)
{
temp = temp->next;
}
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
free(temp);
return;
}
| c1f0f92a31a7f904c62f148da3ffaac13dd90af8 | [
"C"
] | 2 | C | EricFill99/Data-Structures | a569b6e889b8590913e8b9928661969e1556464f | acf276b64372332ad5de0461875284d3a7bc52bc |
refs/heads/master | <repo_name>vavalm/discord_bot_tortue_geniale<file_sep>/tortue_geniale/tg_channel_events.py
import discord
import asyncio
import re
import logging
from data.groups_name import free_random_name
logging.basicConfig(level=logging.INFO)
client = discord.Client()
class ClientEvents(discord.Client):
'''
Classe initialization
'''
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# create the background task and run it in the background
self.bg_task = self.loop.create_task(self.my_background_task())
async def my_background_task(self):
await self.wait_until_ready()
counter = 0
channel = self.get_channel(1234567) # channel ID goes here
while not self.is_closed():
counter += 1
await channel.send(counter)
await asyncio.sleep(60) # task runs every 60 seconds
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
''' ############### EVENTS ABOUT CHANNELS AND SERVERS MANAGEMENT ###############'''
async def on_member_join(self, member):
guild = member.guild
if guild.system_channel is not None:
to_send = 'Welcome {0.mention} to {1.name}!'.format(member, guild)
await guild.system_channel.send(to_send)
'''
Permet la création et la suppression automatique de channels
'''
async def on_voice_state_update(self, member: discord.Member, before: discord.VoiceState,
after: discord.VoiceState):
await self.wait_until_ready()
after_channel: discord.VoiceChannel = after.channel
before_channel: discord.VoiceChannel = before.channel
# We enter in a channel
if type(after_channel) is discord.VoiceChannel:
category: discord.CategoryChannel = after_channel.category
guild: discord.guild = member.guild
if "Escouade".lower() in str(category.name).lower() and (
"Créer channel").lower() == after_channel.name.lower():
team_size = re.findall(r'\d+', category.name)
if len(team_size) == 0:
return
else:
team_size = int(re.findall(r'\d+', category.name)[0])
print("Création nouveau Channel")
new_name = free_random_name(team_size, guild)
new_channel: discord.VoiceChannel = await guild.create_voice_channel(
new_name,
category=category,
user_limit=int(team_size))
await member.move_to(new_channel)
# If we quit a channel and no one else is in, deletion of the channel
if type(before_channel) is discord.VoiceChannel \
and ("Créer channel").lower() != before_channel.name.lower():
if len(before_channel.members) == 0:
await before_channel.delete(reason="Channel empty")
''' ############### EVENTS ABOUT REPLIES ON MESSAGE ###############'''
@client.event
async def on_message(self, message):
# we do not want the bot to reply to itself
if message.author.id == self.user.id:
return
if message.content.startswith('!hello'):
await message.channel.send('Hello {0.author.mention} sur le serveur {1.guild}'.format(message, message))
class CommandsClient(discord.Client):
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_member_join(self, member):
guild = member.guild
if guild.system_channel is not None:
to_send = 'Welcome {0.mention} to {1.name}!'.format(member, guild)
await guild.system_channel.send(to_send)
async def on_message(message):
if message.content.startswith('$greet'):
channel = message.channel
await channel.send('Say hello!')
def check(m):
return m.content == 'hello' and m.channel == channel
msg = await client.wait_for('message', check=check)
await channel.send('Hello {.author}!'.format(msg))
<file_sep>/main.py
from tortue_geniale.tg_channel_events import ClientEvents
import os
if __name__ == '__main__':
client = ClientEvents()
client.run(os.getenv('DISCORD_TG_KEY'))<file_sep>/requirements.txt
aiohttp<3.6.0
websockets<7.0
asyncio
#discord
<file_sep>/tortue_geniale/tg_commands.py
import discord
from discord.ext import commands
import random
import logging
logging.basicConfig(level=logging.INFO)
description = '''Coucou je suis <NAME>, si tu veux mes deux boules de cristalle,
fais moi voir ta culotte'''
bot = commands.Bot(command_prefix='?', description=description)
class ClientChannelEvents(discord.ext.commands):
@bot.event
async def on_ready(self):
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.command()
async def roll(self, ctx, dice: str):
"""Rolls a dice in NdN format."""
try:
rolls, limit = map(int, dice.split('d'))
except Exception:
await ctx.send('Format has to be in NdN!')
return
result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))
await ctx.send(result)
@bot.command(description='For when you wanna settle the score some other way')
async def choose(self, ctx, *choices: str):
"""Chooses between multiple choices."""
random.seed()
await ctx.send(random.choice(choices))
@bot.command()
async def repeat(self, ctx, times: int, content='repeating...'):
"""Repeats a message multiple times."""
for i in range(times):
await ctx.send(content)
@bot.command()
async def joined(self, ctx, member: discord.Member):
"""Says when a member joined."""
await ctx.send('{0.name} joined in {0.joined_at}'.format(member))
@bot.group()
async def cool(self, ctx):
"""Says if a user is cool.
In reality this just checks if a subcommand is being invoked.
"""
if ctx.invoked_subcommand is None:
await ctx.send('No, {0.subcommand_passed} is not cool'.format(ctx))
@cool.command(name='bot')
async def _bot(self, ctx):
"""Is the bot cool?"""
await ctx.send('Yes, the bot is cool.')<file_sep>/data/groups_name.py
from random import seed, randrange
from datetime import datetime
import discord
DUO = [
'C-3PO & R2-D2',
'Harry & Lloy',
'Batman & Robin ',
'Will & Carlton',
'Michael & Kitt',
'MR Burns & Smithers',
'Mario & Luigi',
'Starsky & Hutch',
'Harold & Kumar',
'Astérix & Obélix',
'Dupond & Dupont ',
'Spirou & Fantasio',
'Tintin & Milou',
'Olive & Tom',
'Satanas & Diabolo',
'Tic & Tac',
'Titi & Grosminet',
'Timon & Pumbaa',
'Tom & Jerry',
'Minux & Cortex ',
'Ratchet & Clank',
'MARTY & DOC',
'Han Solo & Chewbacca',
'Goku & Vegeta',
'Woody & Buzz',
'Itchy & Scratchy',
'Sam & Frodon',
'Boule & Bill',
'Lilo & Stitch',
'Rox & Rouky',
'Laurel & Hardy'
]
QUATUOR = [
'Les 4 fantastiques',
'Adibou & Les 3 petits chats',
'Ghostbusters',
'Les tortues ninja',
'Cartman, Stan, Kenny & Kyle',
'Les Daltons',
'Les Teletubbies',
'Les power rangers',
"Les Beatles"
]
OCTO = [
"Les carottes sont qu'huit",
"Les 8 rennes du père noël",
"L'octet",
"Les 8 chevrons SG1",
"Les 8 bits"
]
GROUPS_NAMES = {
2: DUO,
4: QUATUOR,
8: OCTO
}
def random_name(size):
names = GROUPS_NAMES[size]
seed(datetime.now())
nb = randrange(0, len(names))
return names[nb]
''' Generate a random name from the lists but verify if it's not already taken'''
# TODO : lorsque tous les noms sont utilisés : boucle infinie à régler
def free_random_name(size, guild: discord.guild):
new_name = None
channels = guild.voice_channels
while new_name is None or new_name in channels:
new_name = random_name(size)
return new_name
| 654911f49a30c6abe82e82efd6767c4e1abe87bf | [
"Python",
"Text"
] | 5 | Python | vavalm/discord_bot_tortue_geniale | 2fa2865166dd109b1138b77ed7f21d8e59efd8ab | a4e45c26a233e83e266cf3cdf82c4a7e31a2b411 |
refs/heads/main | <file_sep>package com.customterrarium;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/static/media/**")
.addResourceLocations("C:\\Users\\User\\Documents\\<NAME>\\myshop\\src\\main\\resources\\static\\media");
}
}
<file_sep>$(function () {
$("a.confirmDeletion").click(function () {
if (!confirm("Confirm deletion")) return false;
});
if ( $("#content").length) {
ClassicEditor
.create(document.querySelector("#content"))
.catch(error => {
console.log(error);
});
}
if ( $("#description").length) {
ClassicEditor
.create(document.querySelector("#description"))
.catch(error => {
console.log(error);
});
}
});
// Loads preview of uploaded photo
function readURL(input, idNum) {
if (input.files && input.files[0]) {
let reader = new FileReader();
reader.onload = function (e) {
$("#imgPreview" + idNum).attr("src", e.target.result).width(100).height(100);
}
reader.readAsDataURL(input.files[0]);
}
}
// Finding elements in the DOM
const form = document.getElementsByTagName('form')[0];
const email = document.getElementById('mail');
let error = email;
while ((error = error.nextSibling).nodeType != 1);
// Email regular expression
const emailRegExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
/* Function that does what addEventListener method would've done, callback returns false
and interrupts the event callback */
function addEvent(element, event, callback) {
let previousEventCallBack = element["on"+event];
element["on"+event] = function (e) {
const output = callback(e);
if (output === false)
return false;
if (typeof previousEventCallBack === 'function') {
let output = previousEventCallBack(e);
if(output === false)
return false;
}
}
};
// Test if it's empty field or valid email entered
addEvent(window, "load", function () {
const test = email.value.length === 0 || emailRegExp.test(email.value);
email.className = test ? "valid" : "invalid";
});
// Defines what happens when the user types into the field
addEvent(email, "input", function () {
const test = email.value.length === 0 || emailRegExp.test(email.value);
if (test) {
email.className = "valid";
error.textContent = "";
error.className = "error";
} else {
email.className = "invalid";
}
});
// Defines what happens when the user tries to Submit
addEvent(form, "submit", function () {
const test = email.value.length === 0 || emailRegExp.test(email.value);
if (!test) {
email.className = "invalid";
error.textContent = "Please type in a valid email";
error.className = "error active";
return false;
} else {
email.className = "valid";
error.textContent = "";
error.className = "error";
}
});
// Displays alert with user Submits
function submitAlert() {
alert("Thanks! Submission Received!");
}<file_sep>###### [GitHub Repository](https://github.com/imjesska/casestudy)
# <NAME> Case Study
#### Project Summary: Build an application using Spring Boot
**Work Flow**
>-Have at least 4 models
>
>-Have DAO that are composed of one or more functions and have direct access to the database
>
>-Use HTML for static and dynamic pages and markup the structure of every page
>
>-Use CSS to style HTML pages

**Website Concepts:**
>-This pseudo-website is for my friend that sells her crafts as a side-gig
>
>-Registration/Login requests made by the user
>
>-Admin can create, update, delete pages, categories, and products
>
>-A cart that can hold products to be purchased
>
>-Implement a sandbox payment system for a way for users to purchase products
**Notes/Comments:**
* [x] Needs commenting and tests for DAO
* [x] Used BCrypt to hash passwords
* [x] Used Lombok
* [x] Used Bootstrap and Thymeleaf
* [x] Referred to StackOverflow and previous group SMS exercise for guidance
| 83caf8dbd817bb482e14bb07a80265f5368f83ea | [
"JavaScript",
"Java",
"Markdown"
] | 3 | Java | imjesska/casestudy | b9c38c3c3a71c84048b106260393aa6a47c4ee73 | 7112b1b4e1f5ca2070fa927a7e9400d34b098d05 |
refs/heads/master | <file_sep>import React from "react";
import classes from "./Rinse.module.css";
const rinse = props => {
const { method, defaultRecovery, recovery } = props.rinseData;
return (
<div>
<label className={classes.LABEL}>
Method
<input
type="text"
name="method"
value={method}
onChange={props.handler}
/>
</label>
<br />
<label className={classes.DEFAULTRECOVERY}>
Default Recovery (%)
<input
type="number"
name="defaultRecovery"
value={defaultRecovery}
onChange={props.handler}
/>
</label>
<button
className={classes.BUTTON}
name="addMOCRinse"
value={props.addMOCRinse}
onClick={props.mocRenderHandler}
>
Add MOC
</button>
{props.addMOCRinse === false ? null : (
<div className={classes.LABEL2}>
<label className={classes.LABEL2SELECT}>
Select MOC
<select name="mocOption" onChange={props.handler}>
<option>Please Select a Value</option>
<option value="stainless-steel">Stainless Steel</option>
<option value="glass">Glass</option>
<option value="teflon">Teflon</option>
<option value="plastic">Plastic</option>
</select>
</label>
<label className={classes.LABEL2RECOVERY}>
Recovery{" "}
<input
type="number"
name="recovery"
value={recovery}
onChange={props.handler}
/>
</label>
</div>
)}
</div>
);
};
export default rinse;
<file_sep>import React from "react";
import Aux from "../../hoc/Aux";
import Swab from "../Swab/Swab";
import Rinse from "../Rinse/Rinse";
import classes from "./APICleaningComponent.module.css";
const APICleaningComponent = props => {
let configSwab = "Configure Swab Sampling Parameters";
let removeSwab = "Remove Swab Sampling Parameters";
let configRinse = "Configure Rinse Sampling Parameters";
let removeRinse = "Remove Rinse Sampling Parameters";
// SWAB
let mocHandler = props.mocHandler;
let swabDataProp = props.swabData;
//RINSE
let rinseData = props.rinseData;
let rinseMOC = props.rinseMOC;
const buttonStyleActive = {
border: "2px solid #ff8dac",
color: "#fc3368"
};
const buttonStyle = {
border: "2px solid #9dd0ff",
color: "#1890ff"
};
return (
<Aux>
<div className={classes.LABEL}>
<label>
* LOD(in ppm)
<input
type="number"
name="LOD"
value={props.lod}
placeholder="Enter LOD Value"
onChange={props.formHandler}
/>
</label>
<label>
* LOQ(in ppm)
<input
type="number"
name="LOQ"
value={props.loq}
placeholder="Enter LOQ Value"
onChange={props.formHandler}
/>
</label>
</div>
<br />
<button
style={props.addSwabProp === true ? buttonStyleActive : buttonStyle}
className={classes.BUTTON}
onClick={props.enableSwab}
>
{props.addSwabProp === true ? removeSwab : configSwab}
</button>
{props.addSwabProp === true ? (
<Swab
swabData={swabDataProp}
handler={mocHandler}
mocRenderHandler={props.mocRenderHandler}
addMOCSwab={props.addMOCSwab}
/>
) : null}
<button
style={props.addRinseProp === true ? buttonStyleActive : buttonStyle}
className={classes.BUTTON}
onClick={props.enableRinse}
>
{props.addRinseProp === true ? removeRinse : configRinse}
</button>
{props.addRinseProp === true ? (
<Rinse
rinseData={rinseData}
handler={rinseMOC}
mocRenderHandler={props.mocRenderHandler}
addMOCRinse={props.addMOCRinse}
/>
) : null}
{/* <Swab /> */}
</Aux>
);
};
export default APICleaningComponent;
<file_sep>import React from "react";
import Aux from "../../hoc/Aux";
import classes from "./Reason.module.css";
const Reason = props => {
return (
<Aux>
<label className={classes.LABEL}>
Reason
<input
type="text"
name="mainReason"
value={props.reason}
onChange={props.formChangeHandler}
required
/>
</label>
</Aux>
);
};
export default Reason;
<file_sep>import React, { Component } from "react";
import AnalyticalMethodID from "./AnalyticalMethodID/AnalyticalMethodID";
import TargetResidueType from "./TargetResidueType/TargetResidueType";
import Reason from "./Reason/Reason";
import classes from "./MainForm.module.css";
class MainForm extends Component {
state = {
analyticalMethodID: "",
mainReason: "",
option: "",
define: "",
LOD: "",
LOQ: "",
option1: null,
MethodUsed: "",
TNTCLimit: "",
TFTCLimit: "",
reason: "",
addSwab: false,
addSwab2: false,
swabData: {
methodUsed: "",
solventName: "",
solventQuantity: "",
defaultRecovery: "",
mocOption: "",
mocRecovery: ""
},
swabData2: {
defaultRecovery: "",
mocOption: "",
recovery: ""
},
rinseData: {
method: "",
defaultRecovery: "",
mocOption: "",
recovery: ""
},
rinse2Data: {
solventVolume: "",
defaultRecovery: "",
mocOption: "",
recovery: ""
},
addRinse: false,
addRinse2: false,
addMOCSwab: false,
addMOCSwab2: false,
addMOCRinse: false,
addMOCRinse2: false
};
mocRenderHandler = e => {
const { name } = e.target;
this.setState({
[name]: !this.state[name]
});
};
setOption = e => {
e.preventDefault();
const { value } = e.target;
this.setState({
option: value
});
};
formChangeHandler = e => {
e.preventDefault();
const { name, value } = e.target;
this.setState({
[name]: value
});
};
defineTNTCandTFTCHandler = e => {
e.preventDefault();
const { name, value } = e.target;
this.setState({
[name]: value
});
};
swabEnableHandler = e => {
e.preventDefault();
this.setState({
addSwab: !this.state.addSwab
});
};
swab2EnableHandler = e => {
e.preventDefault();
this.setState({
addSwab2: !this.state.addSwab2
});
};
swabMOCHandler = e => {
e.preventDefault();
const { name, value } = e.target;
console.log(name, value);
this.setState({
swabData: { ...this.state.swabData, [name]: value }
});
};
swabMOCHandler2 = e => {
e.preventDefault();
const { name, value } = e.target;
this.setState({
swabData2: { ...this.state.swabData2, [name]: value }
});
};
rinseEnableHandler = e => {
e.preventDefault();
this.setState({
addRinse: !this.state.addRinse
});
};
rinse2EnableHandler = e => {
e.preventDefault();
this.setState({
addRinse2: !this.state.addRinse2
});
};
rinseMOCHandler = e => {
e.preventDefault();
const { name, value } = e.target;
this.setState({
rinseData: { ...this.state.rinseData, [name]: value }
});
};
rinseMOCHandler2 = e => {
e.preventDefault();
const { name, value } = e.target;
this.setState({
rinse2Data: { ...this.state.rinse2Data, [name]: value }
});
};
formSubmithandler = e => {
e.preventDefault();
console.log(this.state);
// console.table(this.state);
alert("The Form has been submitted successfully!");
};
render() {
return (
<div>
<form type="submit" action="POST" className={classes.FORM}>
<AnalyticalMethodID
formChangeHandler={this.formChangeHandler}
methodID={this.state.analyticalMethodID}
/>
<TargetResidueType
state={this.state}
setOption={this.setOption}
formChangeHandler={this.formChangeHandler}
defineTNTCandTFTCHandler={this.defineTNTCandTFTCHandler}
swabEnableHandler={this.swabEnableHandler}
swab2EnableHandler={this.swab2EnableHandler}
swabMOCHandler={this.swabMOCHandler}
swabMOCHandler2={this.swabMOCHandler2}
rinseEnableHandler={this.rinseEnableHandler}
rinse2EnableHandler={this.rinse2EnableHandler}
rinseMOCHandler={this.rinseMOCHandler}
rinseMOCHandler2={this.rinseMOCHandler2}
mocRenderHandler={this.mocRenderHandler}
addMOCSwab={this.state.addMOCSwab}
addMOCSwab2={this.state.addMOCSwab2}
addMOCRinse={this.state.addMOCRinse}
addMOCRinse2={this.state.addMOCRinse2}
/>
<Reason
reason={this.state.mainReason}
formChangeHandler={this.formChangeHandler}
/>
<button
type="submit"
className={classes.BUTTON}
onClick={this.formSubmithandler}
>
Submit Form
</button>
</form>
</div>
);
}
}
export default MainForm;
<file_sep>import React from "react";
import classes from "./Rinse2.module.css";
import Aux from "../../hoc/Aux";
const rinse = props => {
const { solventVolume, defaultRecovery, recovery } = props.rinseData;
return (
<div className={classes.PARENT}>
<label className={classes.LABEL1}>
Solvent Volume
<input
type="number"
name="solventVolume"
value={solventVolume}
onChange={props.handler}
/>
</label>
<br />
<label className={classes.LABEL2}>
Use Recovery for Swab?
<div>
<input type="radio" value="yes" />
Yes
<input type="radio" value="no" />
No
</div>
</label>
<label className={classes.LABEL3}>
Default Recovery (%)
<input
type="number"
name="defaultRecovery"
value={defaultRecovery}
onChange={props.handler}
/>
</label>
<button
className={classes.BUTTON}
value={props.addMOCRinse2}
name="addMOCRinse2"
onClick={props.mocRenderHandler}
>
Add MOC
</button>
{props.addMOCRinse2 === false ? null : (
<Aux>
<div className={classes.LABELX}>
<label className={classes.LABELXSELECT}>
Select MOC
<select name="mocOption" onChange={props.handler}>
<option>Please Select a Value</option>
<option value="stainless-steel">Stainless Steel</option>
<option value="glass">Glass</option>
<option value="teflon">Teflon</option>
<option value="plastic">Plastic</option>
</select>
</label>
<label label className={classes.LABELXRECOVERY}>
Recovery
<input
type="number"
name="recovery"
value={recovery}
onChange={props.handler}
/>
</label>
</div>
</Aux>
)}
</div>
);
};
export default rinse;
<file_sep>import React from "react";
import Rinse2 from "../Rinse/Rinse2";
import Swab2 from "../Swab/Swab2";
import Aux from "../../hoc/Aux";
import classes from "./BioBurden.module.css";
const BioburdenEndotoxinComponent = props => {
let renderTFTCTNTC = null;
let configSwab = "Configure Swab Sampling Parameters";
let removeSwab = "Remove Swab Sampling Parameters";
let configRinse = "Configure Rinse Sampling Parameters";
let removeRinse = "Remove Rinse Sampling Parameters";
//SWAB
let swabData = props.swabData2;
let mocHandler = props.mocHandler2;
//RINSE
let rinseData = props.rinse2Data;
let rinseMOC = props.rinseMOC;
const buttonStyleActive = {
border: "2px solid #ff8dac",
color: "#fc3368"
};
const buttonStyle = {
border: "2px solid #9dd0ff",
color: "#1890ff"
};
if (props.define === "yes") {
renderTFTCTNTC = (
<div className={classes.TFTCTNTC}>
<label className={classes.TNTC}>
TNTC Limit (in CFU)
<input
type="number"
name="TNTCLimit"
value={props.tntclimit}
placeholder=""
onChange={props.formHandler}
/>
</label>
<label className={classes.TFTC}>
TFTC Limit (in CFU)
<input
type="number"
name="TFTCLimit"
value={props.tftclimit}
placeholder=""
onChange={props.formHandler}
/>
</label>
</div>
);
}
return (
<Aux>
<br />
<label className={classes.LABEL}>
* Method Used
<input
type="text"
name="MethodUsed"
value={props.MethodUsed}
placeholder=""
onChange={props.formHandler}
/>
</label>
<br />
<label className={classes.LABEL}>
*Define TNTC and TFTC
<div>
<input
type="radio"
name="define"
value="yes"
onClick={props.formHandler}
name="define"
checked={props.define === "yes" ? true : null}
/>
Yes
<input
type="radio"
name="define"
value="no"
onClick={props.formHandler}
name="define"
checked={props.define === "no" ? true : null}
/>
No
</div>
</label>
<br />
{renderTFTCTNTC}
<button
className={classes.BUTTON}
style={props.addSwab2Prop === true ? buttonStyleActive : buttonStyle}
onClick={props.enableSwab2}
>
{props.addSwab2Prop === true ? removeSwab : configSwab}
</button>
{props.addSwab2Prop === true ? (
<Swab2
swabData={swabData}
handler={mocHandler}
mocRenderHandler={props.mocRenderHandler}
addMOCSwab2={props.addMOCSwab2}
/>
) : null}
<button
className={classes.BUTTON}
style={props.addRinse2Prop === true ? buttonStyleActive : buttonStyle}
onClick={props.enableRinse2}
>
{props.addRinse2Prop === true ? removeRinse : configRinse}
</button>
{props.addRinse2Prop === true ? (
<Rinse2
rinseData={rinseData}
handler={rinseMOC}
mocRenderHandler={props.mocRenderHandler}
addMOCRinse2={props.addMOCRinse2}
/>
) : null}
{/* <Swab /> */}
</Aux>
);
};
export default BioburdenEndotoxinComponent;
| e02d39697fef808eb71015d86d3911d5b12e6e37 | [
"JavaScript"
] | 6 | JavaScript | shreyas1307/analytical-method-form | f66b12f9788657f4e128353411e68cd3c0bd97f8 | bf4148df0dbd442051723352a7092c58b1532f5a |
refs/heads/master | <repo_name>mehmetbarispolat/tagsisApp<file_sep>/README.md
# tagsisApp
https://tagsis-control-platform.herokuapp.com
<file_sep>/app/app.py
from flask import Flask,render_template,redirect,request,url_for, jsonify
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
""" GLOBAL VARIABLE """
#------------------------------------------------------------
SERVICE_KEY_PATH = './serviceAccountKey.json'
#------------------------------------------------------------
""" FIREBASE CONNECT"""
#------------------------------------------------------------
cred = credentials.Certificate(SERVICE_KEY_PATH)
firebase_admin.initialize_app(cred)
db = firestore.client()
#------------------------------------------------------------
app = Flask(__name__)
@app.route('/')
def index():
return render_template("home.html")
@app.route('/map')
def map():
return render_template("jquerymap.html")
@app.route('/', methods=['GET', 'POST'])
def search():
if request.method == 'POST':
searchInput = request.form['searchInput']
return redirect(url_for("getResult",searchInput = searchInput))
@app.route('/getResult/<searchInput>')
def getResult(searchInput):
list_of_tagsis = searchTagsis(searchInput)
return render_template("home.html",list_of_tagsis = list_of_tagsis)
@app.route('/getMap/<searchInput>',methods=[ 'POST'])
def getMap(searchInput):
if request.method == 'POST':
list_of_region = searchRegion(searchInput)
return jsonify({'data': render_template('response.html', list_of_tagsis=list_of_region)})
def searchTagsis(searchInput):
list_of_tagsis = []
tagsis_ref = db.collection(u'tagsis')
docs = tagsis_ref.stream()
searchInput = searchInput.replace('I','ı').lower()
for doc in docs:
if searchInput in doc.to_dict()["productName"].lower() or searchInput in doc.to_dict()["brand"].lower() or searchInput in doc.to_dict()["companyName"].replace('İ','i').replace('I','ı').lower():
list_of_tagsis.append(doc.to_dict())
return list_of_tagsis
def searchRegion(searchInput):
list_of_region = []
region_ref = db.collection(u'tagsis')
docs = region_ref.stream()
searchInput = searchInput.replace('ı','I')
for doc in docs:
if searchInput.replace('i','İ').upper() in doc.to_dict()["companyName"]:
list_of_region.append(doc.to_dict())
return list_of_region
"""
tagsis_ref = db.collection(u'tagsis')
docs = tagsis_ref.stream() ## Tüm verileri alır. --> .stream()
for doc in docs:
print(f'{doc.id} => {doc.to_dict()}')
"""
#return render_template('index.html', productName = doc.to_dict()["productName"], brand = doc.to_dict()["brand"], companyName = doc.to_dict()["companyName"])#setdefault dict. | 4d75401c35c2350461ec370e98521a1de5dba1bb | [
"Markdown",
"Python"
] | 2 | Markdown | mehmetbarispolat/tagsisApp | 31b380fa82f7a964731d89ab01d714038a4d4d14 | e2589415c296c9f77ded87ccafbd3290a2caeb0a |
refs/heads/master | <file_sep>module.exports = function(grunt) {
grunt.initConfig({
clean: {
style: ['css', 'styleguide']
},
copy: {
styleguide: {
files: [
{ src: ['sass/styleguide.md'], dest: 'css/styleguide.md'}
]
}
},
sass: {
development: {
options: {
style: 'expanded'
},
files: {
'css/style.doc.css': 'sass/style.scss'
}
},
production: {
options: {
style: 'compressed'
},
files: {
'css/style.css': 'sass/style.scss'
}
}
},
shell: {
styleguide: {
command: 'kss-node css styleguide --css css/style.doc.css --template styleguide-template'
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-shell');
grunt.registerTask('default', ['clean', 'sass', 'copy','shell']);
};<file_sep><h1 class="kss-title kss-title-main"> Overview </h1>
This is a demo of [kss-node](http://github.com/hughsk/kss-node)'s built-in styleguide generator. The module is essentially a reimplementation of the [KSS](http://github.com/kneath/kss) Ruby parser, in Node:
This was made with GruntJS, kss-node and others stuff!!! | e84aee86632c44f4d52ade8266207436d73caf8a | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | krismckinnon/customKSSSetup | 2f6dac4afaf3327f70872671f286ebba6ffa75d7 | 78a46f318ac23793142a19d02e1d29de8e7f88dd |
refs/heads/master | <repo_name>LemuelAcosta/Parcial<file_sep>/parcial1/parcial1/Program.cs
using System;
namespace parcial1
{
class Program
{
static void Main(string[] args)
{
double prec;
string pag;
Console.WriteLine("Cual es el precio del producto?");
prec = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Cual es la forma de pagar efectivo o tarjeta?");
pag = Console.ReadLine();
if (pag == "tarjeta")
{
string tarj;
Console.WriteLine("Digite el numero de su tarjeta.");
tarj = Console.ReadLine();
int size = tarj.Length;
bool a = true;
if (size == 12)
{ Console.WriteLine("Gracias por su compra!"); }
else
{
if (size != 12)
{
Console.WriteLine("ERROR!! Numero incorrecto");
}
}
}
else
{
Console.WriteLine("Gracias por su compra!");
}
}
}
}
| 84103391f716c4c5f16b1f6d07fe6c1f64fef9bf | [
"C#"
] | 1 | C# | LemuelAcosta/Parcial | 464db56e4369da4cf1513e898fdade99fc3651c0 | 42ca6e8b5034a73a56de677f9de454eb8586e46f |
refs/heads/master | <repo_name>kumboj/comehome<file_sep>/src/main/java/com/kum/daos/CalledFunctionDAO.java
package com.kum.daos;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.metamodel.EntityType;
import com.kum.model.CalledFunction;
public class CalledFunctionDAO {
private static final String PERSISTENCE_UNIT_NAME = "JPAEclipseLinkDemoPU";
public CalledFunction create(CalledFunction obj) throws SQLException {
EntityManagerFactory emf = Persistence
.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(obj);
em.getTransaction().commit();
em.close();
emf.close();
return obj;
}
public CalledFunction findByID(CalledFunction obj) throws SQLException {
if ((Long) obj.getId() == null) {
throw new SQLException("No ID!");
}
EntityManagerFactory emf = Persistence
.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = emf.createEntityManager();
obj = em.find(CalledFunction.class, obj.getId());
em.close();
emf.close();
return obj;
}
public Set<EntityType<?>> findAllNew() {
EntityManagerFactory emf = Persistence
.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = emf.createEntityManager();
Set<EntityType<?>> dl = em.getMetamodel().getEntities();
em.close();
emf.close();
return dl;
}
@SuppressWarnings("unchecked")
public Collection<CalledFunction> findAllCalledFunctions() {
EntityManagerFactory emf = Persistence
.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("SELECT e FROM CalledFunction e");
Collection<CalledFunction> calledFunctions = (Collection<CalledFunction>) query.getResultList();
em.close();
emf.close();
return calledFunctions;
}
public void removeCalledFunction(CalledFunction obj) throws SQLException {
if ((Long) obj.getId() == null) {
throw new SQLException("No ID!");
}
EntityManagerFactory emf = Persistence
.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = emf.createEntityManager();
// fetch entity
em.getTransaction().begin();
CalledFunction toDelete = em.find(CalledFunction.class, obj.getId());
// remove entity
em.remove(toDelete);
em.getTransaction().commit();
em.close();
emf.close();
}
}
<file_sep>/src/main/java/com/kum/StoreData.java
package com.kum;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.kum.model.Location;
import com.kum.model.Device;
import com.kum.model.Function;
public class StoreData {
private static final String PERSISTENCE_UNIT_NAME = "JPAEclipseLinkDemoPU";
public StoreData() {
EntityManagerFactory objEntityManagerFactory = Persistence
.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager objEntityManager = objEntityManagerFactory
.createEntityManager();
// Begin a new local transaction so that we can persist a new entity
objEntityManager.getTransaction().begin();
Function lichtAn = setFunction("Licht an");
objEntityManager.persist(lichtAn);
Function radioAn = setFunction("Radio an");
objEntityManager.persist(radioAn);
Device wohnzimmerBeleuchtung = new Device();
wohnzimmerBeleuchtung.setName("Wohnzimmerbeleuchtung");
wohnzimmerBeleuchtung.getFunctions().add(lichtAn);
objEntityManager.persist(wohnzimmerBeleuchtung);
Device musikAnlage = new Device();
musikAnlage.setName("Musikanlage");
musikAnlage.getFunctions().add(radioAn);
objEntityManager.persist(musikAnlage);
Location wohnort = new Location();
wohnort.setDescription("Neuburg an der Donau");
wohnort.getDevices().add(wohnzimmerBeleuchtung);
wohnort.getDevices().add(musikAnlage);
objEntityManager.persist(wohnort);
wohnzimmerBeleuchtung.setLocation(wohnort);
objEntityManager.persist(wohnzimmerBeleuchtung);
musikAnlage.setLocation(wohnort);
objEntityManager.persist(musikAnlage);
// Commit the transaction, which will cause the entity to be stored in
// the database
objEntityManager.getTransaction().commit();
objEntityManager.close();
objEntityManagerFactory.close();
}
private Function setFunction(String description) {
Function newFunction = new Function();
newFunction.setName(description);
return newFunction;
}
/**
* @param args
*/
public static void main(String[] args) {
new StoreData();
}
}<file_sep>/src/main/java/com/kum/model/Function.java
package com.kum.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement
@Entity
public class Function implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private long id;
private String name;
@ManyToOne
private Device device;
@OneToMany(mappedBy = "function")
private java.util.List<CalledFunction> calledFunctions = new java.util.ArrayList<CalledFunction>();
private static final long serialVersionUID = 1L;
public Function() {
super();
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@XmlTransient
public Device getDevice() {
return device;
}
public void setDevice(Device device) {
this.device = device;
}
@XmlTransient
public java.util.List<CalledFunction> getCalledFunctions() {
return calledFunctions;
}
public void setCalledFunctions(java.util.List<CalledFunction> calledFunctions) {
this.calledFunctions = calledFunctions;
}
}<file_sep>/src/main/java/com/kum/daos/LocationDeviceDAO.java
package com.kum.daos;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.kum.model.Device;
import com.kum.model.Location;
public class LocationDeviceDAO {
private static final String PERSISTENCE_UNIT_NAME = "JPAEclipseLinkDemoPU";
public Device create(Location location, Device device) throws SQLException {
EntityManagerFactory emf = Persistence
.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(device);
location.getDevices().add(device);
em.merge(location);
device.setLocation(location);
em.persist(device);
em.getTransaction().commit();
em.close();
emf.close();
// Device musikAnlage = new Device();
// musikAnlage.setName("Musikanlage");
// objEntityManager.persist(musikAnlage);
//
// Location wohnort = new Location();
// wohnort.setDescription("Neuburg an der Donau");
// wohnort.getDevices().add(musikAnlage);
// objEntityManager.persist(wohnort);
//
// musikAnlage.setLocation(wohnort);
// objEntityManager.persist(musikAnlage);
//
// // Commit the transaction, which will cause the entity to be stored in
// // the database
// objEntityManager.getTransaction().commit();
//
// objEntityManager.close();
// objEntityManagerFactory.close();
return device;
}
}
<file_sep>/src/main/java/com/kum/ws/DeviceFunctionResource.java
package com.kum.ws;
import java.sql.SQLException;
import java.util.Collection;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.kum.daos.DeviceDAO;
import com.kum.daos.DeviceFunctionDAO;
import com.kum.model.Device;
import com.kum.model.Function;
@Path("/location/{location: [0-9]* }/device/{device: [0-9]* }/function/")
public class DeviceFunctionResource {
@PathParam("device") long device;
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Collection<Function> getAllFunctionsForDevice() throws SQLException {
DeviceDAO daoDevice = new DeviceDAO();
Device currentDevice = new Device();
currentDevice.setId(device);
Device curDev = daoDevice.findByID(currentDevice);
Collection<Function> functions = curDev.getFunctions();
return functions;
}
@Path("new/{name: .* }")
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Function setFunction(@PathParam("name") String name) throws SQLException{
DeviceFunctionDAO daoDeviceFunction = new DeviceFunctionDAO();
Function newFunction = new Function();
newFunction.setName(name);
DeviceDAO daoDevice = new DeviceDAO();
Device currentDevice = new Device();
currentDevice.setId(device);
Device curDev = daoDevice.findByID(currentDevice);
curDev.getFunctions().add(newFunction);
newFunction.setDevice(currentDevice);
daoDeviceFunction.create(curDev, newFunction);
return newFunction;
}
}
<file_sep>/README.md
comehome
========
| 1852ed8f4da10be356d06986b11f9e41a18e9047 | [
"Markdown",
"Java"
] | 6 | Java | kumboj/comehome | 396eecef9f2bf26fd682050224709a37372d0b19 | e98b1b8f7c8c12cee5c0a9a5cfb0293987ff87be |
refs/heads/master | <repo_name>vikramarka/createjsbitmaptext<file_sep>/src/js/text/HAlign.js
(function(window) {
HAlign = function(){
}
HAlign.CENTER = "center";
HAlign.LEFT = "left";
HAlign.RIGHT = "right";
window.HAlign = HAlign;
})(window);<file_sep>/src/js/text/BitmapTextField.js
(function(window)
{
/**
*
* @param width: width of the text field
* @param height: height of the text field
* @param text: text to be displayed
* @param fontName: name of the font give while registering the font.
* @param fontSize: size of the font, -1 to keep the font size as exported
* @param horizantalLetterSpacing: Horizantal letter space
* @param verticalLetterSpacing: line spacing
* @param hAlign: Horizantal alignment: accepted parameters: "left","right","center", default:"center"
* @param vAlign: Verticle alignment: accepter parameters: "top","center",""bottom", default:"center"
* @param autoScale: true, scales the text to fit in the space, default: true
*/
BitmapTextField = function (width, height, text, fontName,fontSize,horizantalLetterSpacing,verticalLetterSpacing,hAlign,vAlign,autoScale)
{
this.Container_constructor();
this.font = null;
if(horizantalLetterSpacing==null)
horizantalLetterSpacing = 1;
if(verticalLetterSpacing == null)
verticalLetterSpacing = 1;
if(hAlign == null)
hAlign = "center";
if(vAlign == null)
vAlign = "center";
if(autoScale==null)
autoScale = true;
this.hAlign = hAlign;
this.vAlign = vAlign;
this.autoScale = autoScale;
this.color = "";
this.initialize(width, height, text, fontName,fontSize,horizantalLetterSpacing,verticalLetterSpacing,hAlign,vAlign,autoScale);
this.containerWidth = width;
this.containerHeight = height;
this.fontSize = fontSize;
this.horizantalLetterSpacing = horizantalLetterSpacing;
this.verticalLetterSpacing = verticalLetterSpacing;
}
BitmapTextField.bitmapFonts = [];
var instance = createjs.extend(BitmapTextField,createjs.Container);
instance.initialize = function (width, height, text, fontName,fontSize,horizantalLetterSpacing,verticalLetterSpacing,hAlign,vAlign,autoScale)
{
var textDisplay = String(text);
this.border = new createjs.Shape();
this.border.graphics.setStrokeStyle(1);
this.border.graphics.beginStroke(createjs.Graphics.getRGB(255,0,0));
this.border.graphics.drawRect(0,0,width,height);
this.addChild(this.border);
this.border.visible = false;
this.textContainer = new createjs.Container();
this.addChild(this.textContainer);
if(BitmapTextField.bitmapFonts[fontName])
{
this.font = BitmapTextField.bitmapFonts[fontName];
var container = this.font.createSprite(width,height,textDisplay,fontSize,horizantalLetterSpacing,verticalLetterSpacing,hAlign,vAlign,autoScale,true);
this.actualWidth = this.font.getWidth();
this.textContainer.addChild(container);
}
else
{
console.log("BitmapTextField: Font is not registered "+fontName);
}
};
//sets the text.
instance.setText = function(text)
{
var textDisplay = String(text);
this.textContainer.uncache();
this.textContainer.removeAllChildren();
var container = this.font.createSprite(this.containerWidth,this.containerHeight,textDisplay,this.fontSize,this.horizantalLetterSpacing,this.verticalLetterSpacing,this.hAlign,this.vAlign,this.autoScale,true);
this.textContainer.addChild(container);
if(this.color!="")
{
this.setColor(this.color);
}
this.actualWidth = this.font.getWidth();
};
//width of the container, the width given while creating text field
instance.getWidth = function()
{
return this.containerWidth;
};
//height of the container, the width given while creating text field
instance.getHeight = function()
{
return this.containerHeight;
};
//actual text width.
instance.getActualWidth = function()
{
return this.actualWidth;
};
//shows a red colored bounding box, useful for debugging.
instance.showBorder = function(visible)
{
if(visible==null)
visible = true;
this.border.visible = visible;
};
instance.setColor = function(color)
{
var R = hexToR(color);
var G = hexToG(color);
var B = hexToB(color);
if(color!=this.color)
{
this.colorFilter = new createjs.ColorFilter(0,0,0,1,R,G,B,0);
}
this.textContainer.filters = [this.colorFilter];
this.textContainer.cache(0,0,this.containerWidth,this.containerHeight);
this.color = color;
function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
};
//One must register bitmapfont before creating a textfield..
/**
*
* @param bitmapFont: BitmapFont instance
* @param fontName: name of the font, this will be used later while creating the text field.
*/
BitmapTextField.registerBitmapFont = function(bitmapFont,fontName)
{
if(BitmapTextField.bitmapFonts[fontName] == null)
{
BitmapTextField.bitmapFonts[fontName] = bitmapFont;
return fontName;
}
else
{
console.log(fontName+" : is already registered");
}
}
window.BitmapTextField = createjs.promote(BitmapTextField,'Container');
})(window);<file_sep>/src/js/Main.js
/** @define {string} */
var BUILD = "debug";
(function(){
/**
* Main class of the app.
*/
function Main(){}
/**
* Entry point of the app.
*/
var bitmap;
var xml;
var bitmapFont;
var text;
Main.main = function()
{
var main = new Main();
if (!window.HTMLCanvasElement)
{
alert("Your browser does not support HTML5 Canvas.");
return;
}
else main.initialize();
// entry point
}
/**
* Initializes the basics of the app.
*/
Main.prototype.initialize = function()
{
/**
* mainCanvas
*/
this.mainCanvas = document.getElementById("mainCanvas");
/**
* mainStage
*/
this.mainStage = new createjs.Stage(this.mainCanvas);
this.mainStage.snapToPixelsEnabled = false;
/*
* createjs
*/
this.count = 0;
loader = new createjs.LoadQueue();
loader.loadFile('cooper.png');
loader.loadFile('cooper.xml');
var thisRef = this;
loader.on('fileload',fileLoadHandler);
loader.on('complete',loadCompleteHandler);
function fileLoadHandler(event){
if(event.item.type==createjs.AbstractLoader.IMAGE){
thisRef.bitmap = event.result;
}
if(event.item.type==createjs.AbstractLoader.XML){
thisRef.xml = event.result;
}
}
function loadCompleteHandler(event){
bitmapFont = new BitmapFont(thisRef.bitmap,thisRef.xml,32);
BitmapTextField.registerBitmapFont(bitmapFont,"cooper");
var bitmapText = new BitmapTextField(200,100,"Bitmap text","cooper",-1,0,0,"left","top",true);
bitmapText.showBorder();
bitmapText.x = 10;
bitmapText.y = 10;
thisRef.mainStage.addChild(bitmapText);
bitmapText = new BitmapTextField(200,100,"Bitmap text","cooper",-1,0,0,"right","top",true);
bitmapText.showBorder();
bitmapText.x = 220;
bitmapText.y = 10;
thisRef.mainStage.addChild(bitmapText);
bitmapText = new BitmapTextField(200,100,"Bitmap text","cooper",-1,0,0,"center","top",true);
bitmapText.showBorder();
bitmapText.x = 430;
bitmapText.y = 10;
thisRef.mainStage.addChild(bitmapText);
bitmapText = new BitmapTextField(200,100,"Bitmap text","cooper",-1,0,0,"center","center",true);
bitmapText.showBorder();
bitmapText.x = 10;
bitmapText.y = 120;
thisRef.mainStage.addChild(bitmapText);
bitmapText = new BitmapTextField(200,100,"Bitmap text and multiline text","cooper",-1,0,0,"center","center",true);
bitmapText.showBorder();
bitmapText.x = 220;
bitmapText.y = 120;
thisRef.mainStage.addChild(bitmapText);
bitmapText = new BitmapTextField(200,100,"Bitmap text and multiline text","cooper",-1,0,0,"left","center",true);
bitmapText.showBorder();
bitmapText.x = 430;
bitmapText.y = 120;
thisRef.mainStage.addChild(bitmapText);
bitmapText = new BitmapTextField(200,100,"Bitmap text and multiline text","cooper",-1,0,0,"right","center",true);
bitmapText.showBorder();
bitmapText.x = 10;
bitmapText.y = 240;
thisRef.mainStage.addChild(bitmapText);
bitmapText = new BitmapTextField(200,100,"you can change the color also","cooper",-1,0,0,"center","center",true);
bitmapText.setColor("#009900");
bitmapText.x = 220;
bitmapText.y = 240;
thisRef.mainStage.addChild(bitmapText);
thisRef.score = 0;
thisRef.scoreText = new BitmapTextField(200,50,"Score: "+thisRef.score,"cooper",-1,0,0,"right","center",true);
thisRef.scoreText.x = 200;
thisRef.scoreText.y = 360;
thisRef.mainStage.addChild(thisRef.scoreText);
};
createjs.Ticker.timingMode = createjs.Ticker.RAF;
createjs.Ticker.addEventListener("tick", tick);
function tick(event){
if(thisRef.scoreText!=null)
{
thisRef.count++;
if(thisRef.count>5)
{
thisRef.count = 0;
thisRef.score++;
thisRef.scoreText.setText("Score: "+thisRef.score);
}
}
thisRef.mainStage.update();
}
}
/**
* Expose class.
*/
window.Main = Main;
})();
<file_sep>/README.md
createjsbitmaptext
==================
Updated to EaselJS 0.8.0
bitmap font library for createjs library
Use bmFonts or GlyphDesigner to export bitmap fonts.
Inspired from starling bitmap fonts.
Important notes:
Export bitmap font from bmfont software (http://www.angelcode.com/products/bmfont/) to get png and .fnt file
Rename the .fnt file to .xml
Create BitmapFont instance.
var bitmapFont = new BitmapFont(bitmap,xml,32);
Register Bitmapfont with a name.
BitmapTextField.registerBitmapFont(bitmapFont,"cooper");
Create BitmapTextField
var bitmapText = new BitmapTextField(200,100,"Bitmap Text","cooper",-1,0,0,"left","top",true);
mainStage.addChild(bitmapText);
Features:
* Supports Multiline Text.
* Supports horizontal and vertical alignment.
* Support for \n for new line.
* kerning
* Change color using setColor method of BitmapTextField
Note: You need to include Filter.js and ColorFilter.js to your project, if you are using minified version of easeljs.
Demo:
https://googledrive.com/host/0BzMWTsJiuGb7d2NCSVdSb19qaVk/index.html
<file_sep>/src/js/text/VAlign.js
(function(window) {
VAlign = function(){
}
VAlign.BOTTOM = "bottom";
VAlign.TOP = "top";
VAlign.CENTER = "center";
window.VAlign = VAlign;
})(window);<file_sep>/src/js/text/CharLocation.js
(function(window) {
CharLocation = function(_char)
{
this._char = _char;
this._char = null;
this.scale = 0;
this.x = 0;
this.y = 0;
}
window.CharLocation = CharLocation;
})(window);<file_sep>/src/js/text/BitmapFont.js
(function(window) {
var mStage;
/**
*
* @param texture: png image of the font
* @param fontXML: xml exported from bmFonts software
* @param size: size of the font we exported using bmFonts, useful for a reference.
*/
BitmapFont = function(texture,fontXML,size){
this.mName = "unknown";
this.mLineHeight = this.mSize = this.mBaseLine = size;
this.mTexture = texture;
this.mChars = [];
this.mHelperImage = new createjs.Bitmap(texture);
this.mCharLocationPool = [];
if(fontXML)
this.parseFontXml(fontXML);
this.textWidth = 0;
this.textHeight = 0;
this.previousWidth = [];
}
BitmapFont.NATIVE_SIZE = -1;
BitmapFont.MINI = "mini";
BitmapFont.CHAR_SPACE = 32;
BitmapFont.CHAR_TAB = 9;
BitmapFont.CHAR_NEWLINE = 10;
BitmapFont.CHAR_CARRIAGE_RETURN = 13;
BitmapFont.prototype.parseFontXml = function(fontXML)
{
var charecters = fontXML.childNodes[0].getElementsByTagName('chars')[0].getElementsByTagName('char');
var arrFrames = [];
var animations = {};
var id;
var allChars = [];
var allKernings = [];
for(var i = 0;i<charecters.length;i++){
var obj = new Object();
obj.id = charecters[i].getAttribute('id');
id = charecters[i].getAttribute('id');
obj.x = charecters[i].getAttribute('x');
obj.y = charecters[i].getAttribute('y');
obj.xAdvance = charecters[i].getAttribute('xadvance');
obj.xOffset = charecters[i].getAttribute('xoffset');
obj.yOffset = charecters[i].getAttribute('yoffset');
obj.width = charecters[i].getAttribute('width');
obj.height = charecters[i].getAttribute('height');
var arr = [obj.x,obj.y,obj.width,obj.height];
arrFrames.push(arr);
animations["frame"+i] = [i];
allChars.push(obj);
}
spriteSheet = new createjs.SpriteSheet({images:[this.mTexture],frames:arrFrames,animations:animations});
for(var k = 0;k<allChars.length;k++){
//var texture = createjs.SpriteSheetUtils.extractFrame(spriteSheet,k);
var texture = new createjs.Sprite(spriteSheet);
texture.gotoAndStop(k);
//mStage.addChild(texture);
texture.x = Math.random()*800;
texture.y = 100;
var bitmapChar = new BitmapChar(allChars[k].id,texture,allChars[k].xOffset,allChars[k].yOffset,allChars[k].xAdvance);
this.addChar(allChars[k].id,bitmapChar);
}
if(fontXML.childNodes[0].getElementsByTagName('kernings')[0]!=null)
{
var kernings = fontXML.childNodes[0].getElementsByTagName('kernings')[0].getElementsByTagName('kerning');
for(var j = 0;j<kernings.length;j++){
var obj = new Object();
obj.first = kernings[j].getAttribute('first');
obj.second = kernings[j].getAttribute('second');
obj.amount = kernings[j].getAttribute('amount');
allKernings.push(obj);
if(obj.second in this.mChars){
this.getChar(obj.second).addKerning(obj.first,obj.amount);
}
}
}
}
BitmapFont.prototype.getChar = function(charId)
{
return this.mChars[charId];
};
BitmapFont.prototype.addChar = function(charId,bitmapChar)
{
this.mChars[charId] = bitmapChar;
};
BitmapFont.prototype.createSprite = function(width,height,text,fontSize,horizantalLetterSpacing,verticalLetterSpacing,hAlign,vAlign,autoScale,kerning)
{
if(fontSize==null) fontSize = -1;
if(hAlign==null) hAlign = "center";
if(vAlign==null) vAlign = "center";
if(autoScale==null) autoScale = true;
if(kerning==null) kerning = true;
var charLocations = this.arrangeChars(width,height,text,fontSize,hAlign,vAlign,autoScale,kerning,verticalLetterSpacing);
var numChars = charLocations.length;
var sprite = new createjs.Container();
for(var i=0;i<numChars;i++)
{
var charLocation = charLocations[i];
var _char = charLocation._char.createImage();
_char.x = charLocation.x+i*horizantalLetterSpacing;
_char.y = charLocation.y;
_char.scaleX = _char.scaleY = charLocation.scale;
sprite.addChild(_char);
var charHeight = charLocation._char.getHeight()*charLocation.scale;
if(charHeight>this.textHeight)
{
this.textHeight = charHeight;
}
}
return sprite;
};
BitmapFont.prototype.arrangeChars = function(width,height,text,fontSize,hAlign,vAlign,autoScale,kerning,verticalLetterSpacing)
{
if(fontSize==null) fontSize = -1;
if(hAlign==null) hAlign = "center";
if(vAlign==null) vAlign = "center";
if(autoScale==null) autoScale = true;
if(kerning==null) kerning = true;
if(text==null || text.length==0 || (width==0&&height==0))
return [];
if(fontSize<0)fontSize *= -this.mSize;
var lines = [[]];
var finished = false;
var charLocation = {};
var numChars = 0;
var containerWidth = 0;
var containerHeight = 0;
var scale = 0;
while(!finished)
{
scale = fontSize/this.mSize;
containerWidth = width/scale;
containerHeight = height/scale;
lines = [];
lines.push([]);
if(this.mLineHeight <= containerHeight)
{
var lastWhiteSpace = -1;
var lastCharID = -1;
var currentX = 0;
var currentY = 0;
var currentLine = [];
numChars = text.length;
for(var i=0;i<numChars;++i)
{
var lineFull = false;
var charID = text.charCodeAt(i);
var _char = this.getChar(charID);
if(charID == BitmapFont.CHAR_NEWLINE || charID == BitmapFont.CHAR_CARRIAGE_RETURN)
{
lineFull = true;
}
else if(_char == null)
{
console.log("[BitmapFont] Missing character: "+ charID);
}
else
{
if(charID == BitmapFont.CHAR_SPACE || charID == BitmapFont.CHAR_TAB)
lastWhiteSpace = i;
if(kerning)
{
currentX = _char.getKerning(lastCharID)/1+currentX/1;
}
charLocation = new CharLocation(_char);
charLocation._char = _char;
charLocation.x = currentX/1+_char.getXOffset()/1;
charLocation.y = currentY/1+_char.getYOffset()/1;
currentLine.push(charLocation);
currentX += _char.getXAdvance()/1;
lastCharID = charID;
if(charLocation.x + Number(_char.getWidth()) > containerWidth)
{
var numCharsToRemove = lastWhiteSpace == -1 ? 1 : i-lastWhiteSpace;
var removeIndex = currentLine.length - numCharsToRemove;
currentLine.splice(removeIndex,numCharsToRemove);
if(currentLine.length == 0)
break;
i -= numCharsToRemove;
lineFull = true;
}
}
if(i == numChars-1)
{
lines.push(currentLine);
finished = true;
}
else if(lineFull)
{
lines.push(currentLine);
if(lastWhiteSpace == i)
currentLine.pop();
if(currentY + 2*this.mLineHeight <= containerHeight)
{
currentLine = [];
currentX = 0;
currentY += this.mLineHeight;
lastWhiteSpace = -1;
lastCharID = -1;
}
else
{
break;
}
}
}
}
if(autoScale && !finished)
{
fontSize -= 1;
lines.length = 0;
}
else
{
finished = true;
}
}
var finalLocations = [];
var numLines = lines.length;
var bottom = currentY+this.mLineHeight;
var yOffset = 0;
if(vAlign == VAlign.BOTTOM) yOffset = containerHeight - bottom;
else if(vAlign == VAlign.CENTER) yOffset = (containerHeight - bottom)/2;
this.previousWidth = [];
for(var lineID = 0;lineID<numLines; ++lineID)
{
var line = lines[lineID];
numChars = line.length;
if(numChars==0) continue;
var xOffset = 0;
var lastLocation = line[line.length-1];
var right = lastLocation.x - lastLocation._char.getXOffset()/1 + lastLocation._char.getXAdvance()/1;
if(hAlign == HAlign.RIGHT) xOffset = containerWidth - right;
else if(hAlign == HAlign.CENTER) xOffset = (containerWidth - right)/2;
this.width = 0;
for(var c=0;c<numChars;++c)
{
charLocation = line[c];
this.width += charLocation._char.getXAdvance()/1+charLocation._char.getXOffset()/1+1;
charLocation.x = scale * (charLocation.x + xOffset);
charLocation.y = scale * (charLocation.y + yOffset+(lineID-1)*verticalLetterSpacing);
charLocation.scale = scale;
if (charLocation._char.getWidth() > 0 && charLocation._char.getHeight() > 0)
finalLocations.push(charLocation);
// return to pool for next call to "arrangeChars"
this.mCharLocationPool.push(charLocation);
}
this.previousWidth.push(this.width);
}
this.width = this.previousWidth[0];
for(var i=1;i<this.previousWidth.length;i++)
{
if(this.previousWidth[i]>this.width)
this.width = this.previousWidth[i];
}
return finalLocations;
}
BitmapFont.prototype.getName = function()
{
return this.mName;
}
BitmapFont.prototype.getSize = function()
{
return this.mSize;
}
BitmapFont.prototype.getLineHeight = function()
{
return this.mLineHeight;
}
BitmapFont.prototype.setLineHeight = function(value)
{
this.mLineHeight = value;
}
BitmapFont.prototype.getBaseLine = function()
{
return this.mBaseLine;
}
BitmapFont.prototype.getWidth = function()
{
return this.width;
}
BitmapFont.prototype.getHeight = function()
{
return this.textHeight;
}
window.BitmapFont = BitmapFont;
})(window);<file_sep>/src/js/text/readme.txt
v 0.1.0
v0.1.1
* added setColor function to BitmapTextField.js
* updated easeljs library to 0.6.1
v0.1.2
* added setColor function to BitmapTextField.js
* updated easeljs library to 0.8.0
| ac415f5857baac44418be7b3a96bcda98e7cbe51 | [
"JavaScript",
"Text",
"Markdown"
] | 8 | JavaScript | vikramarka/createjsbitmaptext | 12ffb5dc40ab9616e4d248c2526c5881800de1c5 | c9886daae8aa118e112d9e88901b9db5acc3dafc |
refs/heads/master | <file_sep>/*
1. Write a function called hasMostFollowers, which accepts a variable number of arguments. You should
then make an AJAX call to the Github User API (https://developer.github.com/v3/users/#get-a-single-user)
to get the name and number of followers of each argument. The function should return a string which displays
the username who has the most followers.
Hint - Try to use Promise.all to solve this and remember that the jQuery AJAX methods ($.getJSON, $.ajax, etc.)
eturn a promise.
hasMostFollowers('elie','tigarcia','colt').then(function(data){
console.log(data)
});
"Colt has the most followers with 424"
2. Write a function called starWarsString, which accepts a number. You should then make an AJAX call to
the Star Wars API (https://swapi.co/ ) to search for a specific character by the number passed to the function.
Your function should return a promise that when resolved will console.log the name of the character.
starWarsString(1).then(function(data){
console.log(data)
})
"<NAME>"
Bonus 1 - Using the data from the previous AJAX call above, make another AJAX request to get the first
film that character is featured in and return a promise that when resolved will console.log the name of
the character and the film they are featured in
starWarsString(1).then(function(data){
console.log(data)
})
"<NAME> is featured in The Empire Strikes Back, directed by <NAME>"
Bonus 2 - Using the data from Bonus 1 - make another AJAX call to get the information about the first
planet that the film contains. Your function should return a promise that when resolved will console.log
the name of the character and the film they are featured in and the name of the planet.
starWarsString(1).then(function(data){
console.log(data)
})
"<NAME> is featured in The Empire Strikes Back, directed by <NAME> and it takes place on Hoth"
*/
function hasMostFollowers(...usernames) {
let baseUrl = 'https://api.github.com/users/';
let urls = usernames.map(username => $.getJSON(baseUrl + username));
return Promise.all(urls).then(function(data) {
let max = data.sort((a, b) => a.followers < b.followers)[0];
return `${max.name} has the most followers with ${max.followers}`;
})
}
function starWarsString(id) {
let str = '';
return $.getJSON(`https://swapi.co/api/people/${id}/`).then(function(data) {
str += `${data.name} is first featured in `;
let filmData = data.films[0];
return $.getJSON(filmData);
}).then(function(res) {
str += `${res.title}, directed by ${res.director} `
let planetData = res.planets[0];
return $.getJSON(planetData);
}).then(function(res) {
str += `and it takes place on ${res.name}`;
return str;
})
}
| 13ea642f14eebb7591031d265ef2e63f93b4708b | [
"JavaScript"
] | 1 | JavaScript | SpurgeonPrakash/ES6 | 6c2179aaebe8e9dd53990ff760cde9b62a91ea1b | 09b332455732ca47b5980b0fa238b4decbd9a82a |
refs/heads/main | <repo_name>SourceWriters/amongus4j<file_sep>/src/main/java/net/sourcewriters/server/amongus4j/net/packet/client/ClientPacketType.java
package net.sourcewriters.server.amongus4j.net.packet.client;
public enum ClientPacketType {
;
int packetId() {
return 0;
}
}
<file_sep>/src/main/java/net/sourcewriters/server/amongus4j/utils/ReflectionProvider.java
package net.sourcewriters.server.amongus4j.utils;
import java.util.HashMap;
import org.pf4j.Plugin;
import org.pf4j.PluginManager;
import org.pf4j.PluginWrapper;
import org.reflections.Reflections;
import org.reflections.util.ClasspathHelper;
import com.syntaxphoenix.syntaxapi.utils.java.Arrays;
public final class ReflectionProvider {
private static ReflectionProvider PROVIDER;
public static ReflectionProvider build(PluginManager pluginManager) {
if (PROVIDER != null) {
return null;
}
return PROVIDER = new ReflectionProvider(pluginManager);
}
public static ReflectionProvider get() {
return PROVIDER;
}
private final HashMap<String, Reflections> reflections = new HashMap<>();
private final PluginManager pluginManager;
private ReflectionProvider(PluginManager pluginManager) {
this.pluginManager = pluginManager;
}
/*
* ClassLoaders
*/
private ClassLoader[] defaults;
private ClassLoader[] classLoaders() {
if (defaults != null)
return defaults;
return defaults = Arrays.merge(size -> new ClassLoader[size], ClasspathHelper.classLoaders(), getClass().getClassLoader(),
ClassLoader.getSystemClassLoader(), ClassLoader.getPlatformClassLoader(), Runtime.getRuntime().getClass().getClassLoader());
}
private Object[] buildParameters(String packageName, ClassLoader... loaders) {
return Arrays.merge(new Object[] {
packageName
}, loaders.length == 0 ? classLoaders() : Arrays.merge(size -> new ClassLoader[size], classLoaders(), loaders));
}
/*
* Reflections
*/
public Reflections of(String packageName) {
return of((PluginWrapper) null, packageName);
}
public Reflections of(Class<? extends Plugin> clazz, String packageName) {
return of(clazz == null ? null : pluginManager.whichPlugin(clazz), packageName);
}
public Reflections of(PluginWrapper wrapper, String packageName) {
synchronized (reflections) {
if (reflections.containsKey(packageName)) {
return reflections.get(packageName);
}
}
Reflections reflect = new Reflections(wrapper == null ? buildParameters(packageName) : buildParameters(packageName, wrapper.getPluginClassLoader()));
synchronized (reflections) {
reflections.put(packageName, reflect);
}
return reflect;
}
public boolean has(String packageName) {
synchronized (reflections) {
return reflections.containsKey(packageName);
}
}
public boolean delete(String packageName) {
synchronized (reflections) {
return reflections.remove(packageName) != null;
}
}
/*
* Data
*/
public ReflectionProvider flush() {
synchronized (reflections) {
reflections.clear();
}
return this;
}
}
<file_sep>/src/main/java/net/sourcewriters/server/amongus4j/net/UdpServer.java
package net.sourcewriters.server.amongus4j.net;
import java.net.InetAddress;
import java.util.Optional;
import com.syntaxphoenix.syntaxapi.utils.java.tools.Container;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
public class UdpServer {
private final Bootstrap bootstrap = new Bootstrap();
private final Container<Channel> channel = Container.of();
private final InetAddress address;
private final int port;
public UdpServer(int port) {
this.address = null;
this.port = port;
}
public UdpServer(InetAddress address, int port) {
this.address = address;
this.port = port;
}
public void start() {
if (isRunning()) {
return;
}
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(new NioEventLoopGroup()).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).handler(new AmongUsChannelInit());
ChannelFuture channelFuture;
if (address == null) {
channelFuture = bootstrap.bind(port);
} else {
channelFuture = bootstrap.bind(address, port);
}
this.channel.replace(channelFuture.channel());
}
public void stop() {
if (!isRunning()) {
return;
}
channel.get().close();
channel.replace(null);
}
public boolean isRunning() {
return channel.isPresent();
}
public Optional<Channel> getChannel() {
return channel.asOptional();
}
public Bootstrap getBootstrap() {
return bootstrap;
}
}
<file_sep>/src/main/java/net/sourcewriters/server/amongus4j/command/PluginCommand.java
package net.sourcewriters.server.amongus4j.command;
import org.pf4j.PluginWrapper;
import com.syntaxphoenix.syntaxapi.command.Arguments;
import com.syntaxphoenix.syntaxapi.command.BaseCommand;
import com.syntaxphoenix.syntaxapi.command.BaseCompletion;
import com.syntaxphoenix.syntaxapi.command.BaseInfo;
public class PluginCommand extends BaseCommand {
private final PluginWrapper wrapper;
private final BaseCommand command;
public PluginCommand(PluginWrapper wrapper, BaseCommand command) {
this.wrapper = wrapper;
this.command = command;
}
public PluginWrapper getWrapper() {
return wrapper;
}
public BaseCommand getCommand() {
return command;
}
/*
* BaseCommand Implementation
*/
@Override
public void execute(BaseInfo info, Arguments arguments) {
command.execute(info, arguments);
}
@Override
public BaseCompletion complete(BaseInfo info, Arguments arguments) {
return command.complete(info, arguments);
}
}
<file_sep>/src/main/java/net/sourcewriters/server/amongus4j/command/AmongInfo.java
package net.sourcewriters.server.amongus4j.command;
import com.syntaxphoenix.syntaxapi.command.BaseInfo;
import com.syntaxphoenix.syntaxapi.command.CommandManager;
public class AmongInfo extends BaseInfo {
public AmongInfo(CommandManager manager, String label) {
super(manager, label);
}
}
<file_sep>/src/main/java/net/sourcewriters/server/amongus4j/net/hazel/UnreliableHazelPacket.java
package net.sourcewriters.server.amongus4j.net.hazel;
import java.net.InetSocketAddress;
import io.netty.buffer.ByteBuf;
public class UnreliableHazelPacket extends HazelPacket {
public UnreliableHazelPacket(int id, int length, short tag, ByteBuf data, InetSocketAddress sender, InetSocketAddress recipient) {
super(id, length, tag, data, sender, recipient);
}
@Override
public HazelPacketType getType() {
return HazelPacketType.UNRELIABLE;
}
@Override
public short getTypeId() {
return 0;
}
}
<file_sep>/src/main/java/net/sourcewriters/server/amongus4j/net/packet/Packet.java
package net.sourcewriters.server.amongus4j.net.packet;
public abstract class Packet {
public abstract boolean isClient();
public abstract int getId();
public abstract byte[] serialize();
}
<file_sep>/src/main/java/net/sourcewriters/server/amongus4j/net/hazel/ControlHazelPacket.java
package net.sourcewriters.server.amongus4j.net.hazel;
import java.net.InetSocketAddress;
import io.netty.buffer.Unpooled;
public class ControlHazelPacket extends HazelPacket {
private final HazelControlType type;
public ControlHazelPacket(int id, int length, short tag, InetSocketAddress sender, InetSocketAddress recipient, HazelControlType type) {
super(id, length, tag, Unpooled.EMPTY_BUFFER, sender, recipient);
this.type = type;
}
@Override
public HazelPacketType getType() {
return HazelPacketType.CONTROL;
}
public HazelControlType getControlType() {
return type;
}
@Override
public short getTypeId() {
short output = 8;
if (type.isReliable()) {
output += 2;
}
if (type.isFragmented()) {
output += 4;
}
return output;
}
public static ControlHazelPacket acknowledge(HazelPacket packet) {
return new ControlHazelPacket(packet.getId(), -1, (short) 0, packet.getRecipient(), packet.getSender(),
HazelControlType.ACKNOWLEDGED);
}
public static ControlHazelPacket disconnect(HazelPacket packet) {
return new ControlHazelPacket(packet.getId(), -1, (short) 0, packet.getRecipient(), packet.getSender(),
HazelControlType.DISCONNECT);
}
}
<file_sep>/src/main/java/net/sourcewriters/server/amongus4j/plugin/SafePluginManager.java
package net.sourcewriters.server.amongus4j.plugin;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import org.pf4j.DefaultPluginManager;
import org.pf4j.PluginState;
import org.pf4j.PluginStateEvent;
import org.pf4j.PluginStateListener;
import org.pf4j.PluginWrapper;
import com.syntaxphoenix.syntaxapi.command.CommandManager;
import com.syntaxphoenix.syntaxapi.event.Event;
import com.syntaxphoenix.syntaxapi.event.EventExecutor;
import com.syntaxphoenix.syntaxapi.event.EventListener;
import com.syntaxphoenix.syntaxapi.event.EventManager;
import com.syntaxphoenix.syntaxapi.logging.ILogger;
import com.syntaxphoenix.syntaxapi.service.ServiceManager;
import com.syntaxphoenix.syntaxapi.utils.java.Collect;
import com.syntaxphoenix.syntaxapi.utils.java.tools.Container;
import net.sourcewriters.server.amongus4j.command.CommandHandler;
import net.sourcewriters.server.amongus4j.command.PluginCommand;
import net.sourcewriters.server.amongus4j.config.Config;
import net.sourcewriters.server.amongus4j.utils.ReflectionProvider;
public class SafePluginManager extends DefaultPluginManager implements PluginStateListener {
private final Container<ReflectionProvider> provider;
private final ServiceManager service;
private final CommandHandler command;
private final EventManager event;
private final ILogger logger;
public SafePluginManager(ILogger logger, Container<ReflectionProvider> provider, CommandHandler command,
EventManager event, ServiceManager service) {
super();
this.provider = provider;
this.event = event;
this.logger = logger;
this.service = service;
this.command = command;
super.addPluginStateListener(this);
}
public SafePluginManager(Path pluginsRoot, ILogger logger, Container<ReflectionProvider> provider,
CommandHandler command, EventManager event, ServiceManager service) {
super(pluginsRoot);
this.provider = provider;
this.event = event;
this.logger = logger;
this.service = service;
this.command = command;
super.addPluginStateListener(this);
}
/*
* Getter
*/
public ReflectionProvider getProvider() {
return provider.get();
}
public ServiceManager getServiceManager() {
return service;
}
public EventManager getEventManager() {
return event;
}
public ILogger getLogger() {
return logger;
}
/*
* Plugin Listener
*/
@Override
public synchronized void addPluginStateListener(PluginStateListener listener) {
return;
}
@Override
public synchronized void removePluginStateListener(PluginStateListener listener) {
return;
}
@Override
public void pluginStateChanged(PluginStateEvent event) {
if (event.getPluginState() == PluginState.STARTED) {
Config.ACCESS.load(event.getPlugin());
this.event.call(new PluginEnableEvent(this, event.getPlugin()));
return;
}
if (event.getOldState() != PluginState.STARTED)
return;
switch (event.getPluginState()) {
case STOPPED:
case DISABLED:
break;
default:
return;
}
PluginWrapper wrapper = event.getPlugin();
this.event.call(new PluginDisableEvent(this, wrapper));
List<Class<? extends EventListener>> owners = this.event.getOwnerClasses();
int size = owners.size();
for (int index = 0; index < size; index++) {
if (wrapper.equals(whichPlugin(owners.get(index))))
continue;
owners.remove(index);
index--;
size--;
}
owners.stream().forEach(clazz -> this.event.unregisterEvents(clazz));
List<Class<? extends Event>> events = this.event
.getEvents()
.stream()
.filter(clazz -> isFromPlugin(wrapper, clazz))
.collect(Collectors.toList());
this.event.unregisterExecutors(events.stream().collect(collectExecutor()));
events.forEach(clazz -> this.event.unregisterEvent(clazz));
service
.getContainers()
.stream()
.filter(service -> isFromPlugin(wrapper, service.getOwner()))
.forEach(container -> service.unsubscribe(container));
service
.getServices()
.stream()
.filter(service -> isFromPlugin(wrapper, service.getOwner()))
.forEach(service -> this.service.unregister(service));
CommandManager manager = command.getManager();
PluginCommand[] commands = command.getCommands(wrapper);
for (int index = 0; index < commands.length; index++)
manager.unregister(commands[index]);
Config.ACCESS.unload(wrapper);
ClassLoader loader = wrapper.getPluginClassLoader();
Package[] packages = loader.getDefinedPackages();
ReflectionProvider current = provider.get();
for (int index = 0; index < packages.length; index++)
current.delete(packages[index].getName());
}
/*
* Utilities
*/
private Collector<Class<? extends Event>, List<EventExecutor>, List<EventExecutor>> collectExecutor() {
return Collect
.collectList((output, clazz) -> this.event.getExecutorsForEvent(clazz, true).stream().forEach(executor -> {
if (output.contains(executor))
return;
output.add(executor);
}));
}
public boolean isFromPlugin(PluginWrapper wrapper, Object object) {
return wrapper.equals(whichPlugin(!(object instanceof Class) ? object.getClass() : (Class<?>) object));
}
}
<file_sep>/src/main/java/net/sourcewriters/server/amongus4j/net/hazel/HazelPacketDecoder.java
package net.sourcewriters.server.amongus4j.net.hazel;
import java.util.List;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
public class HazelPacketDecoder extends MessageToMessageDecoder<DatagramPacket> {
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
ByteBuf buffer = msg.content();
short type = buffer.readUnsignedByte();
int id = buffer.readUnsignedShort();
int length;
short tag;
if (type == 10) {
length = -1;
tag = 0;
} else {
length = buffer.readUnsignedShort();
tag = buffer.readUnsignedByte();
}
boolean reliable = (type & 0b0000_0001) == 1;
if ((type & 0b0000_1000) == 8) {
out.add(new ControlHazelPacket(id, length, tag, msg.sender(), msg.recipient(),
HazelControlType.of(reliable, (type & 0b000_0010) == 2)));
} else if (reliable) {
out.add(new ReliableHazelPacket(id, length, tag, extractData(buffer), msg.sender(), msg.recipient()));
} else {
out.add(new UnreliableHazelPacket(id, length, tag, extractData(buffer), msg.sender(), msg.recipient()));
}
}
private ByteBuf extractData(ByteBuf buffer) {
int readable = buffer.readableBytes();
if (readable == 0) {
return Unpooled.EMPTY_BUFFER;
}
ByteBuf output = Unpooled.buffer();
output.readBytes(buffer, readable);
return output.asReadOnly();
}
}
<file_sep>/src/main/java/net/sourcewriters/server/amongus4j/net/hazel/HazelPacketEncoder.java
package net.sourcewriters.server.amongus4j.net.hazel;
import java.util.List;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
public class HazelPacketEncoder extends MessageToMessageEncoder<HazelPacket> {
@Override
protected void encode(ChannelHandlerContext ctx, HazelPacket msg, List<Object> out) throws Exception {
ByteBuf buffer = Unpooled.buffer();
buffer.writeByte(msg.getTypeId());
buffer.writeShort(msg.getId());
if (msg.getLength() != -1) {
buffer.writeShort(msg.getLength());
buffer.writeByte(msg.getTag());
buffer.writeBytes(msg.getData());
}
out.add(new DatagramPacket(buffer, msg.getRecipient(), msg.getSender()));
}
}
<file_sep>/src/main/java/net/sourcewriters/server/amongus4j/net/data/BufferWriter.java
package net.sourcewriters.server.amongus4j.net.data;
import static net.sourcewriters.server.amongus4j.net.data.DataSerialization.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
public class BufferWriter {
private byte[] buffer = new byte[0];
public void writeByte(byte value) {
append(fromByte(value));
}
public void writeShort(short value) {
append(fromShort(value));
}
public void writeInt(int value) {
append(fromInt(value));
}
public void writeFloat(float value) {
append(fromFloat(value));
}
public void writeLong(long value) {
append(fromLong(value));
}
public void writeDouble(double value) {
append(fromDouble(value));
}
public void writeBoolean(boolean value) {
append(fromBoolean(value));
}
public void writeString(String value) {
writeString(value, StandardCharsets.UTF_8);
}
public void writeString(String value, Charset charset) {
byte[] bytes = fromString(value, charset);
writePackedInt(bytes.length);
append(bytes);
}
public void writePackedInt(int value) {
writePackedUnsignedInt(Integer.toUnsignedLong(value));
}
public void writePackedUnsignedInt(long value) {
do {
short b = (short) (value & 0xFF);
if (value >= 0x80) {
b |= 0x80;
}
writeShort(b);
value >>= 7;
} while (value > 0);
}
public int length() {
return buffer.length;
}
public ByteBuf asBuffer() {
return Unpooled.wrappedBuffer(buffer);
}
public ByteBuf asHazelBuffer(boolean reliable) {
ByteBuf buf = Unpooled.buffer(2048);
if(reliable) {
buf.writeByte((byte) 0);
} else {
buf.writeByte((byte) buffer.length);
buf.writeByte((byte) (buffer.length >> 8));
buf.writeByte((byte) 1);
}
buf.writeBytes(buffer);
return buf;
}
private byte[] merge(byte[] var0, byte[] var1) {
byte[] output = new byte[var0.length + var1.length];
System.arraycopy(var0, 0, output, 0, var0.length);
System.arraycopy(var1, 0, output, var0.length, var1.length);
return output;
}
private void append(byte[] data) {
buffer = merge(buffer, data);
}
}
<file_sep>/src/main/java/net/sourcewriters/server/amongus4j/command/CommandHandler.java
package net.sourcewriters.server.amongus4j.command;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.pf4j.PluginManager;
import org.pf4j.PluginWrapper;
import com.syntaxphoenix.syntaxapi.command.CommandManager;
import com.syntaxphoenix.syntaxapi.event.EventManager;
import com.syntaxphoenix.syntaxapi.logging.ILogger;
import com.syntaxphoenix.syntaxapi.utils.alias.Alias;
public class CommandHandler {
private final CommandManager manager;
private final CommandListener listener;
public CommandHandler(EventManager eventManager, String prefix, String splitter, ILogger logger) {
this.manager = new CommandManager().setPrefix(prefix).setSplitter(splitter).setLogger(logger);
this.listener = new CommandListener(manager);
eventManager.registerEvents(listener);
}
/*
* Getter
*/
public CommandManager getManager() {
return manager;
}
public CommandListener getListener() {
return listener;
}
/*
* Command Loading
*/
public int load(PluginManager pluginManager) {
if (manager.getCommands().length != 0)
manager.unregisterAll();
List<PluginWrapper> wrappers = pluginManager.getStartedPlugins();
if (wrappers.isEmpty())
return 0;
int size = wrappers.size();
for (int index = 0; index < size; index++) {
PluginWrapper wrapper = wrappers.get(index);
List<Class<? extends CommandExtension>> extensions = pluginManager.getExtensionClasses(CommandExtension.class, wrapper.getPluginId());
if (extensions.isEmpty())
continue;
ArrayList<AmongCommand> commands = new ArrayList<>();
int size0 = extensions.size();
for (int index0 = 0; index0 < size0; index0++) {
Class<? extends CommandExtension> clazz = extensions.get(index0);
try {
clazz.getDeclaredConstructor().newInstance().onCommandCreation(commands);
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
continue;
}
}
if (commands.isEmpty())
continue;
size0 = commands.size();
for (int index0 = 0; index0 < size0; index0++) {
AmongCommand command = commands.get(index0);
Alias alias;
if ((alias = command.info()) == null)
continue;
manager.register(new PluginCommand(wrapper, command), alias);
}
}
return manager.getCommands().length;
}
/*
* Command Management
*/
public PluginCommand[] getCommands(PluginWrapper wrapper) {
return getCommands(wrapper == null ? null : wrapper.getPluginId());
}
public PluginCommand[] getCommands(String pluginId) {
if (pluginId == null)
return new PluginCommand[0];
return Arrays.stream(manager.getCommands()).filter(command -> command instanceof PluginCommand).map(command -> (PluginCommand) command)
.filter(command -> command.getWrapper().getPluginId().equals(pluginId)).toArray(size -> new PluginCommand[size]);
}
}
| d8c5cfe22721de17b289ae304aa015c08425a0f9 | [
"Java"
] | 13 | Java | SourceWriters/amongus4j | ada7b3697d27f60df2485450183bc425365529c2 | 51e78b170af48d7aaef0568b9d7db4527e4d1a18 |
refs/heads/main | <repo_name>trasgoverde/dh<file_sep>/src/main/java/com/blocknitive/com/repository/package-info.java
/**
* Spring Data JPA repositories.
*/
package com.blocknitive.com.repository;
<file_sep>/src/main/java/com/blocknitive/com/config/package-info.java
/**
* Spring Framework configuration files.
*/
package com.blocknitive.com.config;
<file_sep>/src/test/resources/i18n/messages_es.properties
email.test.title=Activación de dh
| 493062b6ecba6d73b1af61d413f031e3a2ce275c | [
"Java",
"INI"
] | 3 | Java | trasgoverde/dh | 2031d757df5f8f420c8084dd5b9e5875accff454 | e580d16bcd4dd1abf3845915c3ff37d8cf109e38 |
refs/heads/master | <repo_name>deviyantiam/Ujian_Pemain_Muda_Berbakat<file_sep>/soal2_1.py
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df=pd.read_csv('data.csv')
print(list(df))
df_n=df[['Name','Age','Overall','Potential']] #buat df lebih mudah dilihat
xao=df_n['Age'][(df_n['Age']<=25)&(df_n['Overall']>=80)&(df_n['Potential']>=80)]
yao=df_n['Overall'][(df_n['Age']<=25)& (df_n['Overall']>=80)&(df_n['Potential']>=80)]
yap=df_n['Potential'][(df_n['Age']<=25)& (df_n['Potential']>=80)&(df_n['Overall']>=80)]
ind_xao=xao.index.tolist()
xao_bukan=df_n['Age'].loc[~df_n.index.isin(ind_xao)] #bukan target
yao_bukan=df_n['Overall'].loc[~df_n.index.isin(ind_xao)] #bukan target
yap_bukan=df_n['Potential'].loc[~df_n.index.isin(ind_xao)] #bukan target
## Plot Age vs Overall dan Age vs Potential
plt.figure(figsize=(13,8))
ax=plt.subplot(121)
plt.scatter(xao,yao,color='green',label='Target')
plt.scatter(xao_bukan,yao_bukan,color='red',label='Non-Target')
plt.ylabel('Overall')
plt.legend()
plt.xlabel('Age')
plt.grid(True)
ax.set_title("Age vs Overall")
bx=plt.subplot(122)
plt.scatter(xao,yap,color='green',label='Target')
plt.scatter(xao_bukan,yap_bukan,color='red',label='Non-Target')
plt.ylabel('Overall')
plt.xlabel('Age')
plt.legend()
bx.set_title("Age vs Potential")
plt.grid(True)
plt.show()<file_sep>/soal2_2.py
'''
Berdasarkan model yang saya buat, paling bagus decision tree dengan rincian dibawah
DecisionTrees's Accuracy: 1.0
Logistic's Accuracy: 0.9939593629873695
KNN's Accuracy: 0.9989017023613399
Cross_Val_Score untuk Decision Tree 1.0
Cross_Val_Score untuk Linear Regression 0.9924935920908092
Cross_Val_Score untuk KNN 0.9989625289881606
'''
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df=pd.read_csv('data.csv')
# print(list(df))
df_n=df[['Name','Age','Overall','Potential']] #buat df lebih mudah dilihat
#Check if there's any missing values in the dataset
df_n=df_n.replace(['-','n.a'],np.nan)
df_n=df_n.fillna(0)
# print('Jumlah data yang bernilai 0 :')
# print(df_n.isnull().sum())
# print(len(df))
# print(df.head())
xao=df_n[(df_n['Age']<=25)&(df_n['Overall']>=80)&(df_n['Potential']>=80)]
ind_xao=xao.index.tolist() #index yang target
df_n['Status']=['Target' if i in ind_xao else 'Non_Target' for i in range(len(df_n.index))]
# print(df_n.head(10))
from sklearn.preprocessing import LabelEncoder
lab=LabelEncoder()
df_new=df_n #mau di drop kolom statusnya
df_new['Status_en']=lab.fit_transform(df_new['Status']) ####0 bukan target, 1 target
df_new=df_new.drop(['Status'],axis='columns')
# print(df_new.head(10))
untukx=df_new[['Age','Overall','Potential']]
untuky=df_new['Status_en']
##SPLIT
from sklearn.model_selection import train_test_split,KFold
x_trainset, x_testset, y_trainset, y_testset = train_test_split(untukx, untuky, test_size=0.1, random_state=3) #test_size sudah diganti2, tetep decision tree paling baik
kf=KFold(n_splits=3,random_state=1) ##buat cross_validation
## TREE
from sklearn import tree
#Train Model and Predict
fifaTree=tree.DecisionTreeClassifier(criterion='entropy',max_depth=3)
fifaTree.fit(x_trainset,y_trainset)
predTree = fifaTree.predict(x_testset)
## score/accuracy
from sklearn import metrics
print("DecisionTrees's Accuracy: ", metrics.accuracy_score(y_testset, predTree))
'''
##EVALUATION untuk decision tree
error=[]
for i in range(1,int(untukx.shape[1])+1):
drugTree=tree.DecisionTreeClassifier(criterion='entropy',max_depth=i)
drugTree.fit(x_trainset,y_trainset)
predTree = drugTree.predict(x_testset)
err=metrics.accuracy_score(y_testset, predTree)
error.append(err)
from sklearn import metrics
# import matplotlib.pyplot as plt
# print("DecisionTrees's Accuracy: ", metrics.accuracy_score(y_testset, predTree))
print(error)
'''
###====================================================================
##LOGISTIC REGRESSION
from sklearn.linear_model import LogisticRegression
modellr=LogisticRegression(solver='lbfgs')
modellr.fit(x_trainset,y_trainset)
predlr=modellr.predict(x_testset)
## score/accuracy
from sklearn import metrics
print("Logistic's Accuracy: ", metrics.accuracy_score(y_testset, predlr))
###====================================================================
##KNN
from sklearn.neighbors import KNeighborsClassifier
k = 11 #paling bagus di gambar pada step evaluation
#Train Model and Predict
neigh = KNeighborsClassifier(n_neighbors = k).fit(x_trainset,y_trainset)
predknn = neigh.predict(x_testset)
##score/accuracy
from sklearn import metrics
print("KNN's Accuracy: ", metrics.accuracy_score(y_testset, predknn))
'''
## Evaluation buat KNN
Ks = round((len(x_testset)+len(x_trainset))**.5) ##akar dari jumlah data
mean_acc = np.zeros((Ks-1))
std_acc = np.zeros((Ks-1))
for n in range(1,Ks):
neigh = KNeighborsClassifier(n_neighbors = n).fit(x_trainset,y_trainset)
yhat=neigh.predict(x_testset)
mean_acc[n-1] = metrics.accuracy_score(y_testset, yhat)
std_acc[n-1]=np.std(yhat==y_testset)/np.sqrt(yhat.shape[0])
##plot accuracy
plt.plot(range(1,Ks),mean_acc,'g')
plt.fill_between(range(1,Ks),mean_acc - 1 * std_acc,mean_acc + 1 * std_acc, alpha=0.10)
plt.legend(('Accuracy ', '+/- 3xstd'))
plt.ylabel('Accuracy ')
plt.xlabel('Number of Nabors (K)')
plt.tight_layout()
plt.show()
'''
# ###====================================================================
# ###CROSSVALL
from sklearn.model_selection import cross_val_score
acctree = cross_val_score(fifaTree,x_trainset,y_trainset,cv=kf) #kf udah diassigned di atas
print('Cross_Val_Score untuk Decision Tree',acctree.mean())
accreg = cross_val_score(modellr,x_trainset,y_trainset,cv=kf) #kf udah diassigned di atas
print('Cross_Val_Score untuk Linear Regression',accreg.mean())
accknn = cross_val_score(neigh,x_trainset,y_trainset,cv=kf) #kf udah diassigned di atas
print('Cross_Val_Score untuk KNN',accknn.mean())
<file_sep>/soal2_3.py
'''
Name Age Overall Potential Status
0 <NAME> 27 87 90 Non-Target
1 <NAME> 22 75 83 Non-Target
2 <NAME> 38 85 75 Non-Target
3 <NAME> 43 90 85 Non-Target
4 <NAME> 18 88 90 Target
5 <NAME> 24 85 87 Target
6 <NAME> 23 77 80 Non-Target
7 <NAME> 24 82 85 Target
8 <NAME> 22 83 80 Target
9 <NAME> 29 88 86 Non-Target
'''
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df=pd.read_csv('data.csv')
# print(list(df))
df_n=df[['Name','Age','Overall','Potential']] #buat df lebih mudah dilihat
xao=df_n[(df_n['Age']<=25)&(df_n['Overall']>=80)&(df_n['Potential']>=80)]
ind_xao=xao.index.tolist() #index yang target
df_n['Status']=['Target' if i in ind_xao else 'Non_Target' for i in range(len(df_n.index))]
# print(df_n.head(10))
from sklearn.preprocessing import LabelEncoder
lab=LabelEncoder()
df_new=df_n #mau di drop kolom statusnya
df_new['Status_en']=lab.fit_transform(df_new['Status'])
df_new=df_new.drop(['Status'],axis='columns')
# print(df_new.head(10))
untukx=df_new[['Age','Overall','Potential']]
untuky=df_new['Status_en']
##SPLIT
from sklearn.model_selection import train_test_split,KFold
x_trainset, x_testset, y_trainset, y_testset = train_test_split(untukx, untuky, test_size=0.1, random_state=3) #test_size sudah diganti2, tetep decision tree paling baik
kf=KFold(n_splits=3,random_state=1) ##buat cross_validation
## TREE
from sklearn import tree
#Train Model and Predict
fifaTree=tree.DecisionTreeClassifier(criterion='entropy',max_depth=3)
fifaTree.fit(x_trainset,y_trainset)
##### PREDICT
dfpred=pd.read_csv('prediksisoal2.csv')
# print(dfpred.head())
x=dfpred.iloc[:,1:] #parameter prediksi
prediksi=fifaTree.predict(x)
levels = {0:'Non-Target', 1:'Target'}
dfpred['Status'] = [levels[x] for x in prediksi]
print(dfpred)
| c6836d67f50d34687c74cf7147ca9a02b3a0e97d | [
"Python"
] | 3 | Python | deviyantiam/Ujian_Pemain_Muda_Berbakat | 48a447620202107695ed449dc02933117729d2c2 | 586252955232af648d61cc4c193c89d328c4817a |
refs/heads/master | <repo_name>si13n/todolist<file_sep>/app/controllers/projects_controller.rb
class ProjectsController < ApplicationController
before_action :authenticate_user!
def index
@projects = Project.where(:user_id => current_user.id)
end
def create
@project = Project.new(project_params)
@project.save
redirect_to projects_path, notice: 'Project was successfully created.'
end
def edit
@project = Project.find(params[:id])
respond_to do |format|
format.js
end
end
def update
@project = Project.find(params[:id])
@project.update(project_params)
redirect_to projects_path, notice: 'Project was successfully updated.'
end
def destroy
@project = Project.find(params[:id])
@project.destroy
redirect_to projects_path, notice: 'Project was successfully deleted.'
end
private
def project_params
params.require(:project).permit(:name, :user_id)
end
end
<file_sep>/app/controllers/sql_controller.rb
class SqlController < ApplicationController
def queries
end
end
<file_sep>/README.md
# Task manager
I'm a person who passionate about my own productivity. I want to manage my tasks
and projects more effectively. I need a simple tool that supports me in controlling my
task-flow
Functional requirements
* I want to be able to create/update/delete projects
* I want to be able to add tasks to my project
* I want to be able to update/delete tasks
* I want to be able to prioritize tasks into a project
* I want to be able to choose deadline for my task
* I want to be able to mark a task as 'done'
Technical requirements
* It should be a WEB application
* For the client side must be used: HTML, CSS (any libs as Twitter Bootstrap,
Blueprint ...), JavaScript (any libs as jQuery, Prototype ...)
* For a server side any language as Ruby, PHP, Python, JavaScript, C#, Java ...
* It should have a client side and server side validation
* It should look like on screens (see attached file ‘rg_test_task_grid.png’).
Additional functionality
* It should work like one page WEB application and should use AJAX technology, load
and submit data without reloading a page.
* It should have user authentication solution and a user should only have access to
their own projects and tasks.
* It should have automated tests for the all functionality<file_sep>/app/controllers/tasks_controller.rb
class TasksController < ApplicationController
before_action :authenticate_user!
def edit
@project = Project.find(params[:project_id])
@task = @project.tasks.find(params[:id])
respond_to do |format|
format.js
end
end
def create
@project = Project.find(params[:project_id])
@task = @project.tasks.create(task_params)
redirect_to projects_path
end
def update
@task = Task.find(params[:id])
@task.update(task_params)
redirect_to projects_path
end
def destroy
@project = Project.find(params[:project_id])
@task = @project.tasks.find(params[:id])
@task.destroy
redirect_to projects_path
end
def priority
@project = Project.find(params[:project_id])
@task = @project.tasks.find(params[:id])
@task.priority!
redirect_to projects_path
end
def complete
@project = Project.find(params[:project_id])
@task = @project.tasks.find(params[:id])
@task.complete!
redirect_to projects_path
end
private
def task_params
params.require(:task).permit(:name, :project_id, :id, :priority, :user_id, :due_date, :status)
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
get 'sql/queries', :as => 'queries'
post "projects/:id/tasks/:id/edit" => "tasks#update"
devise_for :users
root 'projects#index'
resources :projects do
resources :tasks do
put 'priority', on: :member
put 'complete', on: :member
end
end
end
<file_sep>/test/controllers/sql_controller_test.rb
require 'test_helper'
class SqlControllerTest < ActionDispatch::IntegrationTest
test "should get queries" do
get sql_queries_url
assert_response :success
end
end
<file_sep>/app/models/task.rb
class Task < ApplicationRecord
validates :name, presence: true, length: { in: 4..200 }
belongs_to :project
before_create :set_defaults
PRIORITIES = ['Low','Medium','High','Urgent']
def complete!
self.status = !self.status
save
end
def priority!
if self.priority
self.priority == 3 ? self.priority = 0 : self.priority += 1
else
self.priority = 0
end
save
end
private
def set_defaults
self.priority = 0
self.status = false
end
end
<file_sep>/Gemfile
source 'https://rubygems.org'
git_source(:github) do |repo_name|
repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
"https://github.com/#{repo_name}.git"
end
gem 'rails', '~> 5.1.4'
gem 'puma', '~> 3.7'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.2'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
gem 'semantic-ui-sass'
gem 'devise'
gem 'jquery-rails'
gem 'bcrypt', git: 'https://github.com/codahale/bcrypt-ruby.git', :require => 'bcrypt'
group :development do
gem 'sqlite3'
end
group :production do
gem 'pg', '~> 0.18'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
<file_sep>/app/models/project.rb
class Project < ApplicationRecord
validates :name, presence: true,
length: { in: 4..100 }
has_many :tasks, dependent: :delete_all
end
| 37951c66334f834e29d1b626d951ed07c57104ca | [
"Markdown",
"Ruby"
] | 9 | Ruby | si13n/todolist | 70f14e83049fe3847808e7471ba4ab1ac0deec3c | bd77ed66e38ab5615fc6618dd0e6b096931016a3 |
refs/heads/master | <repo_name>russfeld/hubot-russbot<file_sep>/scripts/lib/common.js
function randomString(strings){
if(typeof strings == 'string'){
return strings;
}else if (strings instanceof Array){
return strings[Math.floor(Math.random() * strings.length)];
}
}
function applyVariable(string, variable, value){
console.log("Matching variable: " + variable);
string = string.replace(new RegExp('\\$' + variable, 'g'), value);
return string;
}
function replaceVariables(string, res){
string = applyVariable(string, "user", res.envelope.user.name);
return string;
}
function sendMessages(strings, res){
if(!(Array.isArray(strings))){
strings = [strings];
}
strings.forEach(function(string){
string = replaceVariables(string, res);
res.send(string);
})
}
module.exports = {randomString, sendMessages};
<file_sep>/scripts/lib/handler.js
fs = require('fs');
path = require('path');
actions = {}
function register(actionpath){
actionpath = path.join(__dirname, "..", actionpath);
console.log("Loading actions from " + actionpath);
fs.readdirSync(actionpath).sort().forEach(function(action){
name = action.replace(".js", "");
actions[name] = require(actionpath + "/" + action);
});
}
function takeAction(res, msg, interaction){
if(!(interaction.action in actions)){
res.reply("I'm sorry, Dave. I'm afraid I can't do that.");
}else{
actions[interaction.action].process(res, msg, interaction);
}
}
module.exports = {takeAction, register};
<file_sep>/scripts/lib/security.js
//Get user roles from Rocket.chat
function getUserRoles(robot){
var usersAndRoles = {};
robot.adapter.driver.callMethod('getUserRoles').then(function(users){
users.forEach(function(user){
user.roles.forEach(function(role){
if(!(role in usersAndRoles)){
usersAndRoles[role] = [];
}
usersAndRoles[role].push(user.username);
});
});
//robot.logger.info(JSON.stringify(usersAndRoles));
robot.brain.set("usersAndRoles", usersAndRoles);
});
}
//check if the user in a message has the provided role
function checkRole(msg, role){
var usersAndRoles = msg.robot.brain.get("usersAndRoles") || {};
if(Object.entries(usersAndRoles).length === 0 && usersAndRoles.constructor === Object){
msg.robot.logger.info("Roles are empty!");
}else{
if(usersAndRoles[role].indexOf(msg.envelope.user.name) > -1){
return true;
}else{
return false;
}
}
}
module.exports = {getUserRoles, checkRole}
<file_sep>/README.md
# Russbot 2.0
Built with love with Hubot and a bunch of secret sauce
More details coming soon!
<file_sep>/scripts/actions/respond.js
common = require('../lib/common');
function process(res, msg, interaction){
common.sendMessages(common.randomString(interaction.answer), res);
}
module.exports = {process}
<file_sep>/scripts/lib/classifier.js
natural = require("natural");
root_classifier = {};
root_trust = 0.0;
root_corpus = {};
function classify(interaction, classifier){
if(!("expect" in interaction)){
console.warn("\t Interaction with no expect: " + interaction.name);
return;
}
console.log("\t Processing interaction: " + interaction.name);
if(!(Array.isArray(interaction.expect))){
interaction.expect = [interaction.expect];
}
interaction.expect.forEach(function(document){
if(!(typeof document === 'string' || document instanceof String)){
document = '' + document;
}
//console.log("\t\t Adding Document: " + document);
classifier.addDocument(document, interaction.name);
});
}
function train(acorpus){
root_corpus = acorpus;
console.log("Processing corpus");
console.time("Processing corpus (Done)");
root_classifier = new natural.LogisticRegressionClassifier(natural.PorterStemmer);
root_trust = root_corpus.trust;
root_corpus.interactions.forEach(function(interaction){
classify(interaction, root_classifier);
});
console.log("Training Classifier (this may take some time...)");
root_classifier.train();
console.timeEnd("Processing corpus (Done)");
}
function processMessage(res, msg){
current_classifier = root_classifier;
current_trust = root_trust;
console.log("\tNLP message: " + msg);
console.log("\t\tContext: " + "root");
classifications = current_classifier.getClassifications(msg);
console.log("\t\tClassifications: ");
console.log(classifications.slice(0, 4));
if(classifications[0].value >= current_trust){
var interaction = root_corpus.interactions.find(function(element){
return element.name == classifications[0].label;
})
//console.log(interaction);
return interaction;
}else{
return {};
}
}
module.exports = {train, processMessage};
<file_sep>/scripts/_index.js
security = require("./lib/security");
natural = require("natural");
module.exports = (robot) => {
security.getUserRoles(robot);
}
<file_sep>/scripts/dice.js
// Description:
// Allows Hubot to roll dice
//
// Dependencies:
// None
//
// Configuration:
// None
//
// Commands:
// hubot roll (die|one) - Roll one six-sided dice
// hubot roll dice - Roll two six-sided dice
// hubot roll <x>d<y> - roll x dice, each of which has y sides
// hubot roll <x>d<y>([+-]<z>) - roll x dice, each of which has y sides with a modifier
//
// Author:
// ab9,apowers,rjanardhana
module.exports = function(robot) {
let rollOne;
robot.respond(/roll (die|one)/i, msg => msg.reply(report([rollOne(6)])));
robot.respond(/roll dice/i, msg => msg.reply(report((roll(2, 6)))));
robot.respond(/roll (\d+)d(\d+)([+-]\d+)?/i, function(msg) {
const dice = parseInt(msg.match[1]);
const sides = parseInt(msg.match[2]);
const modifier = (msg.match[3] != null) ? parseInt(msg.match[3]) : null;
const answer = sides < 1 ?
"I don't know how to roll a zero-sided die."
: dice > 100 ?
"I'm not going to roll more than 100 dice for you."
:
report((roll(dice, sides)), modifier);
return msg.reply(answer);
});
var report = function(results, modifier) {
if (results != null) {
let total;
switch (results.length) {
case 0:
return "I didn't roll any dice.";
case 1:
if (modifier != null) {
total = results[0] + modifier;
return `I rolled a ${results[0]} + ${modifier}, making ${total}.`;
} else {
return `I rolled a ${results[0]}.`;
}
default:
total = (results.reduce((x, y) => x + y));
if (modifier != null) {
total += modifier;
}
var finalComma = (results.length > 2) ? "," : "";
var last = results.pop();
if (modifier != null) {
return `I rolled ${results.join(", ")}${finalComma} and ${last} + ${modifier}, making ${total}.`;
} else {
return `I rolled ${results.join(", ")}${finalComma} and ${last}, making ${total}.`;
}
}
}
};
var roll = (dice, sides) => __range__(0, dice, false).map((i) => rollOne(sides));
return rollOne = sides => 1 + Math.floor(Math.random() * sides);
};
function __range__(left, right, inclusive) {
let range = [];
let ascending = left < right;
let end = !inclusive ? right : ascending ? right + 1 : right - 1;
for (let i = left; ascending ? i < end : i > end; ascending ? i++ : i--) {
range.push(i);
}
return range;
}
| b3f1eedcb08d146e4df0fdf00d29cb00cb34a210 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | russfeld/hubot-russbot | cb7f357d70b80a2e36ad84584890439956215b93 | ea236cb8bffe9cd4a6764ec72b5fa20aedb33045 |
refs/heads/master | <repo_name>samcreate/EVB_Boilderplate<file_sep>/www/index.php
<?php
ob_start('ob_gzhandler');
// ======================
// = defining constants =
// ======================
define('DIR_WEB', dirname(__FILE__));
define('DIR_PHPLIB', dirname(__FILE__).'/lib/php');
define('DIR_SYS', DIR_PHPLIB.'/system');
define('DIR_CTRL', DIR_PHPLIB.'/controller');
define('DIR_TMPL', DIR_PHPLIB.'/template');
define('DIR_VIEW', DIR_PHPLIB.'/view');
define('DIR_PLUGINS', DIR_PHPLIB.'/plugins');
// =====================
// = disecting the URI =
// =====================
$ru = &$_SERVER['REQUEST_URI'];
$qmp = strpos($ru, '?');
list($path, $params) = $qmp === FALSE
? array($ru, NULL)
: array(substr($ru, 0, $qmp), substr($ru, $qmp + 1));
$parts = explode('/', $path);
$i = 0;
foreach ($parts as $part)
{
if (strlen($part) && $part !== '..' && $part !== '.')
{
define('URI_PART_'.$i++, $part);
}
}
define('URI_PARAM', isset($params) ? '' : $params);
define('URI_PARTS', $i);
define('URI_PATH', $path);
define('URI_REQUEST', $_SERVER['REQUEST_URI']);
// ==========================
// = routing and other init =
// ==========================
session_start();
require_once DIR_SYS.'/Config.php';
include DIR_SYS.'/router.php';
include DIR_SYS.'/config.routes.php';
$settings = Config::getInstance();
if ($ctrl = Router::controller())
{
include $ctrl;
}
else
{
header('HTTP/1.1 404 Not Found');
}
?>
<file_sep>/README.md
EVB_Boilderplate
================
Simple PHP Project boilerplate using MVC | d7d0efbb4f1a9fa1d61d2980dc150387dad81451 | [
"Markdown",
"PHP"
] | 2 | PHP | samcreate/EVB_Boilderplate | 19baccddf48f3974f87b9d6842552da3ce286647 | b223613e25f1fe97f5e8ac2f1239743856e1fa1f |
refs/heads/master | <file_sep>3.2.4.1 BETA (2014/12/16)
---------------------------
Global:
- Pgina service bugfixes
- Pgina service extend max shutdowntime to 1h
LDAP plugin:
- a view bugfixes
- option to use authentication bind when searching in authorization and gateway stages.
pgSMB plugin:
- add 1 minute timeout if an SMB connection fails
Radius plugin:
- Lots of updates to the RADIUS plugin from Oooska
MySQL plugin:
- add option to prevent (or not) logon in gateway if server error occurs
3.2.0.0 BETA (2013/12/02)
---------------------------
Global:
- reliable Logoff detection (e4d2a96484cdb060262c515d19e1a21dee4282e6)
- a profiles is not reloded during an unlock (#9)
- Accept credentials provided by RDP clients (weiss)
- UserInformation fix NullReferenceException (0ac6606b84e945e195fce0b96c5a4f58807dfa5f)
- add password change (<PASSWORD>)
- password change plugin handling changed to abort as soon as a plugin returns an error
LDAP plugin:
- attribute converter added
- TLS option added
- Authorization and Gateway search changed
- Authorization Default behavior changed (white- or blacklist)
- remove BouncyCastle crypto lib
- add ldap timestamp attributes
LocalMachine plugin:
- added Roaming profile and Loginscript support (attribute converter)
pgSMB plugin:
- can overwrite settings from ldap attributes (attribute converter)
- pgSMB quota GPO not set during first login (#10)
3.1.6.2 BETA (2013/03/13)
---------------------------
- bug fixing only
3.1.6.1 BETA (2013/01/08)
---------------------------
- bugfix free memory (#146)
- finally Fix session cache bug related to CredUI login (#153).
- added plugin pgSMB
changed LocaleMachine plugin cleanup be triggered by Events
preventing a system shutdown while cleanupjobs are running
Make userprofile cleanup depended on the comment of the userprofile field
- A Message will be displayed during logon
3.1.6.0 BETA (2012/10/24)
---------------------------
- Support for filtering in CredUI scenario.
- Simulator explains lack of logging when using pGina service.
- Support for using original username in the unlock scenario (CP only, #154).
- Fix session cache bug related to CredUI login (#153).
3.1.5.0 BETA (2012/10/03)
---------------------------
- Filtering of any credential provider (#144, #132)
- MySQL: Fix for problem when no hash alg is used (#145)
- Email Auth: IMAP fixes (#150. #151)
3.1.4.0 BETA (2012/07/26)
---------------------------
- MySQL Auth Plugin: support for groups in Gateway (#114)
- Show group list in simulator.
- Support AutoAdminLogon in GINA (#99)
- Fixes for dependency loading (#142,#143)
3.1.3.0 BETA (2012/07/12)
---------------------------
- RADIUS plugin: Improved logging and thread safety (Oooska)
- Fix: crash when unresolvable SIDs exist in groups (#121)
- LocalMachine plugin: make options more flexible for password scrambling
and profile deletion.
3.1.2.0 BETA (2012/07/02)
---------------------------
- New RADIUS plugin (Oooksa)
- Fix: install Cred Prov using env (#137)
- Configuration UI tweaks
3.1.1.0 BETA (2012/06/23)
---------------------------
- LocalMachine plugin: change functionality of the scramble passwords
option. (#136)
- LDAP plugin: support groupOfUniqueNames and groupOfNames object
classes. (#135)
- LDAP plugin: better tool-tips
- GINA support for optional MOTD and service status.
3.1.0.0 BETA (2012/06/05)
---------------------------
- Simulator reworked to include individual plugin information
- MySQL Logger plugin numerous changes (Oooska)
- Single User Login plugin provides more flexibility in options (Oooksa)
- LDAP plugin includes support for group authorization and adding/removing
from local groups.
- Add IStatefulPlugin interface to plugin API
- MySQL auth plugin includes configurable column names
- Make MOTD and service status display optional (in Credential Providers)
3.0.12.1 (2012/06/05)
---------------------------
- Fix for custom CA certs in Windows store (#107)
- Icon improvements
3.0.12.0 (2012/05/29)
---------------------------
- Installer enhancements: internal changes, less noisy at post install
- Fix issue with web services (#127)
- Fix issue with failure when network is disconnected (#128)
- Change default setting for Local Machine authorization stage (#119)
3.0.11.2 (2012/05/16)
---------------------------
- Add some additional logging in install mode.
3.0.11.1 (2012/05/08)
---------------------------
- Bug fix for systems with password security policies (#126)
3.0.11.0 (2012/04/07)
---------------------------
- LDAP plugin option to always fail on empty passwords (#118)
3.0.10.0 (2012/03/25)
---------------------------
- EmailAuth Plugin updates to 3.0.0.1
- Add UsernameMod plugin by <NAME>
3.0.9.0 BETA (2012/03/10)
----------------------------
- Added EmailAuth plugin by <NAME>
- Fixed Issue #93 - GINA crashes if left at login window for several minutes
- Fixed Bug with SingleUser plugin password
- Fixed Issue #98 - Trim whitespace around username prior to login
3.0.8.0 BETA (2012/02/13)
----------------------------
- Added install utility to manage all post install/uninstall tasks.
- Install utility sets ACLs on registry key to only allow SYSTEM/Admin access.
- Log files moved to separate directory (default).
- Service spawns thread to handle initialization so that service can
respond immediately to the OS on startup.
- Fix configuration bug in LDAP Auth plugin (issue #95)
3.0.7.0 BETA (2012/01/25)
----------------------------
- MySQL Auth plugin support for salted hashes and base 64 encoding.
- Configuration app now requires admin escalation in order to run.
3.0.6.0 BETA (2012/01/10)
----------------------------
- Improved exception handling in user cleanup.
- Fix bug in locked scenario (#80)
- Better "login failed" messages from LDAP auth plugin.
3.0.5.0 BETA (2012/01/03)
----------------------------
- Minor logging changes.
3.0.4.0 BETA (2012/01/02)
----------------------------
- Error handling fixes (#79)
3.0.3.0 BETA (2012/01/02)
----------------------------
- Config UI improvments.
- Installer fixes
- Improve external DLL loading (#71).
- Major speed improvements in LocalMachine plugin.
- Fix GINA on XP.
3.0.2.0-BETA (2011/11/05)
----------------------------
- Add msbuild file.
- Add MySQL auth plugin.
3.0.1.0 BETA (2011/10/15)
----------------------------
- Initial release.
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using log4net;
using pGina.Shared.Interfaces;
using pGina.Shared.Types;
using pGina.Shared.Settings;
namespace pGina.Plugin.RADIUS
{
//TODO:
//Idle-Timeout - Unsure if possible / pgina's responsibility
public class RADIUSPlugin : IPluginConfiguration, IPluginAuthentication, IPluginEventNotifications
{
private ILog m_logger = LogManager.GetLogger("RADIUSPlugin");
public static Guid SimpleUuid = new Guid("{350047A0-2D0B-4E24-9F99-16CD18D6B142}");
private string m_defaultDescription = "A RADIUS Authentication and Accounting Plugin";
private dynamic m_settings = null;
private Dictionary<Guid, Session> m_sessionManager;
public RADIUSPlugin()
{
using(Process me = Process.GetCurrentProcess())
{
m_settings = new pGinaDynamicSettings(SimpleUuid);
m_settings.SetDefault("ShowDescription", true);
m_settings.SetDefault("Description", m_defaultDescription);
m_sessionManager = new Dictionary<Guid, Session>();
m_logger.DebugFormat("Plugin initialized on {0} in PID: {1} Session: {2}", Environment.MachineName, me.Id, me.SessionId);
}
}
public string Name
{
get { return "RADIUS Plugin"; }
}
public string Description
{
get { return m_settings.Description; }
}
public string Version
{
get
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public Guid Uuid
{
get { return SimpleUuid; }
}
//Authenticates user
BooleanResult IPluginAuthentication.AuthenticateUser(SessionProperties properties)
{
m_logger.DebugFormat("AuthenticateUser({0})", properties.Id.ToString());
if (!(bool)Settings.Store.EnableAuth)
{
m_logger.Debug("Authentication stage set on RADIUS plugin but authentication is not enabled in plugin settings.");
return new BooleanResult() { Success = false };
}
// Get user info
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
if(String.IsNullOrEmpty(userInfo.Username) || String.IsNullOrEmpty(userInfo.Password))
return new BooleanResult() { Success = false, Message = "Username and password must be provided." };
try
{
RADIUSClient client = GetClient();
bool result = client.Authenticate(userInfo.Username, userInfo.Password);
if (result)
{
Session session = new Session(properties.Id, userInfo.Username, client);
Packet p = client.lastReceievedPacket;
//Check for session timeout
if ((bool)Settings.Store.AllowSessionTimeout && p.containsAttribute(Packet.AttributeType.Session_Timeout))
{
int seconds = client.lastReceievedPacket.getFirstIntAttribute(Packet.AttributeType.Session_Timeout);
session.SetSessionTimeout(seconds, SessionTimeoutCallback);
//m_logger.DebugFormat("Setting timeout for {0} to {1} seconds.", userInfo.Username, seconds);
}
if (p.containsAttribute(Packet.AttributeType.Idle_Timeout))
{
int seconds = client.lastReceievedPacket.getFirstIntAttribute(Packet.AttributeType.Idle_Timeout);
}
if(p.containsAttribute(Packet.AttributeType.Vendor_Specific)){
foreach(byte[] val in p.getByteArrayAttributes(Packet.AttributeType.Vendor_Specific)){
//m_logger.DebugFormat("Vendor ID: {0:D}, Type: {1:D}, Value: {2}", Packet.VSA_vendorID(val), Packet.VSA_VendorType(val), Packet.VSA_valueAsString(val));
if ((bool)Settings.Store.WisprSessionTerminate && Packet.VSA_vendorID(val) == (int)Packet.VSA_WISPr.Vendor_ID
&& Packet.VSA_VendorType(val) == (int)Packet.VSA_WISPr.WISPr_Session_Terminate_Time)
{
try
{
//Value is in format "2014-03-11T23:59:59"
string sdt = Packet.VSA_valueAsString(val);
DateTime dt = DateTime.ParseExact(sdt, "yyyy-MM-dd'T'HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
if (dt > DateTime.Now)
{
session.Set_Session_Terminate(dt, SessionTerminateCallback);
}
else
m_logger.DebugFormat("The timestamp provided for WisperSessionTerminate time value has passed.");
}
catch (FormatException e)
{
m_logger.DebugFormat("Unable to parse timestamp: {0}", Packet.VSA_valueAsString(val));
}
}
}
}
//Check for interim-update
if ((bool)Settings.Store.SendInterimUpdates)
{
int seconds = 0;
if (p.containsAttribute(Packet.AttributeType.Acct_Interim_Interval))
{
seconds = client.lastReceievedPacket.getFirstIntAttribute(Packet.AttributeType.Acct_Interim_Interval);
}
//Check to see if plugin is set to send interim updates more frequently
if ((bool)Settings.Store.ForceInterimUpdates)
{
int forceTime = (int)Settings.Store.InterimUpdateTime;
if (forceTime > 0)
seconds = forceTime;
}
//Set interim update
if (seconds > 0)
{
session.SetInterimUpdate(seconds, InterimUpdatesCallback);
m_logger.DebugFormat("Setting interim update interval for {0} to {1} seconds.", userInfo.Username, seconds);
}
else
{
m_logger.DebugFormat("Interim Updates are enabled, but no update interval was provided by the server or user.");
}
}
lock (m_sessionManager)
{
//m_logger.DebugFormat("Adding session to m_sessionManager. ID: {0}, session: {1}", session.id, session);
m_sessionManager.Add(session.id, session);
}
string message = null;
if (p.containsAttribute(Packet.AttributeType.Reply_Message))
message = p.getFirstStringAttribute(Packet.AttributeType.Reply_Message);
return new BooleanResult() { Success = result, Message = message };
}
//Failure
string msg = "Unable to validate username or password.";
if (client.lastReceievedPacket == null)
{
msg = msg + " No response from server.";
}
else if (client.lastReceievedPacket.containsAttribute(Packet.AttributeType.Reply_Message))
{
msg = client.lastReceievedPacket.getFirstStringAttribute(Packet.AttributeType.Reply_Message);
}
else if (client.lastReceievedPacket.code == Packet.Code.Access_Reject)
{
msg = msg + String.Format(" Access Rejected.");
}
return new BooleanResult() { Success = result, Message = msg };
}
catch (RADIUSException re)
{
m_logger.Error("An error occurred during while authenticating.", re);
return new BooleanResult() { Success = false, Message = re.Message };
}
catch (Exception e)
{
m_logger.Error("An unexpected error occurred while authenticating.", e);
throw e;
}
}
//Processes accounting on logon/logoff
public void SessionChange(int SessionId, System.ServiceProcess.SessionChangeReason Reason, SessionProperties properties)
{
if (Reason != System.ServiceProcess.SessionChangeReason.SessionLogon
&& Reason != System.ServiceProcess.SessionChangeReason.SessionLogoff)
{
//m_logger.DebugFormat("Not logging on or off for this session change call ({0})... exiting.", changeDescription.Reason);
return;
}
if (properties == null)
{
//m_logger.DebugFormat("No session properties available. This account does not appear to be managed by pGina. Exiting SessionChange()");
return;
}
if (!(bool)Settings.Store.EnableAcct)
{
m_logger.Debug("Session Change stage set on RADIUS plugin but accounting is not enabled in plugin settings.");
return;
}
//Determine username (may change depending on value of UseModifiedName setting)
string username = null;
UserInformation ui = properties.GetTrackedSingle<UserInformation>();
if (ui == null)
{
//m_logger.DebugFormat("No userinformation for this session logoff... exiting...");
return;
}
if ((bool)Settings.Store.UseModifiedName)
username = ui.Username;
else
username = ui.OriginalUsername;
Session session = null;
//User is logging on
if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogon)
{
lock (m_sessionManager)
{
//Check if session information is already available for this id
if (!m_sessionManager.Keys.Contains(properties.Id))
{
//No session info - must have authed with something other than RADIUS.
//m_logger.DebugFormat("RADIUS Accounting Logon: Unable to find session for {0} with GUID {1}", username, properties.Id);
if(!(bool)Settings.Store.AcctingForAllUsers){
//m_logger.Debug("Accounting for non-RADIUS users is disabled. Exiting.");
return;
}
RADIUSClient client = GetClient();
session = new Session(properties.Id, username, client);
m_sessionManager.Add(properties.Id, session);
//Check forced interim-update setting
if ((bool)Settings.Store.SendInterimUpdates && (bool)Settings.Store.ForceInterimUpdates)
{
int interval = (int)Settings.Store.InterimUpdateTime;
session.SetInterimUpdate(interval, InterimUpdatesCallback);
}
}
else
session = m_sessionManager[properties.Id];
}
//Determine which plugin authenticated the user (if any)
PluginActivityInformation pai = properties.GetTrackedSingle<PluginActivityInformation>();
Packet.Acct_Authentic authSource = Packet.Acct_Authentic.Not_Specified;
IEnumerable<Guid> authPlugins = pai.GetAuthenticationPlugins();
Guid LocalMachinePluginGuid = new Guid("{12FA152D-A2E3-4C8D-9535-5DCD49DFCB6D}");
foreach (Guid guid in authPlugins)
{
if (pai.GetAuthenticationResult(guid).Success)
{
if (guid == SimpleUuid)
authSource = Packet.Acct_Authentic.RADIUS;
else if (guid == LocalMachinePluginGuid)
authSource = Packet.Acct_Authentic.Local;
else //Not RADIUS, not Local, must be some other auth plugin
authSource = Packet.Acct_Authentic.Remote;
break;
}
}
//We can finally start the accounting process
try
{
lock (session)
{
session.windowsSessionId = SessionId; //Grab session ID now that we're authenticated
session.username = username; //Accting username may have changed depending on 'Use Modified username for accounting option'
session.client.startAccounting(username, authSource);
//m_logger.DebugFormat("Successfully completed accounting start process...");
}
}
catch (Exception e)
{
m_logger.Error("Error occurred while starting accounting.", e);
}
}
//User is logging off
else if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogoff)
{
lock (m_sessionManager)
{
if (m_sessionManager.Keys.Contains(properties.Id))
session = m_sessionManager[properties.Id];
else
{
//m_logger.DebugFormat("Users {0} is logging off, but no RADIUS session information is available for session ID {1}.", username, properties.Id);
return;
}
//Remove the session from the session manager
m_sessionManager.Remove(properties.Id);
}
lock (session)
{
//Disbale any active callbacks for this session
session.disableCallbacks();
session.active = false;
//Assume normal logout if no other terminate reason is listed.
if (session.terminate_cause == null)
session.terminate_cause = Packet.Acct_Terminate_Cause.User_Request;
try
{
//m_logger.DebugFormat("About to send accounting stop packet. Session has been active {0} seconds.", (DateTime.Now - session.client.accountingStartTime).TotalSeconds);
session.client.stopAccounting(session.username, session.terminate_cause);
}
catch (RADIUSException re)
{
m_logger.DebugFormat("Unable to send accounting stop message for user {0} with ID {1}. Message: {2}", session.username, session.id, re.Message);
}
}
}
}
public void Configure()
{
Configuration conf = new Configuration();
conf.ShowDialog();
}
public void Starting()
{
if(m_sessionManager == null)
m_sessionManager = new Dictionary<Guid, Session>();
}
public void Stopping() { }
//Returns the client instantiated based on registry settings
private RADIUSClient GetClient(string sessionId = null)
{
string[] servers = Regex.Split(Settings.Store.Server.Trim(), @"\s+");
int authport = Settings.Store.AuthPort;
int acctport = Settings.Store.AcctPort;
string sharedKey = Settings.Store.GetEncryptedSetting("SharedSecret");
int timeout = Settings.Store.Timeout;
int retry = Settings.Store.Retry;
byte[] ipAddr = null;
string nasIdentifier = null;
string calledStationId = null;
if((bool)Settings.Store.SendNASIPAddress)
ipAddr = getNetworkInfo().Item1;
if((bool)Settings.Store.SendNASIdentifier){
nasIdentifier = Settings.Store.NASIdentifier;
nasIdentifier = nasIdentifier.Contains('%') ? replaceSymbols(nasIdentifier) : nasIdentifier;
}
if ((bool)Settings.Store.SendCalledStationID)
{
calledStationId = (String)Settings.Store.CalledStationID;
calledStationId = calledStationId.Contains('%') ? replaceSymbols(calledStationId) : calledStationId;
}
RADIUSClient client = new RADIUSClient(servers, authport, acctport, sharedKey, timeout, retry, sessionId, ipAddr, nasIdentifier, calledStationId);
return client;
}
private string replaceSymbols(string str)
{
Tuple<byte[], string> networkInfo = getNetworkInfo();
return str.Replace("%macaddr", networkInfo.Item2)
.Replace("%ipaddr", String.Join(".", networkInfo.Item1))
.Replace("%computername", Environment.MachineName);
}
//Returns a tuple containing the current IPv4 address and mac address for the adapter
//If ipAddressRegex is set, this will attempt to return the first address that matches the expression
//Otherwise it returns the first viable IP address or 0.0.0.0 if no viable address is found. An empty
//string is sent if no mac address is determined.
private Tuple<byte[], string> getNetworkInfo()
{
string ipAddressRegex = Settings.Store.IPSuggestion;
//Fallback values
byte[] ipAddr = null;
string macAddr = null;
//Check each network adapter.
foreach(NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()){
foreach (UnicastIPAddressInformation ipaddr in nic.GetIPProperties().UnicastAddresses)
{ //Check to see if the NIC has any valid IP addresses.
if (ipaddr.Address.AddressFamily == AddressFamily.InterNetwork)
if (String.IsNullOrEmpty(ipAddressRegex) || //IP address, grab first adapter or check if it matches ip regex
Regex.Match(ipaddr.Address.ToString(), ipAddressRegex).Success)
return Tuple.Create(ipaddr.Address.GetAddressBytes(), nic.GetPhysicalAddress().ToString());
else if(ipAddr == null && macAddr == null){ //Fallback, grab info from first device
ipAddr = ipaddr.Address.GetAddressBytes();
macAddr = nic.GetPhysicalAddress().ToString();
}
}
}
if (ipAddr == null) ipAddr = new byte[] { 0, 0, 0, 0 };
if (macAddr == null) macAddr = "";
return Tuple.Create(ipAddr, macAddr);
}
//Gets invoked by timer callback after the session times out
private void SessionTimeoutCallback(object state)
{
Session session = (Session)state;
//Lock session? Might cause issues when we call LogoffSession on user and trigger the SessionChange method?
if(!session.windowsSessionId.HasValue){
m_logger.DebugFormat("Attempting to log user {0} out due to timeout, but no windows session ID is present for ID {1}", session.username, session.id);
return;
}
if (session.terminate_cause != null)
{
m_logger.DebugFormat("User {0} has timed out, but terminate cause #{1} has already been set for ID {2}", session.username, session.terminate_cause, session.id);
}
session.terminate_cause = Packet.Acct_Terminate_Cause.Session_Timeout;
m_logger.DebugFormat("Logging off user {0} in session{1} due to session timeout.", session.username, session.windowsSessionId);
bool result = Abstractions.WindowsApi.pInvokes.LogoffSession(session.windowsSessionId.Value);
//m_logger.DebugFormat("Log off {0}.", result ? "successful" : "failed");
}
//Gets invoked if wispr session limit
private void SessionTerminateCallback(object state)
{
Session session = (Session)state;
session.terminate_cause = Packet.Acct_Terminate_Cause.Session_Timeout;
if (!session.windowsSessionId.HasValue)
{
m_logger.DebugFormat("Attempting to log user {0} out due to WISPr Session limit, but no windows session ID is present for ID {1}", session.username, session.id);
return;
}
if (session.terminate_cause != null)
{
m_logger.DebugFormat("User {0} has reached WISPr Session limit, but terminate cause #{1} has already been set for ID {2}", session.username, session.terminate_cause, session.id);
}
session.terminate_cause = Packet.Acct_Terminate_Cause.Session_Timeout;
m_logger.DebugFormat("Logging off user {0} in session{1} due to session-terminate-time.", session.username, session.windowsSessionId);
bool result = Abstractions.WindowsApi.pInvokes.LogoffSession(session.windowsSessionId.Value);
//m_logger.DebugFormat("Log off {0}.", result ? "successful" : "failed");
}
//Gets invoked when its time to send interim updates
private void InterimUpdatesCallback(object state)
{
Session session = (Session)state;
//m_logger.DebugFormat("Sending interim-update for user {0}", session.username);
lock (session)
{
try
{
if (session.active)
session.client.interimUpdate(session.username);
else
{
session.disableCallbacks();
}
}
catch (RADIUSException e)
{
m_logger.DebugFormat("Unable to send interim-update: {0}", e.Message);
}
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
namespace pGina.Plugin.Ldap
{
class AttributeEntry
{
public string Name { get; set; }
public Methods Method { get; set; }
public string ToRegistryString()
{
return Name + "\n" + (int)Method;
}
public void FromRegistryString(string str)
{
string[] parts = Regex.Split(str, @"\n");
if (parts.Length == 2)
{
Name = parts[0];
Method = (Methods)Enum.Parse(typeof(Methods), parts[1]);
}
}
}
class CPAttributeSettings
{
public static List<AttributeEntry> Load()
{
string[] values = Settings.Store.ChangePasswordAttributes;
List<AttributeEntry> result = new List<AttributeEntry>();
foreach (string entry in values)
{
AttributeEntry pae = new AttributeEntry();
pae.FromRegistryString(entry);
result.Add(pae);
}
return result;
}
public static void Save(List<AttributeEntry> values)
{
List<string> regList = new List<string>();
foreach (AttributeEntry entry in values)
{
regList.Add(entry.ToRegistryString());
}
Settings.Store.ChangePasswordAttributes = regList.ToArray();
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include "HookedLoggedOutSAS.h"
#include <Macros.h>
// ID's for MSGINA's WlxLoggedOutSAS dialog
#define IDC_MSGINA_USERNAME 1502
#define IDC_MSGINA_PASSWORD <PASSWORD>
namespace pGina
{
namespace GINA
{
/* static */ DLGPROC HookedLoggedOutSAS::s_hookedDlgProc = 0;
/* static */ bool HookedLoggedOutSAS::s_hookingEnabled = false;
/* static */ pGina::Transactions::User::LoginResult HookedLoggedOutSAS::s_loginResult;
/* static */
INT_PTR HookedLoggedOutSAS::MicrosoftDialogProcWrapper(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
if(s_hookedDlgProc == 0)
{
pERROR(L"HookedLoggedOutSAS::MicrosoftDialogProcWrapper: Dialog wrapper called before we know who we're hooking!");
return 0; // Nothin we can do!
}
// Fall through if hooking is not enabled
if(!s_hookingEnabled)
return s_hookedDlgProc(hwnd, msg, wparam, lparam);
// Hooking is on, so we let msgina do its thing
INT_PTR msginaResult = s_hookedDlgProc(hwnd, msg, wparam, lparam);
// If we're init'ing, then we set username, password and queue a message to login
if(msg == WM_INITDIALOG)
{
std::wstring domainUsername = s_loginResult.Domain();
domainUsername += L"\\";
domainUsername += s_loginResult.Username();
pDEBUG(L"HookedLoggedOutSAS::MicrosoftDialogProcWrapper: Hooked dialog, setting username/password and submitting for user: %s", domainUsername.c_str());
SetDlgItemText(hwnd, IDC_MSGINA_USERNAME, domainUsername.c_str());
SetDlgItemText(hwnd, IDC_MSGINA_PASSWORD, s_loginResult.Password().c_str());
SendMessage(hwnd, WM_COMMAND, 1, 1);
}
return msginaResult;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using pGina.Shared.Settings;
namespace pGina.Plugin.Sample
{
public partial class Configuration : Form
{
dynamic m_settings = new pGinaDynamicSettings(SimplePlugin.SimpleUuid);
public Configuration()
{
InitializeComponent();
txtDescription.Text = m_settings.Description;
chkShowDescription.Checked = m_settings.ShowDescription;
}
private void btnOk_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
m_settings.Description = txtDescription.Text;
m_settings.ShowDescription = chkShowDescription.Checked;
this.Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include <windows.h>
#include <winwlx.h>
#include <Macros.h>
#include "Gina.h"
#include "Winlogon.h"
#include "Themes.h"
#define pGINA_FROM_CTX(context) pGina::GINA::Gina * pGina = static_cast<pGina::GINA::Gina *>(context)
/**
Winlogon and a GINA DLL use this function to determine which version of the interface each
was written for.
<strong>Thread Desktop:</strong> Winlogon Desktop\n
<strong>Workstation:</strong> Locked\n
@return TRUE - The GINA DLL can operate with this version of Winlogon.Continue initializing Winlogon. \n
FALSE - The GINA DLL can not operate with this version of Winlogon.Winlogon (and the system) will not boot.
*/
BOOL WINAPI WlxNegotiate(DWORD dwWinlogonVersion, DWORD *pdwDllVersion)
{
pDEBUG(L"WlxNegotiate(%d (0x%08x), ...)", dwWinlogonVersion, dwWinlogonVersion);
// We support all versions from 1.3 up
if(dwWinlogonVersion < WLX_VERSION_1_3)
return FALSE;
// We'll support what winlogon does
*pdwDllVersion = dwWinlogonVersion;
// Record winlogon version
pGina::GINA::WinlogonInterface::Version(dwWinlogonVersion);
return true;
}
/**
Winlogon calls this function once for each window station present on the machine. (Note that
Windows NT 3.5 supports only one window station. This window station is called "Winsta0".
Additional physical window stations may be supported in futurereleases.) This allows the DLL to
initialize itself, including obtainingaddresses of Winlogon support functions used by this DLL.
The DLL can return a context pointer that will be passed in allfuture interactions from Winlogon to
GINA. This allows GINA to keep global context associated with this window station.
We've added the calls necessary to ensure the theme service is started and working before we go any
further, as explained in http://support.microsoft.com/default.aspx?scid=kb;en-us;322047
@param lpWinsta Points to the name of the window station being initialized.
@param hWlx Handle to Winlogon that must be provided in future calls related tothis window station.
@param pwReserved Reserved
@param pWinlogonFunctions Receives a pointer to a Winlogon function dispatch table. Thecontents of the table is dependent upon
the GINA DLL version returned from the WlxNegotiate() call. The table does not change, so the
GINA DLL can reference the table rather than copying it.
@param pWlxContext This is an OUT parameter. It allows GINA to return a 32bit context value that will be provided in all
future calls related to this window station. Generally the value returned will be something likea
pointer to a context structure allocated by GINA for this window station.
<strong>Thread Desktop:</strong> Winlogon Desktop\n
<strong>Workstation:</strong> Locked\n
@return True - Indicates the Gina DLL successfully initialized.\n
False - Indicates the Gina could not successfully initialize.\n
<i>Note that If the DLL could not initialize, then the system will not boot.<i>
*/
BOOL WINAPI WlxInitialize(LPWSTR lpWinsta, HANDLE hWlx, PVOID pvReserved, PVOID pWinlogonFunctions, PVOID * pWlxContext)
{
pDEBUG(L"WlxInitialize(%s, 0x%08x, 0x%08x, 0x%08x, ...)", lpWinsta, hWlx, pvReserved, pWinlogonFunctions);
pGina::GINA::Themes::Init();
return (pGina::GINA::Gina::InitializeFactory(hWlx, pWinlogonFunctions, (pGina::GINA::Gina **) pWlxContext) ? TRUE : FALSE);
}
/**
Winlogon calls this function when there is no one logged on.
@param pWlxContext (IN parameter) Context value associated with this window station that GINA returned in the
WlxInitialize() call.
<strong>Thread Desktop:</strong> Winlogon Desktop\n
<strong>Workstation:</strong> Locked\n
@return None
*/
VOID WINAPI WlxDisplaySASNotice(PVOID pWlxContext)
{
pDEBUG(L"WlxDisplaySASNotice");
pGINA_FROM_CTX(pWlxContext);
pGina->DisplaySASNotice();
}
/**
Winlogon calls this function when an SAS event is received and noone is logged on. This indicates
that a logon attempt should be made.
@param pWlxContext (IN parameter) Context value associated with this window station that GINA returned in the
WlxInitialize() call.
@param dwSasType (IN parameter) A value indicating what type of secure attentionsequence was entered. Values below
WLX_SAS_TYPE_MAX_MSFT_VALUE are used to define Microsoft standard secure attention
sequences. Values above this value are for definition by GINA developers.
@param pAuthenticationId (IN parameter) The AuthenticationID associated with this logon.The GINA DLL should pass this
value as the LogonId parameter to the LsaLogonUser() call. The pointer is good only until this
routine returns. To keep the LUID value longer than that, the GINA DLL should copy it before
returning.
@param pLogonSid (IN parameter) This parameter contains a pointer to a SID. This sid is unique to this logon session.
Winlogon uses this SID to change the protection on the window station and application desktop so
that the newly logged on user can access them. To ensure proper user shell access to these objects,
the GINA DLL should include this SID in theLocalGroups parameter passed to LsaLogonUser().
Winlogon frees this SID upon return from thiscall, so if it is required by GINA after returning, a copy
must be made in this routine.
@param pdwOptions (OUT parameter) Receives a set of logon options. These options are defined by the manifest
constants named WLX_LOGON_OPT_xxx.
@param phToken (OUT parameter) Upon completion of a successful logon,receives a handle that must be filled in
upon return if a logon was successfully performed. This handle value is typically receivedfrom
LsaLogonUser(). Winlogon closes this handle when it isdone with it, so if the GINA DLL should be
able to access the token, it should make a duplicate of this handle.
@param pMprNotifyInfo (OUT parameter) This parameter contains a pointer to a structure for returning password information
to other network providers. A GINA is not required to return this information. If a GINA returns
password information, then it should fill in the pointers inthe structure. Any NULL field in the
structure will be ignored byWinlogon. The strings should be allocated individually by theGINA, and
they will be freed by Winlogon.
@param pProfile (OUT parameter) Upon return from a successful authentication, this field must point to one of the
WLX_PROFILE_xxx structures. The first DWORD in the profile structure is used to indicate which
of the WLX_PROFILE_xxx structures is beingreturned. The information in this structure is used by
Winlogon to load the logged on user's profile. This structure, and any strings orbuffers pointed to
from withing this structure are freed byWinlogon when no longer needed.
<strong>Thread Desktop:</strong> Winlogon Desktop\n
<strong>Workstation:</strong> Locked\n
@return WLX_SAS_ACTION_LOGON - A user has logged on.\n
WLX_SAS_ACTION_NONE - A logon attempt was unsuccessful or cancelled.\n
WLX_SAS_ACTION_SHUTDOWN - The user requested the system be shut down.\n
WLX_SAS_ACTION_SHUTDOWN_REBOOT - The user requested the system be rebooted.\n
WLX_SAS_ACTION_SHUTDOWN_POWER_OFF - The user requested that the system be turned off\n
*/
int WINAPI WlxLoggedOutSAS(PVOID pWlxContext, DWORD dwSasType, PLUID pAuthenticationId, PSID pLogonSid,
PDWORD pdwOptions, PHANDLE phToken, PWLX_MPR_NOTIFY_INFO pMprNotifyInfo, PVOID *pProfile)
{
pDEBUG(L"WlxLoggedOutSAS");
pGINA_FROM_CTX(pWlxContext);
return pGina->LoggedOutSAS(dwSasType, pAuthenticationId, pLogonSid, pdwOptions, phToken, pMprNotifyInfo, pProfile);
}
/**
Winlogon calls this function following a successful logon. Itspurpose is to request GINA to activate
the user shell program(s). Note that the user shell should be activated in this routine ratherthan in
WlxLoggedOffSas() so that Winlogon has a chance to update its state, including setting workstation
and desktop protections, before any loggedon user processes are allowed to run. The pszDesktop parameter
should be passed to the CreateProcess API through the field lpDesktop in the STARTUPINFO structure. This
field is designated "Reserved forfuture use. Must be NULL." in the Win32 documentation, but pass this parameter in.
@param pWlxContext (IN parameter) Context value associated with this window station that GINA returned in the
WlxInitialize() call.
@param pszDesktopName (IN parameter) Name of the desktop on which to start the shell. This should be supplied to
CreateProcess() in the lpStartupInfo>lpDesktop field (q.v).
@param pszMprLogonScripts (IN parameter) Script names returned from the provider DLLs. Provider DLLs may return scripts to
be executed during logon. The GINA may reject these, but Winlogon will provide them ifthey are
there.
@param pEnvironment (IN parameter) Initial environment for the process. Winlogoncreates this environment and hands it
off to the GINA. The GINA can modify this environment before using it to initialize the user'sshell.
<strong>Thread Desktop:</strong> Application Desktop\n
<strong>Workstation:</strong> Not Locked\n
@return TRUE - Indicates that the shell processes were started by the GINA DLL.\n
FALSE - Indicates that the GINA could not start the shell, and that the logon session should be terminated by
Winlogon.
@Notes
*/
BOOL WINAPI WlxActivateUserShell(PVOID pWlxContext, PWSTR pszDesktopName, PWSTR pszMprLogonScript, PVOID pEnvironment)
{
pDEBUG(L"WlxActivateUserShell");
pGINA_FROM_CTX(pWlxContext);
return (pGina->ActivateUserShell(pszDesktopName, pszMprLogonScript, pEnvironment) ? TRUE : FALSE);
}
/**
Winlogon calls this function when an SAS event is received, andthere is a user logged on. This
indicates that the user needs to talk to the security system. Note, this is distinguished from when the
workstation is locked; see below.
This function is used generally when the logged on user wishes to shut down, log out, or lock the
workstation. The extension DLL can lock the workstation by returning WLX_LOCK_WKSTA.
Winlogon locks the workstation, and calls WlxWkstaLockedSAS the next time an SAS is received.
The extension DLL can use the profile to determine any information needed about the system.
@param pWlxContext (IN parameter) Context value associated with this window station that GINA returned in the
WlxInitialize() call.
@param dwSasType (IN parameter) A value indicating what type of secure attentionsequence was entered. Values below
WLX_SAS_TYPE_MAX_MSFT_VALUE are used to define Microsoft standard secure attention
sequences. Values above this value are for definition by GINA developers.
@param pReserved (IN parameter) Reserved.
<strong>Thread Desktop:</strong> Winlogon Desktop\n
<strong>Workstation:</strong> Locked\n
@return WLX_SAS_ACTION_NONE - Return to the default desktop.\n
WLX_SAS_ACTION_LOCK_WKSTA - Lock the workstation, wait for next SAS.\n
WLX_SAS_ACTION_LOGOFF - Log the user off of the workstation.\n
WLX_SAS_ACTION_SHUTDOWN - Log the user off and shutdown the machine.\n
WLX_SAS_ACTION_SHUTDOWN_REBOOT - Shut down and reboot the machine.\n
WLX_SAS_ACTION_SHUTDOWN_POWER_OFF - Shut down and turn off the machine, if hardware allows.
WLX_SAS_ACTION_PWD_CHANGED - Indicates that the user changed their password. Notify network providers.
WLX_SAS_ACTION_TASKLIST - Invoke the task list.
*/
int WINAPI WlxLoggedOnSAS(PVOID pWlxContext, DWORD dwSasType, PVOID pReserved)
{
pDEBUG(L"WlxLoggedOnSAS");
pGINA_FROM_CTX(pWlxContext);
return pGina->LoggedOnSAS(dwSasType, pReserved);
}
/**
Winlogon calls this function when the workstation is placed in thelocked state. This allows the GINA
to display information aboutthe lock, such as who locked the workstation and when. The GINA
should display a dialog box that will be interrupted by a WLX_WM_SAS message, much like the
WlxDisplaySASNotice function. This function should display a notice that describes the machine as locked.
@param pWlxContext (IN parameter) Context value associated with this window station that GINA returned in the
WlxInitialize() call.
@return None
*/
VOID WINAPI WlxDisplayLockedNotice(PVOID pWlxContext)
{
pDEBUG(L"WlxDisplayLockedNotice");
pGINA_FROM_CTX(pWlxContext);
pGina->DisplayLockedNotice();
}
/**
Winlogon calls this function before locking the workstation, if, forexample, a screen saver is marked
as secure.
@param pWlxContext IN parameter) Context value associated with this window station that GINA returned in the
wlxInitialize() call.
@return True - Indicates it is OK to lock the workstation.\n
False - Indicates it is not OK to lock the workstation.\n
*/
BOOL WINAPI WlxIsLockOk(PVOID pWlxContext)
{
pDEBUG(L"WlxIsLockOk");
pGINA_FROM_CTX(pWlxContext);
return (pGina->IsLockOk() ? TRUE : FALSE);
}
/**
Winlogon calls this function when it receives an SAS and theworkstation is locked. GINA may return
indicating the workstation is to remain locked, the workstation is to be unlocked, or the loggedon
user is being forced to log off (whichleaves the workstation locked until the logoff is completed).
@param pWlxContext (IN parameter) Context value associated with this window station that GINA returned in the
WlxInitialize() call.
@param dwSasType (IN parameter) A value indicating what type of secure attentionsequence was entered. Values below
WLX_SAS_TYPE_MAX_MSFT_VALUE are used to define Microsoft standard secure attention
sequences. Values above this value are for definition by GINA developers.
<strong>Thread Desktop:</strong> Winlogon Desktop\n
<strong>Workstation:</strong> Locked\n
@return WLX_SAS_ACTION_NONE - Workstation remains locked.\n
WLX_SAS_ACTION_UNLOCK_WKSTA - Unlock the workstation.\n
WLX_SAS_ACTION_FORCE_LOGOFF - Force the user to log off.\n
*/
int WINAPI WlxWkstaLockedSAS(PVOID pWlxContext, DWORD dwSasType)
{
pDEBUG(L"WlxWkstaLockedSAS");
pGINA_FROM_CTX(pWlxContext);
return pGina->WkstaLockedSAS(dwSasType);
}
/**
Winlogon calls this function when the user has initiated a logoff, foreaxmple by calling
ExitWindowsEx(). The GINA can determine whether the logoff attempt is to be allowed.
@param pWlxContext (IN parameter) Context value associated with this window station that GINA returned in the
WlxInitialize() call.
@return True - Indicates that it is OK to lock the workstation.\n
False - Indicates that it is not OK to lock the workstation.\n
*/
BOOL WINAPI WlxIsLogoffOk(PVOID pWlxContext)
{
pGINA_FROM_CTX(pWlxContext);
return (pGina->IsLogoffOk() ? TRUE : FALSE);
}
/**
Winlogon calls this function to notify GINA of a logoff on thisworkstation. No action is necessary.
@param pWlxContext (IN parameter) Context value associated with this window station that GINA returned in the
WlxInitialize() call.
<strong>Thread Desktop:</strong> Winlogon Desktop\n
<strong>Workstation:</strong> Locked\n
@return None.
*/
VOID WINAPI WlxLogoff(PVOID pWlxContext)
{
pGINA_FROM_CTX(pWlxContext);
pGina->Logoff();
}
/**
Winlogon calls this function right before shutdown so GINA canperform any shutdown tasks, such as
ejecting a smart card from a reader. The user has already logged off, and the WlxLogoff function has
been called.
@param pWlxContext (IN parameter) Context value associated with this window station that GINA returned in the
WlxInitialize() call.
@param ShutdownType (IN parameter) Type of shutdown, one of: WLX_SAS_ACTION_SHUTDOWN, WLX_SAS_ACTION_SHUTDOWN_REBOOT, or
WLX_SAS_ACTION_SHUTDOWN_POWER_OFF.
<strong>Thread Desktop:</strong> Application desktop if user logged on and the workstation isn't locked, otherwise Winlogon desktop.
<strong>Workstation:</strong> Not locked if application desktop, locked if Winlogon desktop.
*/
VOID WINAPI WlxShutdown(PVOID pWlxContext, DWORD ShutdownType)
{
pGINA_FROM_CTX(pWlxContext);
pGina->Shutdown(ShutdownType);
// As noted by <NAME> in his article, it turns out we can still get calls even after this is done,
// so we leak our Gina * class JIC. We're on our way out anyway, so this isn't a concern in the long term.
}
/**
The WlxScreenSaverNotify function may be implemented by a replacement GINA DLL. Winlogon calls this function immediately
before a screen saver is activated, allowing the GINA to interact with the screen saver program. Before calling WlxScreenSaverNotify,
Winlogon sets the desktop state so that the current desktop is the Winlogon desktop and sets the workstation state so that
the desktop is locked.
@param pWlxContext [in] Pointer to the GINA context associated with this window station. The GINA returns this context value when
Winlogon calls WlxInitialize for this station.
@param pSecure [in, out] Pointer to a Boolean value that, on input, specifies whether the current screen saver is secure and, on
output, indicates whether the workstation should be locked.
@return If the screen saver should be activated, the function returns TRUE.\n
If the screen saver should not be activated, the function returns FALSE.\n
*/
BOOL WINAPI WlxScreenSaverNotify(PVOID pWlxContext, BOOL * pSecure)
{
pGINA_FROM_CTX(pWlxContext);
return (pGina->ScreenSaverNotify(pSecure) ? TRUE: FALSE);
}
/**
The WlxStartApplication function can be implemented by a replacement GINA DLL. Winlogon calls this function when the system needs an
application to be started in the context of the user.
There are two reasons that the system might need an application to start in the context of the user:\n
1. Windows Explorer has quit unexpectedly and needs to be restarted.\n
2. The extended task manager needs to run.\n
The GINA can override this behavior, if appropriate, by using the WlxStartApplication function.
Before calling WlxStartApplication, Winlogon sets the desktop state so that the current desktop is the Winlogon desktop and sets the
workstation state so that the desktop is locked. If the WlxStartApplication function is not exported by the GINA, Winlogon will
execute the process.
@param pWlxContext [in] Pointer to the GINA context associated with this window station. The GINA returns this context value when Winlogon
calls WlxInitialize for this station.
@param pszDesktopName [in] Specifies the name of the desktop on which to start the application. Pass this string to the CreateProcess or
CreateProcessAsUser functions through the lpDesktop member of the STARTUPINFO structure.
@param pEnvironment [in] Specifies the initial environment for the process. Winlogon creates this environment and hands it off to the GINA.
The GINA can modify this environment before using it to initialize the shell of the user. The GINA is responsible for calling the VirtualFree
function to free the memory allocated for pEnvironment.
@param pszCmdLine [in] Program to execute.
@return If the function successfully starts the application, the function returns TRUE.\n
If the function fails or the application did not start, the function returns FALSE.
*/
BOOL WINAPI WlxStartApplication(PVOID pWlxContext, PWSTR pszDesktopName, PVOID pEnvironment, PWSTR pszCmdLine)
{
pGINA_FROM_CTX(pWlxContext);
return (pGina->StartApplication(pszDesktopName, pEnvironment, pszCmdLine) ? TRUE : FALSE);
}
/**
The WlxNetworkProviderLoad function must be implemented by a replacement GINA DLL. Winlogon calls this function to collect valid authentication
and identification information.
The GINA is not required to return password information. Any NULL fields within the structure will be ignored by Winlogon. Use LocalAlloc
to allocate each string; Winlogon will free them when they are no longer needed.
@param pWlxContext [in] Pointer to the GINA context associated with this window station. The GINA returns this context value when Winlogon calls
WlxInitialize for this station.
@param pNprNotifyInfo [out] Points to an WLX_MPR_NOTIFY_INFO structure that contains domain, user name, and password information for the user.
Winlogon will use this information to provide identification and authentication information to network providers.
@return TRUE - Return TRUE if the user was authenticated. \n
FALSE Return FALSE if the user was not authenticated.\n
*/
BOOL WINAPI WlxNetworkProviderLoad(PVOID pWlxContext, PWLX_MPR_NOTIFY_INFO pNprNotifyInfo)
{
pGINA_FROM_CTX(pWlxContext);
return (pGina->NetworkProviderLoad(pNprNotifyInfo) ? TRUE : FALSE);
}
/**
The WlxDisplayStatusMessage function must be implemented by a replacement GINA DLL. Winlogon calls this function when the GINA DLL
should display a message.
@param pWlxContext [in] Pointer to the GINA context associated with this window station. The GINA returns this context value when
Winlogon calls WlxInitialize for this station.
@param hDesktop [in] Handle to the desktop where the status message should be displayed.
@param dwOptions [in] Specifies display options for the status dialog box. The following options are valid: \n
STATUSMSG_OPTION_NOANIMATION\n
STATUSMSG_OPTION_SETFOREGROUND\n
@param pTitle [in] Pointer to a null-terminated wide character string that specifies the title of the message to be displayed.
@param pMessage [in] Pointer to a null-terminated wide character string that specifies the message to be displayed.
@return TRUE - Returns TRUE if the message was displayed. \n
FALSE - Returns FALSE if the message was not displayed. \n
*/
BOOL WINAPI WlxDisplayStatusMessage(PVOID pWlxContext, HDESK hDesktop, DWORD dwOptions, PWSTR pTitle, PWSTR pMessage)
{
pGINA_FROM_CTX(pWlxContext);
return (pGina->DisplayStatusMessage(hDesktop, dwOptions, pTitle, pMessage) ? TRUE : FALSE);
}
/**
The WlxGetStatusMessage function must be implemented by a replacement GINA DLL. Winlogon calls this function to get the status
message being displayed by the GINA DLL.
@param pWlxContext [in] Pointer to the GINA context associated with this window station. The GINA returns this context value
when Winlogon calls WlxInitialize for this station.
@param pdwOptions [out] Pointer to a DWORD that will hold the display options for the current status message.
@param pMessage [out] Returns the current status message text.
@param dwBufferSize [in] Size of the pMessage buffer.
@return TRUE - Returns TRUE if the message was retrieved. \n
FALSE - Returns FALSE if the message was not retrieved. \n
*/
BOOL WINAPI WlxGetStatusMessage(PVOID pWlxContext, DWORD * pdwOptions, PWSTR pMessage, DWORD dwBufferSize)
{
pGINA_FROM_CTX(pWlxContext);
return (pGina->GetStatusMessage(pdwOptions, pMessage, dwBufferSize) ? TRUE : FALSE);
}
/**
The WlxRemoveStatusMessage function must be implemented by a replacement GINA DLL. Winlogon calls this function to tell
the GINA DLL to stop displaying the status message.
@param pWlxContext [in] Pointer to the GINA context associated with this window station. The GINA returns this context
value when Winlogon calls WlxInitialize for this station.
@param TRUE - Return TRUE if the message was removed.\n
FALSE Return FALSE if the message was not removed.\n
*/
BOOL WINAPI WlxRemoveStatusMessage(PVOID pWlxContext)
{
pGINA_FROM_CTX(pWlxContext);
return (pGina->RemoveStatusMessage() ? TRUE : FALSE);
}
/**
TS session is being reconnected
*/
VOID WINAPI WlxReconnectNotify(PVOID pWlxContext)
{
pGINA_FROM_CTX(pWlxContext);
pGina->ReconnectNotify();
}
/**
TS session disconnect
*/
VOID WINAPI WlxDisconnectNotify(PVOID pWlxContext)
{
pGINA_FROM_CTX(pWlxContext);
pGina->DisconnectNotify();
}
/**
The WlxGetConsoleSwitchCredentials function must be implemented by a replacement GINA DLL. Winlogon calls this function to
read the currently logged on user's credentials to transparently transfer them to a target session.
@param pWlxContext [in] Pointer to a GINA-specific context.
@param pInfo [out] Pointer to a WLX_CONSOLESWITCH_CREDENTIALS_INFO_V1_0 to return GINA relevant information.
@return Returns TRUE on success and FALSE on failure.
*/
BOOL WINAPI WlxGetConsoleSwitchCredentials(PVOID pWlxContext, PVOID pCredInfo)
{
pGINA_FROM_CTX(pWlxContext);
return (pGina->GetConsoleSwitchCredentials(pCredInfo) ? TRUE : FALSE);
}
VOID WINAPI zDebugEntryPoint()
{
DWORD fakeDllVersion = 0;
WlxNegotiate(WLX_VERSION_1_4, &fakeDllVersion);
void * context = 0;
WlxInitialize(0, 0, 0, 0, &context);
WlxLoggedOutSAS(context, 1, NULL, NULL, 0, NULL, NULL, NULL);
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using pGina.Shared.Settings;
using pGina.Plugin.UsernameMod;
using pGina.Plugin.UsernameMod.Rules;
namespace pGina.Plugin.UsernameMod
{
public partial class Configuration : Form
{
ListOfRules rules;
public Configuration()
{
InitializeComponent();
//Setup the drop down box
actionBox.Items.AddRange(ListOfRules.Rules);
this.actionBox.SelectedIndex = 0;
//Get list of rules
try
{
rules = new ListOfRules();
rules.Load();
}
catch (UsernameModPluginException)
{
MessageBox.Show("Unable to load all rules from registry.");
}
updateListView();
resetForm();
}
/// <summary>
/// Run when the save button is hit. If an error is encountered due to improper input,
/// a prompt will be shown and the save/exit will be cancelled.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSave_Click(object sender, EventArgs e)
{
try
{
rules.Save();
}
catch (UsernameModPluginException ex)
{
MessageBox.Show("Unable to save settings.\n{0}", ex.Message);
return;
}
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
/// <summary>
/// Discards any changes without saving.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
/// <summary>
/// Executed when the Action drop down box (rule list) is changed.
/// Changes the forms.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dropDownActionChange(object sender, EventArgs e)
{
resetForm();
}
/// <summary>
/// Validates input and adds the rule to the ListOfRules.
/// Displays warning if validation fails.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAddRule_Click(object sender, EventArgs e)
{
Stage stage;
if (authButton.Checked)
stage = Stage.Authentication;
else if (authZButton.Checked)
stage = Stage.Authorization;
else if (gatewayButton.Checked)
stage = Stage.Gateway;
else
{
MessageBox.Show("Authentication, Authorization or Gateway button must be checked.");
return;
}
string action = (string)actionBox.SelectedItem;
string val1 = textBox1.Text;
string val2 = (textBox2.Enabled ? textBox2.Text : null);
try
{
IUsernameRule rule = ListOfRules.CreateRule(stage, action, val1, val2);
rules.Add(rule);
updateListView();
}
catch (UsernameModPluginException ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// If a rule is selected in the rule list, it is removed from the ListOfRules,
/// as well as ListView
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRemRule_Click(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection items = rulesListView.SelectedItems;
if (items.Count > 0)
{
ListViewItem lvi = items[0];
int index = lvi.Index;
rules.remove(index);
rulesListView.Items.RemoveAt(index);
}
}
/// <summary>
/// Called when either the up or down arrow is pressed. Determines which and updates
/// the ListOfRules and ListView accordingly.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnMove_Click(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection items = rulesListView.SelectedItems;
if (items.Count > 0)
{
ListViewItem lvi = items[0];
int oldIndex = lvi.Index;
if (sender == upButton && rules.MoveUp(lvi.Index))
{
string temp = lvi.Text;
lvi.Text = rulesListView.Items[oldIndex - 1].Text;
rulesListView.Items[oldIndex - 1].Text = temp;
rulesListView.Focus();
rulesListView.Items[oldIndex - 1].Selected = true;
}
else if (sender == downButton && rules.MoveDown(lvi.Index))
{
string temp = lvi.Text;
lvi.Text = rulesListView.Items[oldIndex + 1].Text;
rulesListView.Items[oldIndex + 1].Text = temp;
rulesListView.Focus();
rulesListView.Items[oldIndex + 1].Selected = true;
}
}
}
/// <summary>
/// Resets the forms based on the action dropdown box (list of rules)
/// </summary>
private void resetForm()
{
//Append, Prepend, Truncate, Replace, RegEx Replace, Match
switch ((string)actionBox.SelectedItem)
{
case "Append":
setForm("Append the following:", null);
break;
case "Prepend":
setForm("Prepend the following:", null);
break;
case "Truncate":
setForm("Number of characters allowed:", null);
break;
case "Replace":
setForm("Replace the following characters:", "With this string:");
break;
case "RegEx Replace":
setForm("Replace the regex expression:", "With this string:");
break;
case "Match":
setForm("Require the username to match:", null);
break;
}
}
private void setForm(string label1, string label2){
descLabel1.Text = label1;
textBox1.Text = "";
if (label2 != null)
{
descLabel2.Show();
textBox2.Show();
descLabel2.Text = label2;
textBox2.Text = "";
}
else
{
descLabel2.Hide();
textBox2.Hide();
}
}
/// <summary>
/// Clears and reloads the list of rules.
/// </summary>
private void updateListView()
{
rulesListView.Items.Clear();
foreach (IUsernameRule rule in rules.list)
{
ListViewItem lvi = new ListViewItem(rule.ToString());
rulesListView.Items.Add(lvi);
}
}
private void Btn_help(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/username_mod.html");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;
using log4net;
using Abstractions.WindowsApi;
namespace Service
{
public partial class HiddenForm : Form
{
private ILog m_logger = LogManager.GetLogger("pGina.Service.HiddenForm");
private pGina.Service.Impl.ServiceThread m_serviceThreadObj = null;
public HiddenForm(pGina.Service.Impl.ServiceThread serviceThreadObj)
{
m_serviceThreadObj = serviceThreadObj;
InitializeComponent();
}
private void HiddenForm_Load(object sender, EventArgs e)
{
if (!Abstractions.WindowsApi.pInvokes.WTSRegister(this.Handle))
{
m_logger.ErrorFormat("no session events are available");
}
}
private void HiddenForm_FormClosing(object sender, FormClosingEventArgs e)
{
Abstractions.WindowsApi.pInvokes.WTSUnRegister(this.Handle);
}
protected override void WndProc(ref Message m)
{
//m_logger.InfoFormat("WndProc " + m.Msg.ToString());
switch (m.Msg)
{
case (int)Abstractions.WindowsApi.pInvokes.structenums.WM.DEVICECHANGE:
//m_logger.InfoFormat("WM_DEVICECHANGE " + m.WParam.ToInt32());
/*switch (m.WParam.ToInt32())
{
case (int)Abstractions.WindowsApi.pInvokes.structenums.DBT.CONFIGCHANGECANCELED:
m_logger.InfoFormat("DBT_CONFIGCHANGECANCELED");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.DBT.CONFIGCHANGED:
m_logger.InfoFormat("DBT_CONFIGCHANGED");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.DBT.CUSTOMEVENT:
m_logger.InfoFormat("DBT_CUSTOMEVENT");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.DBT.DEVICEARRIVAL:
m_logger.InfoFormat("DBT_DEVICEARRIVAL");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.DBT.DEVICEQUERYREMOVE:
m_logger.InfoFormat("DBT_DEVICEQUERYREMOVE");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.DBT.DEVICEQUERYREMOVEFAILED:
m_logger.InfoFormat("DBT_DEVICEQUERYREMOVEFAILED");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.DBT.DEVICEREMOVECOMPLETE:
m_logger.InfoFormat("DBT_DEVICEREMOVECOMPLETE");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.DBT.DEVICEREMOVEPENDING:
m_logger.InfoFormat("DBT_DEVICEREMOVEPENDING");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.DBT.DEVICETYPESPECIFIC:
m_logger.InfoFormat("DBT_DEVICETYPESPECIFIC");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.DBT.DEVNODES_CHANGED:
m_logger.InfoFormat("DBT_DEVNODES_CHANGED");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.DBT.QUERYCHANGECONFIG:
m_logger.InfoFormat("DBT_QUERYCHANGECONFIG");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.DBT.USERDEFINED:
m_logger.InfoFormat("DBT_USERDEFINED");
break;
}*/
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.WM.POWERBROADCAST:
//m_logger.InfoFormat("WM_POWERBROADCAST " + m.WParam.ToInt32());
/*switch (m.WParam.ToInt32())
{
case (int)Abstractions.WindowsApi.pInvokes.structenums.PBT.APMRESUMEAUTOMATIC:
m_logger.InfoFormat("PBT_APMRESUMEAUTOMATIC");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.PBT.APMSUSPEND:
m_logger.InfoFormat("PBT_APMSUSPEND");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.PBT.APMRESUMESUSPEND:
m_logger.InfoFormat("PBT_APMRESUMESUSPEND");
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.PBT.APMRESUMECRITICAL:
m_logger.InfoFormat("PBT_APMRESUMECRITICAL");
break;
}*/
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.WM.WTSSESSION_CHANGE:
//m_logger.InfoFormat("WM_WTSSESSION_CHANGE " + m.WParam.ToInt32());
/*switch (m.WParam.ToInt32())
{
case (int)Abstractions.WindowsApi.pInvokes.structenums.WTS.CONSOLE_CONNECT:
m_logger.InfoFormat(String.Format("WTS_repl:{0}", m.LParam.ToInt32()));
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.WTS.CONSOLE_DISCONNECT:
m_logger.InfoFormat(String.Format("WTS_CONSOLE_DISCONNECT:{0}", m.LParam.ToInt32()));
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.WTS.REMOTE_CONNECT:
m_logger.InfoFormat(String.Format("WTS_REMOTE_CONNECT:{0}", m.LParam.ToInt32()));
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.WTS.REMOTE_DISCONNECT:
m_logger.InfoFormat(String.Format("WTS_REMOTE_DISCONNECT:{0}", m.LParam.ToInt32()));
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.WTS.SESSION_LOGON:
m_logger.InfoFormat(String.Format("WTS_SESSION_LOGON:{0}", m.LParam.ToInt32()));
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.WTS.SESSION_LOGOFF:
m_logger.InfoFormat(String.Format("WTS_SESSION_LOGOFF:{0}", m.LParam.ToInt32()));
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.WTS.SESSION_LOCK:
m_logger.InfoFormat(String.Format("WTS_SESSION_LOCK:{0}", m.LParam.ToInt32()));
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.WTS.SESSION_UNLOCK:
m_logger.InfoFormat(String.Format("WTS_SESSION_UNLOCK:{0}", m.LParam.ToInt32()));
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.WTS.SESSION_REMOTE_CONTROL:
m_logger.InfoFormat(String.Format("WTS_SESSION_REMOTE_CONTROL:{0}", m.LParam.ToInt32()));
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.WTS.SESSION_CREATE:
m_logger.InfoFormat(String.Format("WTS_SESSION_CREATE:{0}", m.LParam.ToInt32()));
break;
case (int)Abstractions.WindowsApi.pInvokes.structenums.WTS.SESSION_TERMINATE:
m_logger.InfoFormat(String.Format("WTS_SESSION_TERMINATE:{0}", m.LParam.ToInt32()));
break;
}*/
m_serviceThreadObj.SessionChange(m.LParam.ToInt32(), (SessionChangeReason)m.WParam.ToInt32());
break;
}
base.WndProc(ref m);
}
}
partial class HiddenForm
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.SuspendLayout();
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(0, 0);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "HiddenForm";
this.Text = "HiddenForm";
this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
this.Load += new System.EventHandler(this.HiddenForm_Load);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.HiddenForm_FormClosing);
this.ResumeLayout(false);
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using log4net;
using pGina.Shared.Interfaces;
namespace pGina.Core
{
public static class PluginLoader
{
private static string[] m_pluginDirectories = null;
private static List<IPluginBase> m_plugins = new List<IPluginBase>();
private static ILog m_logger = LogManager.GetLogger("PluginLoader");
public enum State
{
UIEnabled = 1,
AuthenticateEnabled = 1 << 1,
AuthorizeEnabled = 1 << 2,
GatewayEnabled = 1 << 3,
NotificationEnabled = 1 << 4,
ChangePasswordEnabled = 1 << 5,
}
public static string[] PluginDirectories
{
get { return m_pluginDirectories; }
set { m_pluginDirectories = value; }
}
public static void Init()
{
m_logger.DebugFormat("Initializing");
PluginDirectories = Core.Settings.Get.PluginDirectories;
// Set up an event handler to load plugin dependencies
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(ResolvePluginDependencies);
// Load the plugins themselves
PluginLoader.LoadPlugins();
m_logger.DebugFormat("Plugins loaded, list follows: ");
foreach (IPluginBase plugin in PluginLoader.AllPlugins)
{
m_logger.DebugFormat(" {0} -> {1}", plugin.Name, plugin.Uuid.ToString());
}
}
/// <summary>
/// This method is intended to help plugins load their dependencies. It is an event handler
/// that is triggered when an assembly is not found (resolved). It tries to load the
/// assembly from the same directory as the assembly that is requesting the dependency.
/// </summary>
/// <returns>The assembly or null if not found.</returns>
public static Assembly ResolvePluginDependencies(Object sender, ResolveEventArgs args)
{
// Get the file name
string[] fields = args.Name.Split(',');
string name = fields[0].Trim();
string culture = fields[2].Trim();
// Ignore requests for resources. These are "satellite assemblies" for
// localization, and this loader will not load them.
if (name.EndsWith(".resources") && !culture.EndsWith("neutral"))
return null;
string fileName = name + ".dll";
m_logger.DebugFormat("Resolving dependency {0}", fileName);
string requestorPath = null;
if (args.RequestingAssembly == null)
{
requestorPath = Assembly.GetExecutingAssembly().Location;
}
else
{
requestorPath = args.RequestingAssembly.Location;
if (string.IsNullOrEmpty(requestorPath))
{
requestorPath = args.RequestingAssembly.CodeBase;
// In certain cases (using SOAP references) this may be a URI
if (Uri.IsWellFormedUriString(requestorPath, UriKind.Absolute))
{
Uri requestorUri = new Uri(requestorPath);
if (requestorUri.IsFile)
{
requestorPath = requestorUri.LocalPath;
}
}
}
}
// If unable to find a good path to search
if (string.IsNullOrEmpty(requestorPath))
{
m_logger.ErrorFormat("Unable to find a reasonable search path for {0}, giving up.", fileName);
return null;
}
try
{
// Look for the assembly in the same directory as the plugin that is loading the assembly
DirectoryInfo dir = Directory.GetParent(requestorPath);
string path = Path.Combine(dir.FullName, fileName);
m_logger.DebugFormat("Looking for: {0}", path);
Assembly a = null;
if (dir.Exists)
{
if (File.Exists(path))
a = Assembly.LoadFile(path);
else
m_logger.DebugFormat("{0} not found", path);
}
if (a == null)
m_logger.ErrorFormat("Unable to resolve dependency: {0}", args.Name);
else
m_logger.InfoFormat("Successfully loaded assembly: {0}", a.FullName);
return a;
}
catch (Exception e)
{
m_logger.ErrorFormat("Error when loading dependency: {0}", e);
return null;
}
}
public static void LoadPlugins()
{
m_plugins.Clear();
foreach (string dir in m_pluginDirectories)
{
LoadPluginsFromDir(dir);
}
// All plugins default to completely disabled
foreach (IPluginBase plugin in m_plugins)
{
Settings.Get.SetDefault(plugin.Uuid.ToString(), 0);
}
}
private static void LoadPluginsFromDir(string dir)
{
if (!Directory.Exists(dir))
{
m_logger.WarnFormat("Skipping invalid plugin directory: {0}", dir);
return;
}
m_logger.DebugFormat("Loading plugins from {0}", dir);
string[] files = Directory.GetFiles(dir, "pGina.Plugin.*.dll");
foreach (string file in files)
{
try
{
// Load the assembly up
Assembly assembly = Assembly.LoadFile(file);
foreach (Type type in assembly.GetTypes())
{
// Make sure its a public class
if (!type.IsClass || type.IsNotPublic)
continue;
Type[] interfaces = type.GetInterfaces();
if (interfaces.Contains(typeof(IPluginBase)))
{
// TBD: We could do inverted control here.. logger, settings, etc?
// We could also consider loading plugins in their own app domain,
// making them unloadable...
object pluginObject = Activator.CreateInstance(type);
IPluginBase pluginBase = pluginObject as IPluginBase;
m_logger.DebugFormat("Created plugin object type: {0} from plugin: {1} uuid: {2}", type.ToString(), file, pluginBase.Uuid);
m_plugins.Add(pluginObject as IPluginBase);
}
}
}
catch (Exception ex)
{
m_logger.ErrorFormat("Error loading {0}: {1}", file, ex);
}
}
}
public static List<IPluginBase> AllPlugins
{
get { return m_plugins; }
}
/// <summary>
/// Returns stateful plugins that are enabled in at least one of the three
/// stages in the login chain.
/// </summary>
/// <returns></returns>
public static List<IStatefulPlugin> GetEnabledStatefulPlugins()
{
List<IStatefulPlugin> list = new List<IStatefulPlugin>();
foreach (IPluginBase plugin in m_plugins)
{
int pluginMask = Settings.Get.GetSetting(plugin.Uuid.ToString());
if ( plugin is IStatefulPlugin &&
(
IsEnabledFor<IPluginAuthentication>(pluginMask) ||
IsEnabledFor<IPluginAuthorization>(pluginMask) ||
IsEnabledFor<IPluginAuthenticationGateway>(pluginMask)
)
)
{
list.Add(plugin as IStatefulPlugin);
}
}
return list;
}
public static List<T> GetPluginsOfType<T>(bool enabledOnly) where T : class, IPluginBase
{
List<T> pluginList = new List<T>();
foreach (IPluginBase plugin in m_plugins)
{
if (plugin is T)
{
int pluginMask = Settings.Get.GetSetting(plugin.Uuid.ToString());
if(enabledOnly && !IsEnabledFor<T>(pluginMask))
continue;
pluginList.Add(plugin as T);
}
}
return pluginList;
}
private static bool TestMask(int mask, State state)
{
int stateMask = (int) state;
int val = stateMask & mask;
if (val != 0)
return true;
return false;
}
public static bool IsEnabledFor<T>(int mask) where T: IPluginBase
{
if (typeof(T) == typeof(IPluginAuthentication) && TestMask(mask, State.AuthenticateEnabled))
return true;
if (typeof(T) == typeof(IPluginAuthorization) && TestMask(mask, State.AuthorizeEnabled))
return true;
if (typeof(T) == typeof(IPluginAuthenticationGateway) && TestMask(mask, State.GatewayEnabled))
return true;
if (typeof(T) == typeof(IPluginEventNotifications) && TestMask(mask, State.NotificationEnabled))
return true;
if (typeof(T) == typeof(IPluginLogoffRequestAddTime) && TestMask(mask, State.NotificationEnabled))
return true;
if (typeof(T) == typeof(IPluginChangePassword) && TestMask(mask, State.ChangePasswordEnabled))
return true;
return false;
}
public static bool IsEnabledFor<T>(IPluginBase plugin) where T : IPluginBase
{
int pluginMask = Settings.Get.GetSetting(plugin.Uuid.ToString());
return IsEnabledFor<T>(pluginMask);
}
public static List<IPluginConfiguration> GetConfigurablePlugins()
{
return GetPluginsOfType<IPluginConfiguration>(false);
}
public static List<T> GetOrderedPluginsOfType<T>() where T : class, IPluginBase
{
List<T> loadedPlugins = GetPluginsOfType<T>(true);
// Now sort by order in settings
string setting = string.Format("{0}_Order", typeof(T).ToString().Replace("pGina.Shared.Interfaces.", ""));
string[] order = Settings.Get.GetSetting(setting, new string[] { });
List<T> orderedPlugins = new List<T>();
foreach (string uuid in order)
{
foreach (T p in loadedPlugins.Where(plugin => plugin.Uuid.ToString() == uuid))
{
orderedPlugins.Add(p);
}
}
// We now have all plugins listed from our order list, what about any remaining? lets pair down
// and look.
foreach (T p in orderedPlugins)
{
loadedPlugins.Remove(p);
}
// Any remaining plugins were loaded and enabled, so they go to the back of our list
// and then we update or list
if (loadedPlugins.Count > 0)
{
foreach (T p in loadedPlugins)
{
orderedPlugins.Add(p);
}
List<string> newOrder = new List<string>();
foreach (var p in orderedPlugins)
newOrder.Add(p.Uuid.ToString());
Settings.Get.SetSetting(setting, newOrder.ToArray());
}
return orderedPlugins;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include "DialogLoggedOutSAS.h"
#include "Dll.h"
#include <wchar.h>
#include <Macros.h>
// ID's for MSGINA's WlxLoggedOutSAS dialog
#define IDC_MSGINA_USERNAME 1502
#define IDC_MSGINA_PASSWORD <PASSWORD>
namespace pGina
{
namespace GINA
{
void DialogLoggedOutSAS::DialogInit()
{
if(!m_username.empty()) SetItemText(IDC_USERNAME_TXT, m_username.c_str());
if(!m_password.empty()) SetItemText(IDC_PASSWORD_TXT, m_password.c_str());
ApplyLogoImage();
SetFocusItem(IDC_USERNAME_TXT);
bool specialActionEnabled = pGina::Registry::GetBool(L"EnableSpecialActionButton", false);
if(specialActionEnabled)
{
EnableItem(IDC_SPECIAL);
SetItemText(IDC_SPECIAL, pGina::Registry::GetString(L"SpecialAction", L"Shutdown").c_str());
}
else
DisableItem(IDC_SPECIAL);
// Service status
//if( pGina::Registry::GetBool(L"ShowServiceStatusInLogonUi", true) )
//{
SetServiceStatus();
// Start a timer to update service status
m_statusTimerId = StartTimer(pGina::Registry::GetDword(L"PingSleepTime", 5000));
//}
//else
//{
// DisableItem(IDC_STATUS);
//}
// MOTD
if( pGina::Registry::GetBool(L"EnableMotd", true) )
{
std::wstring motd = pGina::Transactions::TileUi::GetDynamicLabel(L"MOTD");
SetItemText(IDC_MOTD, motd.c_str());
}
else
{
DisableItem(IDC_MOTD);
}
}
bool DialogLoggedOutSAS::Command(int itemId)
{
switch(itemId)
{
case IDCANCEL:
FinishWithResult(SAS_ACTION_NONE);
return true;
case IDC_LOGIN_BUTTON:
m_username = GetItemText(IDC_USERNAME_TXT);
m_password = GetItemText(IDC_PASSWORD_TXT);
FinishWithResult(SAS_ACTION_LOGON);
return true;
case IDC_SPECIAL:
{
std::wstring action = pGina::Registry::GetString(L"SpecialAction", L"Shutdown");
if(_wcsicmp(action.c_str(), L"Shutdown") == 0)
FinishWithResult(SAS_ACTION_SHUTDOWN_POWER_OFF);
else if(_wcsicmp(action.c_str(), L"Reboot") == 0)
FinishWithResult(SAS_ACTION_SHUTDOWN_REBOOT);
else if(_wcsicmp(action.c_str(), L"Sleep") == 0)
FinishWithResult(SAS_ACTION_SHUTDOWN_SLEEP);
else if(_wcsicmp(action.c_str(), L"Hibernate") == 0)
FinishWithResult(SAS_ACTION_SHUTDOWN_HIBERNATE);
}
return true;
}
return false;
}
void DialogLoggedOutSAS::SetServiceStatus()
{
if( pGina::Registry::GetBool(L"ShowServiceStatusInLogonUi", true) )
{
bool up = pGina::Transactions::Service::Ping();
if(up)
{
SetItemText(IDC_STATUS, L"Service Status: Connected");
}
else
{
SetItemText(IDC_STATUS, L"Service Status: Disconnected");
}
}
}
bool DialogLoggedOutSAS::Timer(int timerId)
{
if(timerId == m_statusTimerId)
{
SetServiceStatus();
return true;
}
return false;
}
INT_PTR DialogLoggedOutSAS::DialogProcImpl(UINT msg, WPARAM wparam, LPARAM lparam)
{
return FALSE;
}
void DialogLoggedOutSAS::ApplyLogoImage()
{
if(m_bitmap == NULL)
{
std::wstring tileImage = pGina::Registry::GetString(L"TileImage", L"");
if(tileImage.empty() || tileImage.length() == 1)
{
// Use builtin
m_bitmap = LoadBitmap(GetMyInstance(), MAKEINTRESOURCE(IDB_PGINA_LOGO));
}
else
{
pDEBUG(L"Credential::GetBitmapValue: Loading image from: %s", tileImage.c_str());
m_bitmap = (HBITMAP) LoadImageW((HINSTANCE) NULL, tileImage.c_str(), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
}
}
if(m_bitmap)
{
SetItemBitmap(IDC_LOGO, m_bitmap);
}
}
}
}<file_sep>How to compile dependent libs
Best to use a Windows 7 Virtual Machine!
.) Install VC 2010 as described here
http://mutonufoai.github.io/pgina/develop.html
.) Install NASM
http://www.nasm.us/
.) Install Active Perl
add perl into the path variable
http://www.activestate.com/activeperl/downloads
.) Install cmake
add cmake into the path variable
https://cmake.org/download/
.) create a folder and
.) extract libssh2 into it
https://www.libssh2.org/download/
.) extract zlib into it
http://www.zlib.net/
remove ZLIB_WINAPI from PreprocessorDefinitions in contrib\vstudio\vc10\zlibstat.vcxproj
(needed to build win32)
.) extract openssl into it
https://www.openssl.org/source/
.) copy dependency_compile.cmd into it
.) open Visual Studio Command Promp for a 32 bit build
.) drag and drop dependency_compile.cmd into it and hit enter
.) open Visual Studio Command Promp for a 64 bit build
.) drag and drop dependency_compile.cmd into it and hit enter
Then you'll find a x86 and x64 folder with all the libs you need. <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Abstractions.Logging;
using System.Net;
using System.Net.Sockets;
using System.Net.Mail;
using System.Diagnostics;
using System.IO;
using log4net;
using log4net.Appender;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
namespace Abstractions.Windows
{
public static class Networking
{
/// <summary>
/// get UTC ntp time
/// based on http://stackoverflow.com/questions/1193955/how-to-query-an-ntp-server-using-c
/// </summary>
/// <param name="FQDN">server address</param>
/// <returns>DateTime, on error DateTime.MinValue</returns>
public static DateTime GetNetworkTime(string[] FQDN)
{
DateTime RetVal = DateTime.MinValue;
//time server
for (uint x = 0; x < FQDN.Length; x++)
{
// NTP message size - 16 bytes of the digest (RFC 2030)
Byte[] ntpData = new byte[48];
//Setting the Leap Indicator, Version Number and Mode values
ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
try
{
IPAddress[] addresses = Dns.GetHostEntry(FQDN[x]).AddressList;
//The UDP port number assigned to NTP is 123
IPEndPoint ipEndPoint = new IPEndPoint(addresses[0], 123);
//NTP uses UDP
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.ReceiveTimeout = 3 * 1000;
socket.SendTimeout = 3 * 1000;
socket.Connect(ipEndPoint);
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
//Offset to get to the "Transmit Timestamp" field (time at which the reply
//departed the server for the client, in 64-bit timestamp format."
const byte serverReplyTime = 40;
//Get the seconds part
UInt64 intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
//Get the seconds fraction
UInt64 fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
//Convert From big-endian to little-endian
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
UInt64 milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
//**UTC** time
RetVal = (new DateTime(1900, 1, 1)).AddMilliseconds((Int64)milliseconds);
break;
}
catch (Exception ex)
{
LibraryLogging.Error("get ntp {0} error:{1}", FQDN[x], ex);
}
}
return RetVal;
}
// stackoverflow.com/a/3294698/162671
internal static UInt32 SwapEndianness(UInt64 x)
{
return (UInt32)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
/// <summary>
/// does send a mail including the last 60 system-Event and application-Event lines
/// plus the last 175 pgina logfile lines
/// </summary>
/// <param name="mailAddress"></param>
/// <param name="smtpAddress"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
/// <param name="ssl"></param>
/// <returns></returns>
public static Boolean email(string[] mailAddress, string[] smtpAddress, string username, string password, string subject, string body, bool ssl)
{
Boolean ret = false;
#region input checks
if (mailAddress.Length == 0)
{
LibraryLogging.Error("can't send email: mailAddress.Length == 0");
return false;
}
else
{
bool atleastonemail = false;
foreach (string str in mailAddress)
{
if (!String.IsNullOrEmpty(str))
{
atleastonemail = true;
break;
}
}
if (!atleastonemail)
{
LibraryLogging.Error("can't send email: mailAddress array is empty");
return false;
}
}
if (smtpAddress.Length == 0)
{
LibraryLogging.Error("can't send email: smtpAddress.Length == 0");
return false;
}
else
{
bool atleastoneserver = false;
foreach (string str in smtpAddress)
{
if (!String.IsNullOrEmpty(str))
{
atleastoneserver = true;
break;
}
}
if (!atleastoneserver)
{
LibraryLogging.Error("can't send email: smtpAddress array is empty");
return false;
}
}
if (String.IsNullOrEmpty(subject))
{
LibraryLogging.Error("can't send email: subject is empty");
}
#endregion
try
{
using (EventLog systemLog = new EventLog("System"))
{
body += "\n\n====================Eventlog System====================\n";
for (int x = systemLog.Entries.Count - 60; x < systemLog.Entries.Count; x++)
{
body += String.Format("{0:yyyy-MM-dd HH:mm:ss} {1} {2} {3}\n", systemLog.Entries[x].TimeGenerated, systemLog.Entries[x].EntryType, (UInt16)systemLog.Entries[x].InstanceId, systemLog.Entries[x].Message);
}
}
using (EventLog application = new EventLog("Application"))
{
body += "\n\n====================Eventlog Application===============\n";
for (int x = application.Entries.Count - 60; x < application.Entries.Count; x++)
{
body += String.Format("{0:yyyy-MM-dd HH:mm:ss} {1} {2} {3}\n", application.Entries[x].TimeGenerated, application.Entries[x].EntryType, (UInt16)application.Entries[x].InstanceId, application.Entries[x].Message);
}
}
}
catch { }
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
for (uint x = 0; x < smtpAddress.Length; x++)
{
string smtp = smtpAddress[x].Split(new char[] { ':' }).First();
int port = 465;
if (String.Compare(smtp, smtpAddress[x].Split(new char[] { ':' }).Last()) != 0)
{
try
{
port = Convert.ToInt32(smtpAddress[x].Split(new char[] { ':' }).Last());
}
catch (Exception ex)
{
LibraryLogging.Warn("unable to retrieve smtp port from {0} Error:{1}", smtpAddress[x], ex.Message);
continue;
}
}
using (SmtpClient client = new SmtpClient(smtp, port))
{
client.EnableSsl = ssl;
client.Timeout = Convert.ToInt32(new TimeSpan(0, 0, 30).TotalMilliseconds);
if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
{
client.Credentials = new NetworkCredential(username, password);
}
for (uint y = 0; y < mailAddress.Length; y++)
{
if (mailAddress[y] == null)
continue;
try
{
// get the logfile
string logfile = null;
logfile = LogManager.GetRepository().GetAppenders().OfType<FileAppender>().Where(fa => fa.Name == "bigfile").Single().File;
if (!String.IsNullOrEmpty(logfile))
{
using (StreamReader log = new StreamReader(logfile, true))
{
// read the last 50kbytes of the log
if (log.BaseStream.Length > 50 * 1024) //50kbytes
log.BaseStream.Seek(50 * 1024 * -1, SeekOrigin.End);
string[] lastlines = log.ReadToEnd().Split('\n');
int line_count = 0;
if (lastlines.Length > 175)
line_count = lastlines.Length - 176;
body += "\n\n====================Pgina log==========================\n";
for (; line_count < lastlines.Length; line_count++)
{
body += lastlines[line_count] + '\n';
}
}
}
using (MailMessage message = new MailMessage(mailAddress[y], mailAddress[y], subject, body))
{
client.Send(message);
}
mailAddress[y] = null;
}
catch (Exception ex)
{
LibraryLogging.Warn("Failed to send message \"{0}\" to:{1} port:{2} Error:{3}", subject, smtp, port, ex.Message);
}
}
}
if (mailAddress.All(k => string.IsNullOrEmpty(k)))
{
ret = true;
break;
}
}
return ret;
}
public static Boolean sendMail(Dictionary<string, string> settings, string username, string password, string subject, string body)
{
string mailAddress = settings["notify_email"];
string smtpAddress = settings["notify_smtp"];
string user = settings["notify_user"];
string pass = settings["notify_pass"];
bool ssl = Convert.ToBoolean(settings["notify_cred"]);
bool cred = Convert.ToBoolean(settings["notify_ssl"]);
if (cred)
{
// use login credential first
if (!Abstractions.Windows.Networking.email(mailAddress.Split(' '), smtpAddress.Split(' '), username, password, subject, body, ssl))
{
if (Abstractions.Windows.Networking.email(mailAddress.Split(' '), smtpAddress.Split(' '), user, pass, subject, body, ssl))
{
return true;
}
}
else
{
return true;
}
}
else
{
if (Abstractions.Windows.Networking.email(mailAddress.Split(' '), smtpAddress.Split(' '), user, pass, subject, body, ssl))
{
return true;
}
}
return false;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include "pGinaMessages.h"
namespace pGina
{
namespace Protocol
{
MessageBase * SendRecvPipeMessage(pGina::NamedPipes::PipeClient &client, MessageBase &msg)
{
return SendRecvPipeMessage(client, &msg);
}
MessageBase * SendRecvPipeMessage(pGina::NamedPipes::PipeClient &client, MessageBase *msg)
{
MessageBase * reply = 0;
pGina::Messaging::Message * dynamicMsg = msg->ToDynamicMessage();
pGina::Memory::Buffer * msgBuffer = pGina::Messaging::Message::Marshal(dynamicMsg);
if(client.WriteLengthEncodedBuffer(msgBuffer))
{
pGina::Memory::Buffer * replyBuffer = client.ReadLengthEncodedBuffer();
if(replyBuffer)
{
pGina::Messaging::Message * replyMsg = pGina::Messaging::Message::Demarshal(replyBuffer);
if(replyMsg->Exists<unsigned char>(L"MessageType"))
{
MessageType type = (MessageType) replyMsg->Property<unsigned char>(L"MessageType");
switch(type)
{
case Hello:
reply = (MessageBase *) (new HelloMessage());
break;
case Disconnect:
reply = (MessageBase *) (new DisconnectMessage());
break;
case Ack:
reply = (MessageBase *) (new AckMessage());
break;
case Log:
reply = (MessageBase *) (new LogMessage());
break;
case LoginRequest:
reply = (MessageBase *) (new LoginRequestMessage());
break;
case LoginResponse:
reply = (MessageBase *) (new LoginResponseMessage());
break;
case DynLabelRequest:
reply = (MessageBase *) (new DynamicLabelRequestMessage());
break;
case DynLabelResponse:
reply = (MessageBase *) (new DynamicLabelResponseMessage());
break;
case UserInfoRequest:
reply = (MessageBase *) (new UserInformationRequestMessage());
break;
case UserInfoResponse:
reply = (MessageBase *) (new UserInformationResponseMessage());
break;
case ChangePasswordRequest:
reply = (MessageBase *) (new ChangePasswordRequestMessage());
break;
case ChangePasswordResponse:
reply = (MessageBase *) (new ChangePasswordResponseMessage());
break;
}
}
if(reply)
{
// Decode any further data needed
reply->FromDynamicMessage(replyMsg);
}
delete replyMsg;
delete replyBuffer;
}
}
delete msgBuffer;
delete dynamicMsg;
return reply;
}
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Dynamic;
namespace Abstractions.Pipes
{
public static class PipeMessage
{
// Every messages starts with a single byte version marker, which can be used
// to facilitate support for older clients if needed. This value indicates
// the most recent version supported by this library.
public const byte CurrentMessageFormatVersion = 0x01;
private enum DataType
{
Byte = 0x00,
Integer = 0x01,
Boolean = 0x02,
String = 0x03,
EmptyString = 0x04,
}
public static IDictionary<string, object> Demarshal(byte[] data)
{
// Cannot be empty
if (data.Length == 0)
throw new InvalidDataException(string.Format("Empty message provided, invalid format."));
using (BinaryReader br = new BinaryReader(new MemoryStream(data, false), Encoding.Unicode))
{
// For now we support only the one message version
byte messageFormatVersion = br.ReadByte();
if (messageFormatVersion != CurrentMessageFormatVersion)
throw new InvalidDataException(string.Format("Message format: {0} is not support (library version: {1})", messageFormatVersion, CurrentMessageFormatVersion));
// Create a dict for the message contents
Dictionary<string, object> messageDict = new Dictionary<string, object>();
while (br.BaseStream.Position < br.BaseStream.Length)
{
string propertyName = br.ReadString();
DataType propertyType = (DataType)br.ReadByte();
switch (propertyType)
{
case DataType.Boolean:
messageDict.Add(propertyName, br.ReadBoolean());
break;
case DataType.Byte:
messageDict.Add(propertyName, br.ReadByte());
break;
case DataType.Integer:
messageDict.Add(propertyName, br.ReadInt32());
break;
case DataType.String:
messageDict.Add(propertyName, br.ReadString());
break;
case DataType.EmptyString:
messageDict.Add(propertyName, (string) null);
break;
default:
throw new InvalidDataException(string.Format("Message includes unknown data type: {0} for property: {1}", propertyType, propertyName));
}
}
return messageDict;
}
}
public static byte[] Marshal(IDictionary<string, object> message)
{
using (MemoryStream memory = new MemoryStream())
{
BinaryWriter writer = new BinaryWriter(memory, Encoding.Unicode);
// Write the version
writer.Write(CurrentMessageFormatVersion);
// Now we just iterate properties and write them out
foreach (KeyValuePair<string, object> property in message)
{
writer.Write(property.Key);
// Null values are treated as empty strings
if (property.Value == null)
{
writer.Write((byte)DataType.EmptyString);
continue;
}
System.Type propType = property.Value.GetType();
if (propType == typeof(int))
{
writer.Write((byte) DataType.Integer);
writer.Write((int)property.Value);
}
else if (propType == typeof(byte))
{
writer.Write((byte)DataType.Byte);
writer.Write((byte)property.Value);
}
else if (propType == typeof(bool))
{
writer.Write((byte)DataType.Boolean);
writer.Write((bool)property.Value);
}
else if(propType == typeof(Enum))
{
writer.Write((byte)DataType.Byte);
writer.Write((byte)property.Value);
}
else
{
// Not one of the former, you're string value it is then!
writer.Write((byte)DataType.String);
writer.Write(property.Value.ToString());
}
}
// Provide our caller a copy in byte[] format
return memory.ToArray();
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using Microsoft.Win32;
using Abstractions.WindowsApi;
using Abstractions.Logging;
namespace Abstractions.Windows
{
public static class User
{
const string ROOT_PROFILE_KEY = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList";
/// <summary>
/// returns profiledir based on regkey
/// </summary>
/// <param name="sid"></param>
/// <returns></returns>
public static List<string> GetProfileDir(SecurityIdentifier sid)
{
List<string> ret = new List<string>();
//"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\S-1-5-21-534125731-1308685933-1530606844-1000}"
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(ROOT_PROFILE_KEY))
{
if (key != null)
{
foreach (string keyName in key.GetSubKeyNames())
{
if (keyName.Contains(sid.ToString())) //get the %SID% and %SID%.bak key
{
using(RegistryKey subKey = Registry.LocalMachine.OpenSubKey(string.Format("{0}\\{1}", ROOT_PROFILE_KEY, keyName)))
{
LibraryLogging.Info("ProfileList key found {0}", keyName);
ret.Add(subKey.GetValue("ProfileImagePath", "", RegistryValueOptions.None).ToString());
}
}
}
}
else
{
LibraryLogging.Info("GetProfileDir key {0} not found", ROOT_PROFILE_KEY);
}
}
return ret;
}
internal enum Profile_State
{
Profile_is_mandatory = 0x0001,
Update_the_locally_cached_profile = 0x0002,
New_local_profile = 0x0004,
New_central_profile = 0x0008,
Update_the_central_profile = 0x0010,
Delete_the_cached_profile = 0x0020,
Upgrade_the_profile = 0x0040,
Using_Guest_user_profile = 0x0080,
Using_Administrator_profile = 0x0100,
Default_net_profile_is_available_and_ready = 0x0200,
Slow_network_link_identified = 0x0400,
Temporary_profile_loaded = 0x0800,
}
/// <summary>
/// return true if profile is temp. uses ProfileList State regkey
/// </summary>
/// <param name="sid"></param>
/// <returns></returns>
public static bool? IsProfileTemp(string sid)
{
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(string.Format("{0}\\{1}", ROOT_PROFILE_KEY, sid)))
{
if (key != null)
{
object type = key.GetValue("State");
Profile_State value = 0;
switch (key.GetValueKind("State"))
{
case RegistryValueKind.DWord:
value = (Profile_State)type;
break;
case RegistryValueKind.QWord:
value = (Profile_State)type;
break;
}
if (value.HasFlag(Profile_State.Temporary_profile_loaded))
{
return true;
}
}
else
{
LibraryLogging.Info("IsProfileTemp key {0}\\{1} not found", ROOT_PROFILE_KEY, sid);
return null;
}
}
}
catch (Exception ex)
{
LibraryLogging.Info("IsProfileTemp exception:{0}", ex.Message);
return null;
}
return false;
}
/// <summary>
/// if a user receives a temp profile of whatever reason
/// MS is renaming the SID key under ProfileList to SID.bak
/// if so winapi calls will fail and not returning anything
/// </summary>
/// <param name="userSID"></param>
/// <returns></returns>
public static Boolean FixProfileList(string userSID)
{
string regkey = ROOT_PROFILE_KEY + "\\" + userSID;
UIntPtr key = UIntPtr.Zero;
UIntPtr key_bak = UIntPtr.Zero;
Boolean ret = false;
key = Abstractions.WindowsApi.pInvokes.RegistryOpenKey(Abstractions.WindowsApi.pInvokes.structenums.baseKey.HKEY_LOCAL_MACHINE, regkey);
if (key == UIntPtr.Zero)
{
key_bak = Abstractions.WindowsApi.pInvokes.RegistryOpenKey(Abstractions.WindowsApi.pInvokes.structenums.baseKey.HKEY_LOCAL_MACHINE, regkey + ".bak");
if (key_bak != UIntPtr.Zero)
{
key = Abstractions.WindowsApi.pInvokes.RegistryCreateKey(Abstractions.WindowsApi.pInvokes.structenums.baseKey.HKEY_LOCAL_MACHINE, regkey);
if (key != UIntPtr.Zero)
{
ret = Abstractions.WindowsApi.pInvokes.RegistryCopyKey(key_bak, null, key);
if (ret)
{
if (Abstractions.WindowsApi.pInvokes.RegistryCloseKey(key_bak))
{
Abstractions.WindowsApi.pInvokes.RegistryDeleteTree(Abstractions.WindowsApi.pInvokes.structenums.baseKey.HKEY_LOCAL_MACHINE, regkey + ".bak");
}
}
}
}
else
{
ret = true;
}
}
else
{
ret = true;
}
if (key_bak != UIntPtr.Zero)
{
Abstractions.WindowsApi.pInvokes.RegistryCloseKey(key_bak);
}
if (key != UIntPtr.Zero)
{
Abstractions.WindowsApi.pInvokes.RegistryCloseKey(key);
}
return ret;
}
/// <summary>
/// Delete ProfileList regkeys
/// </summary>
/// <param name="userSID"></param>
/// <returns></returns>
public static Boolean DelProfileList(string userSID)
{
List<string> regkeys = new List<string>(){
ROOT_PROFILE_KEY + "\\" + userSID,
ROOT_PROFILE_KEY + "\\" + userSID + ".bak"
};
UIntPtr key = UIntPtr.Zero;
Boolean ret = true;
foreach (string regkey in regkeys)
{
key = Abstractions.WindowsApi.pInvokes.RegistryOpenKey(Abstractions.WindowsApi.pInvokes.structenums.baseKey.HKEY_LOCAL_MACHINE, regkey);
if (key != UIntPtr.Zero)
{
bool r = Abstractions.WindowsApi.pInvokes.RegistryDeleteTree(Abstractions.WindowsApi.pInvokes.structenums.baseKey.HKEY_LOCAL_MACHINE, regkey);
if (ret != false)
{
ret = r;
}
Abstractions.WindowsApi.pInvokes.RegistryCloseKey(key);
}
}
return ret;
}
/// <summary>
/// returns user profile direrctory
/// empty string on error
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="sid"></param>
/// <returns></returns>
public static string GetProfileDir(string username, string password, SecurityIdentifier sid)
{
IntPtr hToken = Abstractions.WindowsApi.pInvokes.GetUserToken(username, "", password);
string ret = "";
if (hToken != IntPtr.Zero)
{
ret = Abstractions.WindowsApi.pInvokes.GetUserProfileDir(hToken);
Abstractions.WindowsApi.pInvokes.CloseHandle(hToken);
}
if (String.IsNullOrEmpty(ret))
{
ret = GetProfileDir(sid).DefaultIfEmpty("").FirstOrDefault();
}
return ret;
}
/// <summary>
/// sets user profile quota
/// </summary>
/// <param name="where">ROOTKEY hklm or hku</param>
/// <param name="name">SubKey name</param>
/// <param name="quota">if 0 means the profile quota GPO it will be deleted</param>
/// <returns>false on error</returns>
public static Boolean SetQuota(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation where, string name, uint quota)
{
LibraryLogging.Info("set Quota for {0}", name);
try
{
using (RegistryKey key = Abstractions.WindowsApi.pInvokes.GetRegistryLocation(where).CreateSubKey(name + @"\Software\Microsoft\Windows\CurrentVersion\Policies\System"))
{
if (quota > 0)
{
key.SetValue("EnableProfileQuota", 1, RegistryValueKind.DWord);
//key.SetValue("ProfileQuotaMessage", "You have exceeded your profile storage space. Before you can log off, you need to move some items from your profile to network or local storage.", RegistryValueKind.String);
key.SetValue("MaxProfileSize", quota, RegistryValueKind.DWord);
key.SetValue("IncludeRegInProQuota", 1, RegistryValueKind.DWord);
key.SetValue("WarnUser", 1, RegistryValueKind.DWord);
key.SetValue("WarnUserTimeout", 5, RegistryValueKind.DWord);
}
else
{
key.DeleteValue("EnableProfileQuota", false);
key.DeleteValue("ProfileQuotaMessage", false);
key.DeleteValue("MaxProfileSize", false);
key.DeleteValue("IncludeRegInProQuota", false);
key.DeleteValue("WarnUser", false);
key.DeleteValue("WarnUserTimeout", false);
}
}
}
catch (Exception ex)
{
LibraryLogging.Error("Can't set profile quota for {0} Error:{1}", name, ex.Message);
return false;
}
return true;
}
/// <summary>
/// query for already set user profile quota
/// </summary>
/// <param name="where"></param>
/// <param name="name"></param>
/// <returns>true on already set</returns>
public static Boolean QueryQuota(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation where, string name)
{
LibraryLogging.Info("query Quota for {0}", name);
try
{
using (RegistryKey key = Abstractions.WindowsApi.pInvokes.GetRegistryLocation(where).OpenSubKey(name + @"\Software\Microsoft\Windows\CurrentVersion\Policies\System"))
{
if (key.GetValue("EnableProfileQuota") == null)
{
return false;
}
}
}
catch (Exception ex)
{
LibraryLogging.Error("Can't get profile quota for {0} Error:{1}", name, ex.Message);
return false;
}
return true;
}
}
}
<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <Windows.h>
#include <string>
#include "Gina.h"
#include "Winlogon.h"
#include "WinlogonProxy.h"
namespace pGina
{
namespace GINA
{
// Define function prototypes for all potential GINA exports
typedef BOOL (WINAPI * PFWLXNEGOTIATE) (DWORD, DWORD *);
typedef BOOL (WINAPI * PFWLXINITIALIZE) (LPWSTR, HANDLE, PVOID, PVOID, PVOID *);
typedef VOID (WINAPI * PFWLXDISPLAYSASNOTICE) (PVOID);
typedef int (WINAPI * PFWLXLOGGEDOUTSAS) (PVOID, DWORD, PLUID, PSID, PDWORD, PHANDLE, PWLX_MPR_NOTIFY_INFO, PVOID *);
typedef BOOL (WINAPI * PFWLXACTIVATEUSERSHELL) (PVOID, PWSTR, PWSTR, PVOID);
typedef int (WINAPI * PFWLXLOGGEDONSAS) (PVOID, DWORD, PVOID);
typedef VOID (WINAPI * PFWLXDISPLAYLOCKEDNOTICE) (PVOID);
typedef int (WINAPI * PFWLXWKSTALOCKEDSAS) (PVOID, DWORD);
typedef BOOL (WINAPI * PFWLXISLOCKOK) (PVOID);
typedef BOOL (WINAPI * PFWLXISLOGOFFOK) (PVOID);
typedef VOID (WINAPI * PFWLXLOGOFF) (PVOID);
typedef VOID (WINAPI * PFWLXSHUTDOWN) (PVOID, DWORD);
typedef BOOL (WINAPI * PFWLXSCREENSAVERNOTIFY) (PVOID, BOOL *);
typedef BOOL (WINAPI * PFWLXSTARTAPPLICATION) (PVOID, PWSTR, PVOID, PWSTR);
typedef BOOL (WINAPI * PFWLXNETWORKPROVIDERLOAD) (PVOID, PWLX_MPR_NOTIFY_INFO);
typedef BOOL (WINAPI * PFWLXDISPLAYSTATUSMESSAGE) (PVOID, HDESK, DWORD, PWSTR, PWSTR);
typedef BOOL (WINAPI * PFWLXGETSTATUSMESSAGE) (PVOID, DWORD *, PWSTR, DWORD);
typedef BOOL (WINAPI * PFWLXREMOVESTATUSMESSAGE) (PVOID);
typedef BOOL (WINAPI * PFWLXGETCONSOLESWITCHCREDENTIALS) (PVOID, PVOID);
typedef VOID (WINAPI * PFWLXRECONNECTNOTIFY) (PVOID);
typedef VOID (WINAPI * PFWLXDISCONNECTNOTIFY) (PVOID);
// Gina implementation that loads another gina dll only (no stubbing/hooking),
// allowing a caller to 'be' winlogon.
class GinaWrapper : public Gina
{
public:
GinaWrapper(const wchar_t * dll);
~GinaWrapper();
DWORD Version() { return m_dllVersion; }
// Additional GINA exports that we implement
bool Negotiate(DWORD dwWinlogonVersion);
bool Initialize(LPWSTR lpWinsta, HANDLE hWlx, PVOID pvReserved, PVOID pWinlogonFunctions);
// Standard Gina * interfaces, directly map to GINA exports
virtual bool IsLockOk();
virtual bool IsLogoffOk();
virtual bool GetConsoleSwitchCredentials(PVOID pCredInfo);
virtual void ReconnectNotify();
virtual void DisconnectNotify();
virtual void Logoff();
virtual bool ScreenSaverNotify(BOOL * pSecure);
virtual void Shutdown(DWORD ShutdownType);
virtual void DisplaySASNotice();
virtual void DisplayLockedNotice();
virtual bool DisplayStatusMessage(HDESK hDesktop, DWORD dwOptions, PWSTR pTitle, PWSTR pMessage);
virtual bool GetStatusMessage(DWORD * pdwOptions, PWSTR pMessage, DWORD dwBufferSize);
virtual bool RemoveStatusMessage();
virtual int LoggedOutSAS(DWORD dwSasType, PLUID pAuthenticationId, PSID pLogonSid, PDWORD pdwOptions,
PHANDLE phToken, PWLX_MPR_NOTIFY_INFO pMprNotifyInfo, PVOID *pProfile);
virtual int LoggedOnSAS(DWORD dwSasType, PVOID pReserved);
virtual int WkstaLockedSAS(DWORD dwSasType);
virtual bool ActivateUserShell(PWSTR pszDesktopName, PWSTR pszMprLogonScript, PVOID pEnvironment);
virtual bool StartApplication(PWSTR pszDesktopName, PVOID pEnvironment, PWSTR pszCmdLine);
virtual bool NetworkProviderLoad(PWLX_MPR_NOTIFY_INFO pNprNotifyInfo);
// Call this to load (and verify it loaded) the wrapped gina
bool Load();
void Unload();
bool IsLoaded() { return m_dll != 0; }
private:
std::wstring m_dllname;
void * m_ginaContext;
HINSTANCE m_dll;
DWORD m_dllVersion;
bool m_negotiated;
bool m_initialized;
// Pointers to the real MSGINA functions.
PFWLXNEGOTIATE m_pfWlxNegotiate;
PFWLXINITIALIZE m_pfWlxInitialize;
PFWLXDISPLAYSASNOTICE m_pfWlxDisplaySASNotice;
PFWLXLOGGEDOUTSAS m_pfWlxLoggedOutSAS;
PFWLXACTIVATEUSERSHELL m_pfWlxActivateUserShell;
PFWLXLOGGEDONSAS m_pfWlxLoggedOnSAS;
PFWLXDISPLAYLOCKEDNOTICE m_pfWlxDisplayLockedNotice;
PFWLXWKSTALOCKEDSAS m_pfWlxWkstaLockedSAS;
PFWLXISLOCKOK m_pfWlxIsLockOk;
PFWLXISLOGOFFOK m_pfWlxIsLogoffOk;
PFWLXLOGOFF m_pfWlxLogoff;
PFWLXSHUTDOWN m_pfWlxShutdown;
PFWLXSTARTAPPLICATION m_pfWlxStartApplication;
PFWLXSCREENSAVERNOTIFY m_pfWlxScreenSaverNotify;
PFWLXNETWORKPROVIDERLOAD m_pfWlxNetworkProviderLoad;
PFWLXDISPLAYSTATUSMESSAGE m_pfWlxDisplayStatusMessage;
PFWLXGETSTATUSMESSAGE m_pfWlxGetStatusMessage;
PFWLXREMOVESTATUSMESSAGE m_pfWlxRemoveStatusMessage;
PFWLXGETCONSOLESWITCHCREDENTIALS m_pfWlxGetConsoleSwitchCredentials;
PFWLXRECONNECTNOTIFY m_pfWlxReconnectNotify;
PFWLXDISCONNECTNOTIFY m_pfWlxDisconnectNotify;
};
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using pGina.Shared.Types;
using log4net;
using System.Text.RegularExpressions;
using System.Threading;
namespace pGina.Plugin.scripting
{
public class PluginImpl : pGina.Shared.Interfaces.IPluginAuthentication, pGina.Shared.Interfaces.IPluginAuthorization, pGina.Shared.Interfaces.IPluginAuthenticationGateway, pGina.Shared.Interfaces.IPluginChangePassword, pGina.Shared.Interfaces.IPluginEventNotifications, pGina.Shared.Interfaces.IPluginLogoffRequestAddTime, pGina.Shared.Interfaces.IPluginConfiguration
{
internal class notify : System.Collections.IEnumerable
{
internal bool pwd { get; set; }
internal bool logon { get; set; }
internal bool logoff { get; set; }
internal string script { get; set; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
yield break;
}
}
private ILog m_logger = LogManager.GetLogger("scripting");
private Dictionary<string, Boolean> RunningTasks = new Dictionary<string, Boolean>();
private ReaderWriterLockSlim Locker = new ReaderWriterLockSlim();
public static Boolean IsShuttingDown = false;
#region Init-plugin
public static Guid PluginUuid
{
get { return new Guid("{EA94CEBF-6ED1-454A-B333-81C4FAD61FA4}"); }
}
public PluginImpl()
{
using (Process me = Process.GetCurrentProcess())
{
m_logger.DebugFormat("Plugin initialized on {0} in PID: {1} Session: {2}", Environment.MachineName, me.Id, me.SessionId);
}
}
public string Name
{
get { return "scripting"; }
}
public string Description
{
get { return "run scripts in various stages"; }
}
public string Version
{
get
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public Guid Uuid
{
get { return PluginUuid; }
}
#endregion
public void Starting() { }
public void Stopping() { }
public Boolean LogoffRequestAddTime()
{
IsShuttingDown = true;
try
{
Locker.TryEnterReadLock(-1);
if (RunningTasks.Values.Contains(true))
{
return true;
}
}
catch (Exception ex)
{
m_logger.InfoFormat("LogoffRequestAddTime() error {0}", ex.Message);
}
finally
{
Locker.ExitReadLock();
}
return false;
}
public Boolean LoginUserRequest(string username)
{
try
{
Locker.TryEnterReadLock(-1);
if (RunningTasks.Keys.Contains(username.ToLower()))
{
m_logger.InfoFormat("LoginUserRequest() logoff in process for {0}", username);
return true;
}
else
{
m_logger.InfoFormat("LoginUserRequest() {0} free to login", username);
return false;
}
}
catch (Exception ex)
{
m_logger.InfoFormat("LoginUserRequest() {0} error {1}", username, ex.Message);
}
finally
{
Locker.ExitReadLock();
}
return false;
}
public void Configure()
{
Configuration myDialog = new Configuration();
myDialog.ShowDialog();
}
internal Dictionary<string, List<notify>> GetSettings(UserInformation userInfo)
{
Dictionary<string, List<notify>> ret = new Dictionary<string, List<notify>>();
//Dictionary<bool, string> lines = new Dictionary<bool, string>();
List<notify> lines = new List<notify>();
if (ParseSettings((string[])Settings.Store.authe_sys, ref lines))
ret.Add("authe_sys", lines);
if (!String.IsNullOrEmpty(userInfo.script_authe_sys))
if (ParseSettings((string[])Settings.Store.authe_sys, ref lines))
ret.Add("authe_sys", lines);
if (ParseSettings((string[])Settings.Store.autho_sys, ref lines))
ret.Add("autho_sys", lines);
if (!String.IsNullOrEmpty(userInfo.script_autho_sys))
if (ParseSettings((string[])Settings.Store.autho_sys, ref lines))
ret.Add("autho_sys", lines);
if (ParseSettings((string[])Settings.Store.gateway_sys, ref lines))
ret.Add("gateway_sys", lines);
if (!String.IsNullOrEmpty(userInfo.script_gateway_sys))
if (ParseSettings((string[])Settings.Store.gateway_sys, ref lines))
ret.Add("gateway_sys", lines);
if (ParseSettings((string[])Settings.Store.notification_sys, ref lines))
ret.Add("notification_sys", lines);
if (!String.IsNullOrEmpty(userInfo.script_notification_sys))
if (ParseSettings((string[])Settings.Store.notification_sys, ref lines))
ret.Add("notification_sys", lines);
if (ParseSettings((string[])Settings.Store.notification_usr, ref lines))
ret.Add("notification_usr", lines);
if (!String.IsNullOrEmpty(userInfo.script_notification_usr))
if (ParseSettings((string[])Settings.Store.notification_usr, ref lines))
ret.Add("notification_usr", lines);
if (ParseSettings((string[])Settings.Store.changepwd_sys, ref lines))
ret.Add("changepwd_sys", lines);
if (!String.IsNullOrEmpty(userInfo.script_changepwd_sys))
if (ParseSettings((string[])Settings.Store.changepwd_sys, ref lines))
ret.Add("changepwd_sys", lines);
if (ParseSettings((string[])Settings.Store.changepwd_usr, ref lines))
ret.Add("changepwd_usr", lines);
if (!String.IsNullOrEmpty(userInfo.script_changepwd_usr))
if (ParseSettings((string[])Settings.Store.changepwd_usr, ref lines))
ret.Add("changepwd_usr", lines);
return ret;
}
internal bool ParseSettings(string[] setting, ref Dictionary<bool, string> lines)
{
lines = new Dictionary<bool, string>();
foreach (string line in setting)
{
if (Regex.IsMatch(line, "(?i)(True|False)\t.*"))
{
string[] split = line.Split('\t');
if (split.Length == 2)
{
lines.Add(Convert.ToBoolean(split[0]), split[1]);
}
}
}
return Convert.ToBoolean(lines.Count);
}
internal bool ParseSettings(string[] setting, ref List<notify> lines)
{
lines = new List<notify>();
foreach (string line in setting)
{
if (Regex.IsMatch(line, "(?i)(True|False)\t.*"))
{
string[] split = line.Split('\t');
if (split.Length == 2)
{
notify notification = new notify();
notification.pwd = Convert.ToBoolean(split[0]);
notification.logon = false;
notification.logoff = false;
notification.script = split[1];
lines.Add(notification);
}
}
if (Regex.IsMatch(line, "(?i)(True|False)\t(True|False)\t(True|False)\t.*"))
{
string[] split = line.Split('\t');
if (split.Length == 4)
{
notify notification = new notify();
notification.pwd = Convert.ToBoolean(split[0]);
notification.logon = Convert.ToBoolean(split[1]);
notification.logoff = Convert.ToBoolean(split[2]);
notification.script = split[3];
lines.Add(notification);
}
}
}
return Convert.ToBoolean(lines.Count);
}
internal bool Run(int sessionId, string cmd, UserInformation userInfo, bool pwd, bool? sys, string authentication, string authorization, string gateway)
{
string expand_cmd = "";
string expand_cmd_out = "";
foreach (string c in cmd.Split(' '))
{
string ce = c;
string cp = c;
if (!Regex.IsMatch(c, @"(?i)%\S+%") && Regex.IsMatch(c, @"(?i)%\S+"))
{
ce = ce.Replace("%u", userInfo.Username);
cp = cp.Replace("%u", userInfo.Username);
ce = ce.Replace("%o", userInfo.OriginalUsername);
cp = cp.Replace("%o", userInfo.OriginalUsername);
if (pwd)
{
ce = ce.Replace("%p", userInfo.Password);
cp = cp.Replace("%p", "*****");
ce = ce.Replace("%b", userInfo.oldPassword);
cp = cp.Replace("%b", "*****");
}
ce = ce.Replace("%s", userInfo.SID.Value);
cp = cp.Replace("%s", userInfo.SID.Value);
ce = ce.Replace("%e", userInfo.PasswordEXP.ToString());
cp = cp.Replace("%e", userInfo.PasswordEXP.ToString());
ce = ce.Replace("%i", userInfo.SessionID.ToString());
cp = cp.Replace("%i", userInfo.SessionID.ToString());
ce = ce.Replace("%Ae", "Ae:" + authentication);
cp = cp.Replace("%Ae", "Ae:" + authentication);
ce = ce.Replace("%Ao", "Ao:" + authorization);
cp = cp.Replace("%Ao", "Ao:" + authorization);
ce = ce.Replace("%Gw", "Gw:" + gateway);
cp = cp.Replace("%Gw", "Gw:" + gateway);
expand_cmd += ce + " ";
expand_cmd_out += cp + " ";
}
else
{
expand_cmd += c + " ";
expand_cmd_out += cp + " ";
}
}
expand_cmd = expand_cmd.Trim();
expand_cmd_out = expand_cmd_out.Trim();
m_logger.InfoFormat("execute {0}", expand_cmd_out);
if (sys == true)
{
return (Abstractions.WindowsApi.pInvokes.CProcess(null, expand_cmd) == 0) ? true : false;
}
else if (sys == false)
{
return Abstractions.WindowsApi.pInvokes.StartUserProcessInSessionWait(sessionId, expand_cmd);
}
else //null while logoff
{
return Abstractions.WindowsApi.pInvokes.StartProcessAsUserWait(userInfo.Username, Environment.MachineName, userInfo.Password, expand_cmd);
}
}
internal string GetAuthenticationPluginResults(SessionProperties properties)
{
string authe = "";
try
{
PluginActivityInformation pluginInfo = properties.GetTrackedSingle<PluginActivityInformation>();
foreach (Guid uuid in pluginInfo.GetAuthenticationPlugins())
{
if (pluginInfo.GetAuthenticationResult(uuid).Success)
authe += "{" + uuid + "}";
}
}
catch (Exception ex)
{
m_logger.ErrorFormat("GetAuthenticationPluginResults Exception:", ex);
}
return authe;
}
internal string GetAuthorizationResults(SessionProperties properties)
{
string autho = "";
try
{
PluginActivityInformation pluginInfo = properties.GetTrackedSingle<PluginActivityInformation>();
foreach (Guid uuid in pluginInfo.GetAuthorizationPlugins())
{
if (pluginInfo.GetAuthorizationResult(uuid).Success)
autho += "{" + uuid + "}";
}
}
catch (Exception ex)
{
m_logger.ErrorFormat("GetAuthorizationResults Exception:", ex);
}
return autho;
}
internal string GetGatewayResults(SessionProperties properties)
{
string gateway = "";
try
{
PluginActivityInformation pluginInfo = properties.GetTrackedSingle<PluginActivityInformation>();
foreach (Guid uuid in pluginInfo.GetGatewayPlugins())
{
if (pluginInfo.GetGatewayResult(uuid).Success)
gateway += "{" + uuid + "}";
}
}
catch (Exception ex)
{
m_logger.ErrorFormat("GetGatewayResults Exception:", ex);
}
return gateway;
}
public BooleanResult AuthenticateUser(SessionProperties properties)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
Dictionary<string, List<notify>> settings = GetSettings(userInfo);
List<notify> authe_sys = new List<notify>();
try { authe_sys = settings["authe_sys"]; }
catch { }
foreach (notify line in authe_sys)
{
if (!Run(userInfo.SessionID, line.script, userInfo, line.pwd, true, GetAuthenticationPluginResults(properties), "", ""))
return new BooleanResult { Success = false, Message = String.Format("failed to run:{0}", line.script) };
}
// return false if no other plugin succeeded
BooleanResult ret = new BooleanResult() { Success = false, Message = this.Name + " plugin can't authenticate a user on its own" };
PluginActivityInformation pluginInfo = properties.GetTrackedSingle<PluginActivityInformation>();
foreach (Guid uuid in pluginInfo.GetAuthenticationPlugins())
{
if (pluginInfo.GetAuthenticationResult(uuid).Success)
{
return new BooleanResult() { Success = true };
}
else
{
ret.Message = pluginInfo.GetAuthenticationResult(uuid).Message;
}
}
return ret;
}
public BooleanResult AuthorizeUser(SessionProperties properties)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
Dictionary<string, List<notify>> settings = GetSettings(userInfo);
List<notify> autho_sys = new List<notify>();
try { autho_sys = settings["autho_sys"]; }
catch { }
foreach (notify line in autho_sys)
{
if (!Run(userInfo.SessionID, line.script, userInfo, line.pwd, true, GetAuthenticationPluginResults(properties), GetAuthorizationResults(properties), ""))
return new BooleanResult { Success = false, Message = String.Format("failed to run:{0}", line.script) };
}
// return false if no other plugin succeeded
BooleanResult ret = new BooleanResult() { Success = false, Message = this.Name + " plugin can't authorize a user on its own" };
PluginActivityInformation pluginInfo = properties.GetTrackedSingle<PluginActivityInformation>();
foreach (Guid uuid in pluginInfo.GetAuthorizationPlugins())
{
if (pluginInfo.GetAuthorizationResult(uuid).Success)
{
return new BooleanResult() { Success = true };
}
else
{
ret.Message = pluginInfo.GetAuthorizationResult(uuid).Message;
}
}
return ret;
}
public BooleanResult AuthenticatedUserGateway(SessionProperties properties)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
Dictionary<string, List<notify>> settings = GetSettings(userInfo);
List<notify> gateway_sys = new List<notify>();
try { gateway_sys = settings["gateway_sys"]; }
catch { }
foreach (notify line in gateway_sys)
{
if (!Run(userInfo.SessionID, line.script, userInfo, line.pwd, true, GetAuthenticationPluginResults(properties), GetAuthorizationResults(properties), GetGatewayResults(properties)))
return new BooleanResult { Success = false, Message = String.Format("failed to run:{0}", line.script) };
}
return new BooleanResult() { Success = true };
}
public void SessionChange(int SessionId, System.ServiceProcess.SessionChangeReason Reason, SessionProperties properties)
{
if (properties == null)
return;
if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogoff)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
if (userInfo.Description.Contains("pGina created") && userInfo.HasSID && !properties.CREDUI)
{
try
{
Locker.TryEnterWriteLock(-1);
RunningTasks.Add(userInfo.Username.ToLower(), true);
}
finally
{
Locker.ExitWriteLock();
}
// add this plugin into PluginActivityInformation
m_logger.DebugFormat("{1} properties.id:{0}", properties.Id, userInfo.Username);
PluginActivityInformation notification = properties.GetTrackedSingle<PluginActivityInformation>();
foreach (Guid gui in notification.GetNotificationPlugins())
{
m_logger.DebugFormat("{1} PluginActivityInformation Guid:{0}", gui, userInfo.Username);
}
m_logger.DebugFormat("{1} PluginActivityInformation add guid:{0}", PluginUuid, userInfo.Username);
notification.AddNotificationResult(PluginUuid, new BooleanResult { Message = "", Success = false });
properties.AddTrackedSingle<PluginActivityInformation>(notification);
foreach (Guid gui in notification.GetNotificationPlugins())
{
m_logger.DebugFormat("{1} PluginActivityInformation Guid:{0}", gui, userInfo.Username);
}
}
}
if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogon || Reason == System.ServiceProcess.SessionChangeReason.SessionLogoff)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
if (userInfo.Description.Contains("pGina created"))
{
Dictionary<string, List<notify>> settings = GetSettings(userInfo);
List<notify> notification_sys = new List<notify>();
try { notification_sys = settings["notification_sys"]; }
catch { }
List<notify> notification_usr = new List<notify>();
try { notification_usr = settings["notification_usr"]; }
catch { }
string authe = GetAuthenticationPluginResults(properties);
string autho = GetAuthorizationResults(properties);
string gateway = GetGatewayResults(properties);
foreach (notify line in notification_sys)
{
if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogon && line.logon)
{
if (!Run(userInfo.SessionID, line.script, userInfo, line.pwd, true, authe, autho, gateway))
m_logger.InfoFormat("failed to run:{0}", line.script);
}
}
foreach (notify line in notification_usr)
{
if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogon && line.logon)
{
if (!Run(userInfo.SessionID, line.script, userInfo, line.pwd, false, authe, autho, gateway))
m_logger.InfoFormat("failed to run:{0}", line.script);
}
}
if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogoff)
{
Thread rem_smb = new Thread(() => cleanup(userInfo, SessionId, properties, notification_sys, notification_usr, Reason, authe, autho, gateway));
rem_smb.Start();
}
}
}
}
public BooleanResult ChangePassword(SessionProperties properties, ChangePasswordPluginActivityInfo pluginInfo)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
Dictionary<string, List<notify>> settings = GetSettings(userInfo);
List<notify> changepwd_sys = new List<notify>();
try { changepwd_sys = settings["changepwd_sys"]; }
catch { }
List<notify> changepwd_usr = new List<notify>();
try { changepwd_usr = settings["changepwd_usr"]; }
catch { }
foreach (notify line in changepwd_sys)
{
if (!Run(userInfo.SessionID, line.script, userInfo, line.pwd, true, GetAuthenticationPluginResults(properties), GetAuthorizationResults(properties), GetGatewayResults(properties)))
return new BooleanResult { Success = false, Message = String.Format("failed to run:{0}", line.script) };
}
foreach (notify line in changepwd_usr)
{
if (!Run(userInfo.SessionID, line.script, userInfo, line.pwd, false, GetAuthenticationPluginResults(properties), GetAuthorizationResults(properties), GetGatewayResults(properties)))
return new BooleanResult { Success = false, Message = String.Format("failed to run:{0}", line.script) };
}
// the change password plugin chain will end as soon as one plugin failed
// no special treatment needed
return new BooleanResult { Success = true };
}
private void cleanup(UserInformation userInfo, int sessionID, SessionProperties properties, List<notify> notification_sys, List<notify> notification_usr, System.ServiceProcess.SessionChangeReason Reason, string authentication, string authorization, string gateway)
{
try
{
while (true)
{
// logoff detection is quite a problem under NT6
// a disconnectEvent is only triggered during a logoff
// but not during a shutdown/reboot
// and the SessionLogoffEvent is only saying that the user is logging of
// So, there is no event that is fired during a user-logoff/reboot/shutdown
// that indicates that the user has logged of
if (Abstractions.WindowsApi.pInvokes.IsSessionLoggedOFF(sessionID) || IsShuttingDown)
{
break;
}
else
{
Thread.Sleep(1000);
}
}
while (true)
{
// if no other notification plugin is working on this user
// if the first entry from GetNotificationPlugins is equal to this plugin UID
IEnumerable<Guid> guids = properties.GetTrackedSingle<PluginActivityInformation>().GetNotificationPlugins();
/*foreach(Guid gui in guids)
{
m_logger.DebugFormat("{1} PluginActivityInformation guid:{0}", gui, userInfo.Username);
}*/
if (guids.DefaultIfEmpty(Guid.Empty).FirstOrDefault().Equals(PluginUuid) || guids.ToList().Count == 0)
{
break;
}
Thread.Sleep(1000);
}
foreach (notify line in notification_sys)
{
if (line.logoff)
{
if (!Run(userInfo.SessionID, line.script, userInfo, line.pwd, true, authentication, authorization, gateway))
m_logger.InfoFormat("failed to run:{0}", line.script);
}
}
foreach (notify line in notification_usr)
{
if (line.logoff)
{
if (!Run(userInfo.SessionID, line.script, userInfo, line.pwd, null, authentication, authorization, gateway))
m_logger.InfoFormat("failed to run:{0}", line.script);
}
}
m_logger.InfoFormat("{0} scripting done", userInfo.Username);
}
catch (Exception ex)
{
m_logger.FatalFormat("{0} Error during Logoff of {1}", userInfo.Username, ex.Message);
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), userInfo.Username, userInfo.Password, String.Format("pGina: Logoff Exception {0} from {1}", userInfo.Username, Environment.MachineName), "Logoff Exception\n" + ex.Message);
}
try
{
Locker.TryEnterWriteLock(-1);
RunningTasks.Remove(userInfo.Username.ToLower());
PluginActivityInformation notification = properties.GetTrackedSingle<PluginActivityInformation>();
notification.DelNotificationResult(PluginUuid);
m_logger.InfoFormat("{1} PluginActivityInformation del Guid:{0}", PluginUuid, userInfo.Username);
properties.AddTrackedSingle<PluginActivityInformation>(notification);
foreach (Guid guid in properties.GetTrackedSingle<PluginActivityInformation>().GetNotificationPlugins())
{
m_logger.InfoFormat("{1} PluginActivityInformation Guid:{0}", guid, userInfo.Username);
}
}
finally
{
Locker.ExitWriteLock();
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.ServiceProcess;
using System.Reflection;
using Microsoft.Win32;
using pGina.Core;
using pGina.Core.Messages;
using pGina.Shared.Logging;
using pGina.Shared.Interfaces;
using Abstractions.WindowsApi;
using Abstractions.Logging;
using Abstractions.Pipes;
using log4net;
using pGina.Shared.Types;
namespace pGina.Configuration
{
public partial class ConfigurationUI : Form
{
private class DuplicatePluginDetectedException : System.Exception
{
public DuplicatePluginDetectedException(string Uuid, string Name) :
base(string.Format("Duplicate plugin {0} detected with UUID: {1}", Name, Uuid))
{
}
}
private static readonly string PGINA_SERVICE_NAME = "pGina";
// Plugin information keyed by Guid
private Dictionary<string, IPluginBase> m_plugins = new Dictionary<string, IPluginBase>();
private ILog m_logger = LogManager.GetLogger("ConfigurationUI");
private ServiceController m_pGinaServiceController = null;
private System.Timers.Timer m_serviceTimer = new System.Timers.Timer();
// Plugin data grid view
private const string PLUGIN_UUID_COLUMN = "Uuid";
private const string PLUGIN_VERSION_COLUMN = "Version";
private const string PLUGIN_DESC_COLUMN = "Description";
private const string PLUGIN_NAME_COLUMN = "Name";
private const string AUTHENTICATION_COLUMN = "Authentication";
private const string AUTHORIZATION_COLUMN = "Authorization";
private const string GATEWAY_COLUMN = "Gateway";
private const string NOTIFICATION_COLUMN = "Notification";
private const string PASSWORD_COLUMN = "Change Password";
// Cred Prov Filter data grid view
private const string CPF_CP_NAME_COLUMN = "Name";
private const string CPF_CP_LOGON_COLUMN = "FilterLogon";
private const string CPF_CP_UNLOCK_COLUMN = "FilterUnlock";
private const string CPF_CP_CHANGE_PASS_COLUMN = "FilterChangePass";
private const string CPF_CP_CREDUI_COLUMN = "FilterCredUI";
private const string CPF_CP_UUID_COLUMN = "Uuid";
private LogViewWindow logWindow = null;
public ConfigurationUI()
{
VerifyRegistryAccess();
Framework.Init();
InitializeComponent();
InitOptionsTabs();
InitPluginsDGV();
PopulatePluginDirs();
InitOrderLists();
try
{
RefreshPluginLists();
}
catch (DuplicatePluginDetectedException e)
{
MessageBox.Show(string.Format("Unable to load full plugin list: {0}", e.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
InitSimulationTab();
LoadGeneralSettings();
}
private void Form_Load(object sender, EventArgs e)
{
ToolTip toolTip1 = new ToolTip();
toolTip1.AutoPopDelay = 10000;
toolTip1.InitialDelay = 0;
toolTip1.ReshowDelay = 0;
toolTip1.ShowAlways = true;
toolTip1.SetToolTip(this.notify_smtp, "space seperated FQDN list of your smtp servers\nsmtp.domain.local:25");
toolTip1.SetToolTip(this.notify_email, "space seperated FQDN list of email addresses\nadmin<EMAIL>");
toolTip1.SetToolTip(this.notify_user, "smtp username");
toolTip1.SetToolTip(this.notify_pass, "smtp password");
toolTip1.SetToolTip(this.notify_cred, "prefer Login credentials instead of smtp username and password");
toolTip1.SetToolTip(this.notify_ssl, "use encrypted smtp connection");
toolTip1.SetToolTip(this.ntpservers, "list of NTP servers");
}
private void VerifyRegistryAccess()
{
// Test write access
try
{
using (RegistryKey key = Registry.LocalMachine.CreateSubKey(
pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot))
{
string name = "___test_name___";
key.SetValue(name, "...");
string value = (string)key.GetValue(name);
key.DeleteValue(name);
}
}
catch (System.UnauthorizedAccessException)
{
MessageBox.Show("Unable to access registry, good bye.",
"Registry access error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(1);
}
}
private void InitOptionsTabs()
{
if (Abstractions.Windows.OsInfo.IsVistaOrLater())
{
m_tabs.TabPages.Remove(ginaOptions);
InitCpOptions();
}
else
{
m_tabs.TabPages.Remove(cpOptions);
InitGinaOptions();
}
}
private void InitCpOptions()
{
dgvCredProvFilter.RowHeadersVisible = false;
dgvCredProvFilter.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgvCredProvFilter.MultiSelect = false;
dgvCredProvFilter.AllowUserToAddRows = false;
dgvCredProvFilter.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = CPF_CP_NAME_COLUMN,
DataPropertyName = CPF_CP_NAME_COLUMN,
HeaderText = "Credential Provider",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
ReadOnly = true
});
dgvCredProvFilter.Columns.Add(new DataGridViewCheckBoxColumn()
{
Name = CPF_CP_LOGON_COLUMN,
DataPropertyName = CPF_CP_LOGON_COLUMN,
HeaderText = "Logon",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
});
dgvCredProvFilter.Columns.Add(new DataGridViewCheckBoxColumn()
{
Name = CPF_CP_UNLOCK_COLUMN,
DataPropertyName = CPF_CP_UNLOCK_COLUMN,
HeaderText = "Unlock",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
});
dgvCredProvFilter.Columns.Add(new DataGridViewCheckBoxColumn()
{
Name = CPF_CP_CHANGE_PASS_COLUMN,
DataPropertyName = CPF_CP_CHANGE_PASS_COLUMN,
HeaderText = "Change Password",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
});
dgvCredProvFilter.Columns.Add(new DataGridViewCheckBoxColumn()
{
Name = CPF_CP_CREDUI_COLUMN,
DataPropertyName = CPF_CP_CREDUI_COLUMN,
HeaderText = "Cred UI",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
});
dgvCredProvFilter.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = CPF_CP_UUID_COLUMN,
DataPropertyName = CPF_CP_UUID_COLUMN,
HeaderText = "UUID",
AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
});
dgvCredProvFilter.AutoGenerateColumns = false;
dgvCredProvFilter.DataSource = CredProvFilterConfig.LoadCredProvsAndFilterSettings();
}
private void InitGinaOptions()
{
m_txtGinaChain.Text = Settings.Get.ChainedGinaPath;
chkSpecialButton.Checked = Settings.Get.EnableSpecialActionButton;
string action = Settings.Get.SpecialAction;
switch (action)
{
case "Shutdown":
radioShutdown.Checked = true;
break;
case "Restart":
radioRestart.Checked = true;
break;
case "Sleep":
radioSleep.Checked = true;
break;
case "Hibernate":
radioHibernate.Checked = true;
break;
}
radioSleep.Enabled = chkSpecialButton.Checked;
radioShutdown.Enabled = chkSpecialButton.Checked;
radioRestart.Enabled = chkSpecialButton.Checked;
radioHibernate.Enabled = chkSpecialButton.Checked;
}
private void LoadGeneralSettings()
{
m_pginaVersionLbl.Text = "pGina " +
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
m_tileImageTxt.Text = Settings.Get.GetSetting("TileImage", null);
LoadTileImagePreview();
// Load MOTD settings
this.enableMotdCB.Checked = Settings.Get.EnableMotd;
this.motdTB.Text = Settings.Get.GetSetting("Motd");
this.motdTB.Enabled = this.enableMotdCB.Checked;
// Service status checkbox
this.logonUiShowServiceStatusCB.Checked = Settings.Get.ShowServiceStatusInLogonUi;
// Make sure that the pGina service is installed
foreach( ServiceController ctrl in ServiceController.GetServices() )
{
if (ctrl.ServiceName == PGINA_SERVICE_NAME)
{
m_pGinaServiceController = ctrl;
break;
}
}
// This works around an annoying aspect of the textbox where the foreground color
// can't be changed unless the background color is set.
this.serviceStatusTB.BackColor = Color.GhostWhite;
this.cpEnabledTB.BackColor = Color.GhostWhite;
this.cpRegisteredTB.BackColor = Color.GhostWhite;
if (m_pGinaServiceController != null)
{
// Setup the timer that checks the service status periodically
m_serviceTimer.Interval = 1500;
m_serviceTimer.SynchronizingObject = this.serviceStatusTB;
m_serviceTimer.AutoReset = true;
m_serviceTimer.Elapsed += new System.Timers.ElapsedEventHandler(m_serviceTimer_Elapsed);
m_serviceTimer.Start();
UpdateServiceStatus();
}
else
{
this.serviceStatusTB.Text = "Not Installed";
this.serviceStopBtn.Enabled = false;
this.serviceStartBtn.Enabled = false;
}
UpdateCpStatus();
// Load the unlock setting
chk_originalUsernameUnlock.Checked = Settings.Get.UseOriginalUsernameInUnlockScenario;
// Display last username in logon screen
chk_lastusername.Checked = Settings.Get.LastUsernameEnable;
chk_preferlocalauthentication.Checked = Settings.Get.PreferLocalAuthentication;
//ntp server
//this.ntpservers = Settings.Get.GetGetSetting("ntpservers");
string[] ntpserverList = Settings.Get.ntpservers;
this.ntpservers.Text = String.Join("\n", ntpserverList);
// email notification
this.notify_smtp.Text = Settings.Get.GetSetting("notify_smtp");
this.notify_email.Text = Settings.Get.GetSetting("notify_email");
this.notify_user.Text = Settings.Get.GetSetting("notify_user");
this.notify_pass.Text = Settings.Get.GetEncryptedSetting("notify_pass");
this.notify_cred.Checked = Settings.Get.notify_cred;
this.notify_ssl.Checked = Settings.Get.notify_ssl;
}
private void UpdateCpStatus()
{
pGina.CredentialProvider.Registration.CredProviderManager manager =
pGina.CredentialProvider.Registration.CredProviderManager.GetManager();
if (manager.Registered())
{
this.cpRegisteredTB.Text = "Yes";
this.cpRegisteredTB.ForeColor = Color.Green;
this.cpRegisterBtn.Text = "Unregister";
this.cpEnableDisableBtn.Enabled = true;
if (manager.Enabled())
{
this.cpEnabledTB.Text = "Yes";
this.cpEnabledTB.ForeColor = Color.Green;
this.cpEnableDisableBtn.Text = "Disable";
}
else
{
this.cpEnabledTB.Text = "No";
this.cpEnabledTB.ForeColor = Color.Red;
this.cpEnableDisableBtn.Text = "Enable";
}
if (Abstractions.Windows.OsInfo.Is64Bit() && Abstractions.Windows.OsInfo.IsVistaOrLater() && !manager.Registered6432())
{
MessageBox.Show("Warning: The 32-bit CredentialProvider is not registered. 32-bit apps that " +
"make use of the CredentialProvider may not function correctly.");
}
}
else
{
this.cpRegisteredTB.Text = "No";
this.cpRegisteredTB.ForeColor = Color.Red;
this.cpRegisterBtn.Text = "Register";
this.cpEnabledTB.Text = "No";
this.cpEnabledTB.ForeColor = Color.Red;
this.cpEnableDisableBtn.Enabled = false;
this.cpEnableDisableBtn.Text = "Enable";
}
}
private void UpdateServiceStatus()
{
m_pGinaServiceController.Refresh();
ServiceControllerStatus stat = m_pGinaServiceController.Status;
string statusStr = stat.ToString();
switch (stat)
{
case ServiceControllerStatus.Running:
this.serviceStatusTB.ForeColor = Color.Green;
this.serviceStopBtn.Enabled = true;
this.serviceStartBtn.Enabled = false;
statusStr = "Running";
break;
case ServiceControllerStatus.ContinuePending:
statusStr = "Continue pending...";
this.serviceStatusTB.ForeColor = Color.Black;
this.serviceStopBtn.Enabled = false;
this.serviceStartBtn.Enabled = false;
break;
case ServiceControllerStatus.PausePending:
statusStr = "Pause pending...";
this.serviceStatusTB.ForeColor = Color.Black;
this.serviceStopBtn.Enabled = false;
this.serviceStartBtn.Enabled = false;
break;
case ServiceControllerStatus.StartPending:
statusStr = "Starting...";
this.serviceStatusTB.ForeColor = Color.Black;
this.serviceStopBtn.Enabled = false;
this.serviceStartBtn.Enabled = false;
break;
case ServiceControllerStatus.StopPending:
statusStr = "Stopping...";
this.serviceStatusTB.ForeColor = Color.Black;
this.serviceStopBtn.Enabled = false;
this.serviceStartBtn.Enabled = false;
break;
case ServiceControllerStatus.Paused:
this.serviceStatusTB.ForeColor = Color.Black;
this.serviceStopBtn.Enabled = true;
this.serviceStartBtn.Enabled = true;
break;
case ServiceControllerStatus.Stopped:
statusStr = "Stopped";
this.serviceStatusTB.ForeColor = Color.Red;
this.serviceStopBtn.Enabled = false;
this.serviceStartBtn.Enabled = true;
break;
}
this.serviceStatusTB.Text = statusStr;
}
private void LoadTileImagePreview()
{
if (!string.IsNullOrEmpty(m_tileImageTxt.Text))
{
try
{
m_tileImagePreview.Image = new Bitmap(m_tileImageTxt.Text);
}
catch (Exception ex)
{
MessageBox.Show("Unable to load a preview image for the selected file, pGina may not be able to show this image at login time.\n", "Error", MessageBoxButtons.OK);
m_logger.ErrorFormat("User chose {0} as image file, but we failed to load it? Exception: {1}", m_tileImageTxt.Text, ex);
m_tileImagePreview.Image = null;
}
}
}
private void InitSimulationTab()
{
// Set up columns in simPluginResultsListView
this.simPluginResultsListView.Columns.Add("Stage", -2, HorizontalAlignment.Left);
this.simPluginResultsListView.Columns.Add("Plugin", -2, HorizontalAlignment.Left);
this.simPluginResultsListView.Columns.Add("Result", -2, HorizontalAlignment.Left);
this.simPluginResultsListView.Columns.Add("Message", -2, HorizontalAlignment.Left);
this.simPluginResultsListView.LabelEdit = false;
this.simPluginResultsListView.GridLines = true;
this.simPluginResultsListView.View = View.Details;
this.logWindow = new LogViewWindow();
this.logWindow.FormClosing += new FormClosingEventHandler(logWindow_FormClosing);
ResetStageStatus();
}
void logWindow_FormClosing(object sender, FormClosingEventArgs e)
{
this.logWindow.Hide();
e.Cancel = true; // Don't dispose the window. We might show it again later.
}
private void InitOrderLists()
{
// Setup the DataGridViews
InitPluginOrderDGV(this.authenticateDGV);
InitPluginOrderDGV(this.authorizeDGV);
InitPluginOrderDGV(this.gatewayDGV);
InitPluginOrderDGV(this.eventDGV);
InitPluginOrderDGV(this.passwdDGV);
// Load order lists from the registry
LoadPluginOrderListsFromReg();
}
private void InitPluginOrderDGV(DataGridView dgv)
{
dgv.RowHeadersVisible = false;
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgv.MultiSelect = false;
dgv.AllowUserToAddRows = false;
dgv.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = PLUGIN_UUID_COLUMN,
Visible = false
});
dgv.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = PLUGIN_NAME_COLUMN,
HeaderText = "Plugin",
AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
ReadOnly = true
});
}
private void InitPluginsDGV()
{
pluginsDG.RowHeadersVisible = false;
pluginsDG.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
pluginsDG.MultiSelect = false;
pluginsDG.AllowUserToAddRows = false;
pluginsDG.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = PLUGIN_NAME_COLUMN,
HeaderText = "Plugin Name",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
ReadOnly = true
});
pluginsDG.Columns.Add(new DataGridViewCheckBoxColumn()
{
Name = AUTHENTICATION_COLUMN,
HeaderText = "Authentication",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
});
pluginsDG.Columns.Add(new DataGridViewCheckBoxColumn()
{
Name = AUTHORIZATION_COLUMN,
HeaderText = "Authorization",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
});
pluginsDG.Columns.Add(new DataGridViewCheckBoxColumn()
{
Name = GATEWAY_COLUMN,
HeaderText = "Gateway",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
});
pluginsDG.Columns.Add(new DataGridViewCheckBoxColumn()
{
Name = NOTIFICATION_COLUMN,
HeaderText = "Notification",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
});
pluginsDG.Columns.Add(new DataGridViewCheckBoxColumn()
{
Name = PASSWORD_COLUMN,
HeaderText = "Change Password",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
});
pluginsDG.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = PLUGIN_DESC_COLUMN,
HeaderText = "Description",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
ReadOnly = true
});
pluginsDG.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = PLUGIN_VERSION_COLUMN,
HeaderText = "Version",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
ReadOnly = true
});
pluginsDG.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = PLUGIN_UUID_COLUMN,
HeaderText = "UUID",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
ReadOnly = true
});
// Implement the cell paint event so that we can blank out cells
// that shouldn't be there.
pluginsDG.CellPainting += this.pluginsDG_PaintCell;
pluginsDG.SelectionChanged += this.pluginsDG_SelectionChanged;
pluginsDG.CurrentCellDirtyStateChanged += new EventHandler(pluginsDG_CurrentCellDirtyStateChanged);
pluginsDG.CellValueChanged += new DataGridViewCellEventHandler(pluginsDG_CellValueChanged);
}
void pluginsDG_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex >= 0 && e.RowIndex >= 0 &&
pluginsDG[e.ColumnIndex, e.RowIndex].ValueType == typeof(bool))
{
DataGridViewCell cell = this.pluginsDG[e.ColumnIndex, e.RowIndex];
string uuid = (string)this.pluginsDG.Rows[e.RowIndex].Cells[PLUGIN_UUID_COLUMN].Value;
IPluginBase plug = m_plugins[uuid];
bool checkBoxState = Convert.ToBoolean(cell.Value);
string columnName = pluginsDG.Columns[e.ColumnIndex].Name;
switch (columnName)
{
case AUTHENTICATION_COLUMN:
SyncStateToList(checkBoxState, plug, authenticateDGV);
break;
case AUTHORIZATION_COLUMN:
SyncStateToList(checkBoxState, plug, authorizeDGV);
break;
case GATEWAY_COLUMN:
SyncStateToList(checkBoxState, plug, gatewayDGV);
break;
case NOTIFICATION_COLUMN:
SyncStateToList(checkBoxState, plug, eventDGV);
break;
case PASSWORD_COLUMN:
SyncStateToList(checkBoxState, plug, passwdDGV);
break;
}
}
}
private void SyncStateToList(bool state, IPluginBase plugin, DataGridView grid)
{
if (state)
{
this.AddToOrderList(plugin, grid);
}
else
{
this.RemoveFromOrderList(plugin.Uuid.ToString(), grid);
}
}
void pluginsDG_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (this.pluginsDG.IsCurrentCellDirty)
{
this.pluginsDG.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void pluginsDG_SelectionChanged(object sender, EventArgs e)
{
int nSelectedRows = pluginsDG.SelectedRows.Count;
if (nSelectedRows > 0)
{
DataGridViewRow row = pluginsDG.SelectedRows[0];
string pluginUuid = (string)row.Cells[PLUGIN_UUID_COLUMN].Value;
IPluginBase plug = this.m_plugins[pluginUuid];
configureButton.Enabled = plug is IPluginConfiguration;
}
}
private void RefreshPluginLists()
{
m_plugins.Clear();
pluginsDG.Rows.Clear();
// Get the plugin directories from the list
List<string> pluginDirs = new List<string>();
foreach (ListViewItem item in lstPluginDirs.Items)
{
if (!pluginDirs.Contains((string)item.Tag))
pluginDirs.Add((string)item.Tag);
}
if (pluginDirs.Count > 0)
{
// Get plugins
PluginLoader.PluginDirectories = pluginDirs.ToArray();
PluginLoader.LoadPlugins();
List<IPluginBase> plugins = PluginLoader.AllPlugins;
for (int i = 0; i < plugins.Count; i++)
{
IPluginBase p = plugins[i];
if (m_plugins.ContainsKey(p.Uuid.ToString()))
{
m_logger.ErrorFormat("Duplicate plugin: {0} with UUID: {1}", p.Name, p.Uuid);
throw new DuplicatePluginDetectedException(p.Uuid.ToString(), p.Name);
}
this.m_plugins.Add(p.Uuid.ToString(), p);
pluginsDG.Rows.Add(
new object[] { p.Name, false, false, false, false, false, p.Description, p.Version, p.Uuid.ToString() });
DataGridViewRow row = pluginsDG.Rows[i];
this.SetupCheckBoxCell<IPluginAuthentication>(row.Cells[AUTHENTICATION_COLUMN], p);
this.SetupCheckBoxCell<IPluginAuthorization>(row.Cells[AUTHORIZATION_COLUMN], p);
this.SetupCheckBoxCell<IPluginAuthenticationGateway>(row.Cells[GATEWAY_COLUMN], p);
this.SetupCheckBoxCell<IPluginEventNotifications>(row.Cells[NOTIFICATION_COLUMN], p);
this.SetupCheckBoxCell<IPluginChangePassword>(row.Cells[PASSWORD_COLUMN], p);
}
}
UpdatePluginOrderListsFromUIState();
}
private void SetupCheckBoxCell<T>(DataGridViewCell cell, IPluginBase plug) where T : IPluginBase
{
if (plug is T)
{
cell.Value = PluginLoader.IsEnabledFor<T>(plug);
}
else
{
// If a cell is read-only, the paint callback will draw over the
// checkbox so that it is not visible.
cell.ReadOnly = true;
}
}
private void LoadPluginOrderListsFromReg()
{
LoadPluginOrderListFromReg<IPluginAuthentication>(authenticateDGV);
LoadPluginOrderListFromReg<IPluginAuthenticationGateway>(gatewayDGV);
LoadPluginOrderListFromReg<IPluginAuthorization>(authorizeDGV);
LoadPluginOrderListFromReg<IPluginEventNotifications>(eventDGV);
LoadPluginOrderListFromReg<IPluginChangePassword>(passwdDGV);
}
private void LoadPluginOrderListFromReg<T>(DataGridView grid) where T : class, IPluginBase
{
grid.Rows.Clear();
List<T> plugins = PluginLoader.GetOrderedPluginsOfType<T>();
foreach (IPluginBase plug in plugins)
{
AddToOrderList(plug, grid);
}
}
private void UpdatePluginOrderListsFromUIState()
{
// Make sure that all checkboxes in the main plugin list agree with the ordered
// lists.
foreach (DataGridViewRow row in this.pluginsDG.Rows)
{
string uuid = (string)row.Cells[PLUGIN_UUID_COLUMN].Value;
IPluginBase plug = m_plugins[uuid];
if (!row.Cells[AUTHENTICATION_COLUMN].ReadOnly)
SyncStateToList((bool)row.Cells[AUTHENTICATION_COLUMN].Value, plug, authenticateDGV);
if (!row.Cells[AUTHORIZATION_COLUMN].ReadOnly)
SyncStateToList((bool)row.Cells[AUTHORIZATION_COLUMN].Value, plug, authorizeDGV);
if (!row.Cells[GATEWAY_COLUMN].ReadOnly)
SyncStateToList((bool)row.Cells[GATEWAY_COLUMN].Value, plug, gatewayDGV);
if (!row.Cells[NOTIFICATION_COLUMN].ReadOnly)
SyncStateToList((bool)row.Cells[NOTIFICATION_COLUMN].Value, plug, eventDGV);
if (!row.Cells[PASSWORD_COLUMN].ReadOnly)
SyncStateToList((bool)row.Cells[PASSWORD_COLUMN].Value, plug, passwdDGV);
}
// Remove any plugins that are no longer in the main list from the
// ordered lists
this.RemoveAllNotInMainList(authorizeDGV);
this.RemoveAllNotInMainList(authenticateDGV);
this.RemoveAllNotInMainList(gatewayDGV);
this.RemoveAllNotInMainList(eventDGV);
this.RemoveAllNotInMainList(passwdDGV);
}
private void RemoveAllNotInMainList(DataGridView dgv)
{
List<DataGridViewRow> toRemove = new List<DataGridViewRow>();
foreach (DataGridViewRow row in dgv.Rows)
{
if (!m_plugins.ContainsKey((string)row.Cells[PLUGIN_UUID_COLUMN].Value))
{
toRemove.Add(row);
}
}
foreach (DataGridViewRow row in toRemove)
dgv.Rows.Remove(row);
}
private void RemoveFromOrderList(string uuid, DataGridView dgv)
{
foreach (DataGridViewRow row in dgv.Rows)
{
if ((string)row.Cells[PLUGIN_UUID_COLUMN].Value == uuid)
{
dgv.Rows.Remove(row);
return;
}
}
}
/// <summary>
/// Adds the plugin to the ordered list in the second parameter. If the plugin
/// is already in the list, does nothing.
/// </summary>
/// <param name="plug">Plugin to add</param>
/// <param name="dgv">The ordered list to add to.</param>
private void AddToOrderList(IPluginBase plug, DataGridView dgv)
{
if (!viewContainsPlugin(dgv, plug.Uuid.ToString()))
{
dgv.Rows.Add(new object[] { plug.Uuid.ToString(), plug.Name });
}
}
private bool viewContainsPlugin(DataGridView dgv, string plugUuid)
{
foreach (DataGridViewRow row in dgv.Rows)
{
if ((string)row.Cells[PLUGIN_UUID_COLUMN].Value == plugUuid)
return true;
}
return false;
}
private void pluginsDG_PaintCell(object sender, DataGridViewCellPaintingEventArgs e)
{
// Determine if the cell should have a checkbox or not (via the ReadOnly setting),
// if not, we draw over the checkbox.
if (e != null && sender != null)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0 &&
pluginsDG[e.ColumnIndex, e.RowIndex].ReadOnly &&
pluginsDG[e.ColumnIndex, e.RowIndex].ValueType == typeof(bool))
{
Type foo = pluginsDG[e.ColumnIndex, e.RowIndex].ValueType;
e.PaintBackground(e.CellBounds, true);
e.Handled = true;
}
}
}
private void PopulatePluginDirs()
{
// Populate plugin directories UI
string[] pluginDirectories = Settings.Get.PluginDirectories;
lstPluginDirs.Columns.Clear();
lstPluginDirs.Columns.Add("Directory");
lstPluginDirs.Columns[0].Width = lstPluginDirs.Width - 5;
lstPluginDirs.Items.Clear();
foreach (string dir in pluginDirectories)
{
ListViewItem item = new ListViewItem(new string[] { dir });
item.Tag = dir;
lstPluginDirs.Items.Add(item);
}
}
private void SavePluginDirs()
{
// Save changes to plugin directories
List<string> pluginDirs = new List<string>();
foreach (ListViewItem item in lstPluginDirs.Items)
{
if (!pluginDirs.Contains((string)item.Tag))
pluginDirs.Add((string)item.Tag);
}
Settings.Get.PluginDirectories = pluginDirs.ToArray();
}
private void SavePluginSettings()
{
foreach (DataGridViewRow row in pluginsDG.Rows)
{
try
{
IPluginBase p = m_plugins[(string)row.Cells[PLUGIN_UUID_COLUMN].Value];
int mask = 0;
if (Convert.ToBoolean(row.Cells[AUTHENTICATION_COLUMN].Value))
mask |= (int)Core.PluginLoader.State.AuthenticateEnabled;
if (Convert.ToBoolean(row.Cells[AUTHORIZATION_COLUMN].Value))
mask |= (int)Core.PluginLoader.State.AuthorizeEnabled;
if (Convert.ToBoolean(row.Cells[GATEWAY_COLUMN].Value))
mask |= (int)Core.PluginLoader.State.GatewayEnabled;
if (Convert.ToBoolean(row.Cells[NOTIFICATION_COLUMN].Value))
mask |= (int)Core.PluginLoader.State.NotificationEnabled;
if (Convert.ToBoolean(row.Cells[PASSWORD_COLUMN].Value))
mask |= (int)Core.PluginLoader.State.ChangePasswordEnabled;
Core.Settings.Get.SetSetting(p.Uuid.ToString(), mask);
}
catch (Exception e)
{
MessageBox.Show("Exception when saving data: " + e);
}
}
}
private void SavePluginOrder()
{
SavePluginOrder(authenticateDGV, typeof(IPluginAuthentication));
SavePluginOrder(authorizeDGV, typeof(IPluginAuthorization));
SavePluginOrder(gatewayDGV, typeof(IPluginAuthenticationGateway));
SavePluginOrder(eventDGV, typeof(IPluginEventNotifications));
SavePluginOrder(passwdDGV, typeof(IPluginChangePassword));
}
private void SavePluginOrder(DataGridView grid, Type pluginType)
{
string setting = pluginType.Name + "_Order";
List<string> orderedList = new List<string>();
foreach (DataGridViewRow row in grid.Rows)
{
orderedList.Add((string)row.Cells[PLUGIN_UUID_COLUMN].Value);
}
Settings.Get.SetSetting(setting, orderedList.ToArray<string>());
}
private bool CheckPluginSettings()
{
bool AUTHENTICATION = false;
//bool AUTHORIZATION = false;
foreach (DataGridViewRow row in pluginsDG.Rows)
{
if (Convert.ToBoolean(row.Cells[AUTHENTICATION_COLUMN].Value))
AUTHENTICATION = true;/*
if (Convert.ToBoolean(row.Cells[AUTHORIZATION_COLUMN].Value))
AUTHORIZATION = true;*/
if (AUTHENTICATION /*&& AUTHORIZATION*/)
return true;
}
if (!AUTHENTICATION)
{
MessageBox.Show(this, "At least one plugin must be set for Authentication", "Can't save settings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}/*
if (!AUTHORIZATION)
{
MessageBox.Show(this, "At least one plugin must be set for Authorization", "Can't save settings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}*/
return false;
}
private bool SaveSettings()
{
if (!this.CheckPluginSettings())
return false;
this.SavePluginSettings();
this.SavePluginDirs();
this.SavePluginOrder();
Core.Settings.Get.TileImage = m_tileImageTxt.Text;
this.LoadTileImagePreview();
// MOTD stuff
Settings.Get.EnableMotd = this.enableMotdCB.Checked;
Settings.Get.Motd = this.motdTB.Text.Trim();
// Service status checkbox
Settings.Get.ShowServiceStatusInLogonUi = this.logonUiShowServiceStatusCB.Checked;
// Save unlock setting
Settings.Get.UseOriginalUsernameInUnlockScenario = chk_originalUsernameUnlock.Checked;
// Display last username in logon screen
Settings.Get.LastUsernameEnable = chk_lastusername.Checked;
Settings.Get.PreferLocalAuthentication = chk_preferlocalauthentication.Checked;
if (Abstractions.Windows.OsInfo.IsVistaOrLater())
this.SaveCpSettings();
else
this.SaveGinaSettings();
// ntp server
Settings.Get.ntpservers = this.ntpservers.Text.Split('\n');
// email notification
Settings.Get.notify_smtp = this.notify_smtp.Text;
Settings.Get.notify_email = this.notify_email.Text;
Settings.Get.notify_user = this.notify_user.Text;
Settings.Get.SetEncryptedSetting("notify_pass", this.notify_pass.Text);
Settings.Get.notify_cred = this.notify_cred.Checked;
Settings.Get.notify_ssl = this.notify_ssl.Checked;
return true;
}
private void MoveUp(DataGridView dgv, int index)
{
if (index > 0)
{
DataGridViewRow row = dgv.Rows[index];
dgv.Rows.RemoveAt(index);
dgv.Rows.Insert(index - 1, row);
dgv.Rows[index - 1].Selected = true;
}
}
private void MoveDown(DataGridView dgv, int index)
{
int rows = dgv.Rows.Count;
if (index < rows - 1)
{
DataGridViewRow row = dgv.Rows[index];
dgv.Rows.RemoveAt(index);
dgv.Rows.Insert(index + 1, row);
dgv.Rows[index + 1].Selected = true;
}
}
private void btnOkay_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnApply_Click(object sender, EventArgs e)
{
if (SaveSettings())
MessageBox.Show("Settings written to registry.", "Settings Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btnSaveAndClose_Click(object sender, EventArgs e)
{
if (SaveSettings())
this.Close();
}
private void btnAdd_Click(object sender, EventArgs e)
{
FolderBrowserDialog folder = new FolderBrowserDialog();
folder.Description = "Plugin Directory Selection...";
if (folder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = folder.SelectedPath;
if (lstPluginDirs.Items.Find(path, true).Length == 0)
{
ListViewItem item = new ListViewItem(new string[] { path });
item.Tag = path;
lstPluginDirs.Items.Add(item);
}
try
{
this.RefreshPluginLists();
}
catch (DuplicatePluginDetectedException ex)
{
MessageBox.Show(string.Format("Unable to load full plugin list: {0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
private void btnRemove_Click(object sender, EventArgs e)
{
if (lstPluginDirs.SelectedItems.Count > 0)
{
foreach (ListViewItem item in lstPluginDirs.SelectedItems)
{
lstPluginDirs.Items.Remove(item);
}
try
{
this.RefreshPluginLists();
}
catch (DuplicatePluginDetectedException ex)
{
MessageBox.Show(string.Format("Unable to load full plugin list: {0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
private void configureButton_Click(object sender, EventArgs e)
{
int nSelectedRows = pluginsDG.SelectedRows.Count;
if (nSelectedRows > 0)
{
DataGridViewRow row = pluginsDG.SelectedRows[0];
string pluginUuid = (string)row.Cells[PLUGIN_UUID_COLUMN].Value;
IPluginBase plug = this.m_plugins[pluginUuid];
if (plug is IPluginConfiguration)
{
IPluginConfiguration configPlugin = plug as IPluginConfiguration;
configPlugin.Configure();
}
}
}
private void simMethodChanged(object sender, EventArgs e)
{
btnLaunchCredUI.Enabled = (sender == m_radioCredUI);
}
private void authenticateBtnUp_Click(object sender, EventArgs e)
{
if (this.authenticateDGV.SelectedRows.Count > 0)
MoveUp(this.authenticateDGV, this.authenticateDGV.SelectedRows[0].Index);
}
private void authenticateBtnDown_Click(object sender, EventArgs e)
{
if (this.authenticateDGV.SelectedRows.Count > 0)
MoveDown(this.authenticateDGV, this.authenticateDGV.SelectedRows[0].Index);
}
private void authorizeBtnUp_Click(object sender, EventArgs e)
{
if (this.authorizeDGV.SelectedRows.Count > 0)
MoveUp(this.authorizeDGV, this.authorizeDGV.SelectedRows[0].Index);
}
private void authorizeBtnDown_Click(object sender, EventArgs e)
{
if (this.authorizeDGV.SelectedRows.Count > 0)
MoveDown(this.authorizeDGV, this.authorizeDGV.SelectedRows[0].Index);
}
private void gatewayBtnUp_Click(object sender, EventArgs e)
{
if (this.gatewayDGV.SelectedRows.Count > 0)
MoveUp(this.gatewayDGV, this.gatewayDGV.SelectedRows[0].Index);
}
private void gatewayBtnDown_Click(object sender, EventArgs e)
{
if (this.gatewayDGV.SelectedRows.Count > 0)
MoveDown(this.gatewayDGV, this.gatewayDGV.SelectedRows[0].Index);
}
private void eventBtnUp_Click(object sender, EventArgs e)
{
if (this.eventDGV.SelectedRows.Count > 0)
MoveUp(this.eventDGV, this.eventDGV.SelectedRows[0].Index);
}
private void eventBtnDown_Click(object sender, EventArgs e)
{
if (this.eventDGV.SelectedRows.Count > 0)
MoveDown(this.eventDGV, this.eventDGV.SelectedRows[0].Index);
}
private void passwdBtnUp_Click(object sender, EventArgs e)
{
if (this.passwdDGV.SelectedRows.Count > 0)
MoveUp(this.passwdDGV, this.passwdDGV.SelectedRows[0].Index);
}
private void passwdBtnDown_Click(object sender, EventArgs e)
{
if (this.passwdDGV.SelectedRows.Count > 0)
MoveDown(this.passwdDGV, this.passwdDGV.SelectedRows[0].Index);
}
private void btnLaunchCredUI_Click(object sender, EventArgs e)
{
ResetSimUI();
System.Net.NetworkCredential credential = pInvokes.GetCredentials("Simulated Login", "Please enter your credentials...");
if (credential != null)
{
ResetStageStatus();
m_usernameResult.Text = credential.UserName;
m_domainResult.Text = credential.Domain;
m_passwordResult.Text = <PASSWORD>.Password;
}
}
private void HandleLabelTextChange(Label lbl)
{
if (lbl.Text == "Success")
lbl.ForeColor = Color.Green;
else if (lbl.Text == "Failure")
lbl.ForeColor = Color.Red;
else
lbl.ForeColor = Color.Black;
}
private void m_lblAuthResult_TextChanged(object sender, EventArgs e)
{
HandleLabelTextChange((Label)sender);
}
private void SimLogHandler(string message)
{
this.logWindow.LogTextBox.AppendText(message);
}
private List<string> GetPluginList()
{
List<string> result = new List<string>();
List<IPluginAuthentication> authPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthentication>();
List<IPluginAuthorization> authzPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthorization>();
List<IPluginAuthenticationGateway> gatewayPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthenticationGateway>();
List<IPluginEventNotifications> notePlugins = PluginLoader.GetOrderedPluginsOfType<IPluginEventNotifications>();
List<IPluginChangePassword> passwdPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginChangePassword>();
result.Add("Authentication: " + (string.Join(", ", authPlugins.Select(p => p.Name))));
result.Add("Authorization: " + (string.Join(", ", authzPlugins.Select(p => p.Name))));
result.Add("Gateway: " + (string.Join(", ", gatewayPlugins.Select(p => p.Name))));
result.Add("Notification: " + (string.Join(", ", notePlugins.Select(p => p.Name))));
result.Add("Change Password: " + (string.Join(", ", passwdPlugins.Select(p => p.Name))));
return result;
}
private void ResetSimUI()
{
this.simFinalResultMessageTB.Text = null;
this.simPluginResultsListView.Items.Clear();
ResetStageStatus();
m_usernameResult.Text = null;
m_domainResult.Text = null;
m_passwordResult.Text = null;
this.logWindow.LogTextBox.Text = "";
if (m_radioUseService.Checked || m_radioCredUI.Checked)
{
this.logWindow.LogTextBox.AppendText("*****" + Environment.NewLine);
this.logWindow.LogTextBox.AppendText("***** Log output unavailable when using pGina service or CredUI prompt." +
Environment.NewLine);
this.logWindow.LogTextBox.AppendText("*****" + Environment.NewLine);
}
else
{
this.logWindow.LogTextBox.AppendText("****" + Environment.NewLine);
this.logWindow.LogTextBox.AppendText("**** Simulated login starting: " + DateTime.Now.ToString("F") + Environment.NewLine);
this.logWindow.LogTextBox.AppendText("**** pGina Version: " +
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + Environment.NewLine);
this.logWindow.LogTextBox.AppendText("**** Enabled plugins: " + Environment.NewLine);
foreach (string s in GetPluginList())
{
this.logWindow.LogTextBox.AppendText("**** " + s + Environment.NewLine);
}
this.logWindow.LogTextBox.AppendText("****" + Environment.NewLine);
}
}
private void btnSimGo_Click(object sender, EventArgs e)
{
if (m_radioUseService.Checked)
{
if (MessageBox.Show("Individual plugin results and results for each stage are unavailable when using the pGina service. Continue?",
"Warning", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
return;
ResetSimUI();
DoServiceClientSimulation();
}
else
{
if (MessageBox.Show("Continuing will save all pending changes in configuration, do you want to continue?",
"Warning", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
{
return;
}
pGina.Shared.Logging.InProcAppender.AddListener(SimLogHandler);
SaveSettings();
ResetSimUI();
DoInternalSimulation();
pGina.Shared.Logging.InProcAppender.RemoveListener(SimLogHandler);
}
}
private void DoServiceClientSimulation()
{
ILog abstractionLogger = LogManager.GetLogger("Abstractions");
LibraryLogging.AddListener(LibraryLogging.Level.Debug, abstractionLogger.DebugFormat);
LibraryLogging.AddListener(LibraryLogging.Level.Error, abstractionLogger.ErrorFormat);
LibraryLogging.AddListener(LibraryLogging.Level.Info, abstractionLogger.InfoFormat);
LibraryLogging.AddListener(LibraryLogging.Level.Warn, abstractionLogger.WarnFormat);
try
{
string pipeName = Core.Settings.Get.ServicePipeName;
PipeClient client = new PipeClient(pipeName);
client.Start(
(Func<IDictionary<string, object>, IDictionary<string, object>>)
((m) =>
{
MessageType type = (MessageType)Enum.ToObject(typeof(MessageType), m["MessageType"]);
// Acceptable server responses are Hello, and LoginResponse
switch (type)
{
case MessageType.Hello:
// Send our login request
LoginRequestMessage requestMsg = new LoginRequestMessage()
{
Username = m_username.Text,
Password = <PASSWORD>,
};
return requestMsg.ToDict();
case MessageType.LoginResponse:
LoginResponseMessage responseMsg = new LoginResponseMessage(m);
m_usernameResult.Text = responseMsg.Username;
m_passwordResult.Text = responseMsg.Password;
m_domainResult.Text = responseMsg.Domain;
SetStageStatus(this.simFinalResultPB, responseMsg.Result);
if (responseMsg.Message != null)
{
this.simFinalResultMessageTB.Text = responseMsg.Message;
}
// Respond with a disconnect, we're done
return (new EmptyMessage(MessageType.Disconnect).ToDict());
case MessageType.Ack: // Ack to our disconnect
return null;
default:
m_logger.ErrorFormat("Server responded with invalid message type: {0}", type);
return null;
}
}),
(new EmptyMessage(MessageType.Hello)).ToDict(), 1000);
}
catch (Exception e)
{
m_logger.ErrorFormat("Error during service client simulation: {0}", e);
}
LibraryLogging.RemoveListener(LibraryLogging.Level.Debug, abstractionLogger.DebugFormat);
LibraryLogging.RemoveListener(LibraryLogging.Level.Error, abstractionLogger.ErrorFormat);
LibraryLogging.RemoveListener(LibraryLogging.Level.Info, abstractionLogger.InfoFormat);
LibraryLogging.RemoveListener(LibraryLogging.Level.Warn, abstractionLogger.WarnFormat);
}
private void DoInternalSimulation()
{
Color successColor = Color.FromArgb(150, 255, 150);
Color failColor = Color.FromArgb(255, 150, 150);
PluginDriver sessionDriver = new PluginDriver();
sessionDriver.UserInformation.Username = m_username.Text;
sessionDriver.UserInformation.Password = <PASSWORD>;
this.simPluginResultsListView.Items.Clear();
// Execute the login process
BooleanResult finalResult = sessionDriver.PerformLoginProcess();
// Get the authentication results
PluginActivityInformation actInfo = sessionDriver.SessionProperties.GetTrackedSingle<PluginActivityInformation>();
bool authed = false;
foreach (Guid uuid in actInfo.GetAuthenticationPlugins())
{
BooleanResult result = actInfo.GetAuthenticationResult(uuid);
IPluginAuthentication plugin = actInfo.LoadedAuthenticationPlugins.Find(
delegate(IPluginAuthentication p) { return uuid == p.Uuid; }
);
ListViewItem item = new ListViewItem(
new string[] { "Authentication", plugin.Name, result.Success.ToString(), result.Message });
if (result.Success) item.BackColor = successColor;
else item.BackColor = failColor;
this.simPluginResultsListView.Items.Add(item);
authed = authed || result.Success;
}
// Get the authorization results
bool authzed = true; // Default is true
foreach (Guid uuid in actInfo.GetAuthorizationPlugins())
{
BooleanResult result = actInfo.GetAuthorizationResult(uuid);
IPluginAuthorization plugin = actInfo.LoadedAuthorizationPlugins.Find(
delegate(IPluginAuthorization p) { return uuid == p.Uuid; }
);
ListViewItem item = new ListViewItem(
new string[] { "Authorization", plugin.Name, result.Success.ToString(), result.Message });
if (result.Success) item.BackColor = successColor;
else item.BackColor = failColor;
this.simPluginResultsListView.Items.Add(item);
authzed = authzed && result.Success;
}
// Get the gateway results
bool gatewayed = true;
foreach (Guid uuid in actInfo.GetGatewayPlugins())
{
BooleanResult result = actInfo.GetGatewayResult(uuid);
IPluginAuthenticationGateway plugin = actInfo.LoadedAuthenticationGatewayPlugins.Find(
delegate(IPluginAuthenticationGateway p) { return uuid == p.Uuid; });
ListViewItem item = new ListViewItem(
new string[] { "Gateway", plugin.Name, result.Success.ToString(), result.Message });
if (result.Success) item.BackColor = successColor;
else item.BackColor = failColor;
this.simPluginResultsListView.Items.Add(item);
gatewayed = gatewayed && result.Success;
}
this.simPluginResultsListView.AutoResizeColumn(0, ColumnHeaderAutoResizeStyle.ColumnContent);
this.simPluginResultsListView.AutoResizeColumn(1, ColumnHeaderAutoResizeStyle.ColumnContent);
this.simPluginResultsListView.AutoResizeColumn(2, ColumnHeaderAutoResizeStyle.HeaderSize);
this.simPluginResultsListView.AutoResizeColumn(3, ColumnHeaderAutoResizeStyle.ColumnContent);
// Update stage results
SetStageStatus(this.simAuthResultPB, authed);
SetStageStatus(this.simAuthzResultPB, authzed);
SetStageStatus(this.simGatewayResultPB, gatewayed);
m_usernameResult.Text = sessionDriver.UserInformation.Username;
m_domainResult.Text = sessionDriver.UserInformation.Domain;
m_passwordResult.Text = <PASSWORD>Information.<PASSWORD>;
SetStageStatus(this.simFinalResultPB, finalResult.Success);
this.simFinalResultMessageTB.Text = finalResult.Message;
// Display final list of groups
this.simResultLocalGroupsTB.Text =
string.Join(", ", sessionDriver.UserInformation.Groups.Select(groupInfo => groupInfo.Name) );
}
private void SetStageStatus(PictureBox pb, bool success)
{
if (success)
pb.Image = Configuration.Properties.Resources.greenCheckMark;
else
pb.Image = Configuration.Properties.Resources.redx;
}
private void ResetStageStatus()
{
this.simAuthResultPB.Image = Configuration.Properties.Resources.grayBar;
this.simAuthzResultPB.Image = Configuration.Properties.Resources.grayBar;
this.simGatewayResultPB.Image = Configuration.Properties.Resources.grayBar;
this.simFinalResultPB.Image = Configuration.Properties.Resources.grayBar;
}
private void btnImageBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.FileName = m_tileImageTxt.Text;
ofd.Filter = "Bitmap Files (.bmp)|*.bmp|All Files (*.*)|*.*";
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
m_tileImageTxt.Text = ofd.FileName;
LoadTileImagePreview();
}
}
private void m_tabs_Selected(object sender, TabControlEventArgs e)
{
if (e.TabPage == m_simTab)
{
try
{
if (String.IsNullOrEmpty(m_tileImageTxt.Text.Trim()))
{
m_tileImage.Image = pGina.Configuration.Properties.Resources.pginalogo;
}
else
{
m_tileImage.Image = new Bitmap(m_tileImageTxt.Text);
}
}
catch (Exception)
{
m_tileImage.Image = pGina.Configuration.Properties.Resources.pginalogo;
}
ResetStageStatus();
}
}
private void m_lblAuthorizeResult_TextChanged(object sender, EventArgs e)
{
HandleLabelTextChange((Label)sender);
}
private void m_lblGatewayResult_TextChanged(object sender, EventArgs e)
{
HandleLabelTextChange((Label)sender);
}
private void pluginsDG_DoubleClick(object sender, EventArgs e)
{
configureButton_Click(sender, e);
}
private void serviceStartBtn_Click(object sender, EventArgs e)
{
if (m_pGinaServiceController.Status == ServiceControllerStatus.Stopped)
{
// Disable this right away, otherwise it isn't disabled until the
// service controller shows it as "Start pending"
serviceStartBtn.Enabled = false;
try
{
m_pGinaServiceController.Start();
}
catch (Exception ex)
{
MessageBox.Show(String.Format("{0}\nA dependent service is disabled?", ex.Message), "Can't start pGina service", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
UpdateServiceStatus();
}
}
private void serviceStopBtn_Click(object sender, EventArgs e)
{
if (m_pGinaServiceController.Status == ServiceControllerStatus.Running)
{
// Disable this right away, otherwise it isn't disabled until the
// service controller shows it as "Stop pending"
serviceStopBtn.Enabled = false;
try
{
m_pGinaServiceController.Stop();
}
catch (Exception ex)
{
MessageBox.Show(String.Format("{0}", ex.Message), "Can't stop pGina service", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
UpdateServiceStatus();
}
}
void m_serviceTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
UpdateServiceStatus();
}
private void cpRegisterBtn_Click(object sender, EventArgs e)
{
pGina.CredentialProvider.Registration.CredProviderManager manager =
pGina.CredentialProvider.Registration.CredProviderManager.GetManager();
try
{
if (manager.Registered())
manager.Uninstall();
else
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.Description = "Select the folder containing Credential Provider/GINA DLL." +
" Optionally, the DLL(s) may be contained in subfolders named 'x64' " +
" and 'Win32' for 64 and 32-bit DLLs.";
dlg.SelectedPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (dlg.ShowDialog() == DialogResult.OK)
{
manager.CpInfo.Path = dlg.SelectedPath;
manager.Install();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
this.UpdateCpStatus();
}
private void cpEnableDisableBtn_Click(object sender, EventArgs e)
{
pGina.CredentialProvider.Registration.CredProviderManager manager =
pGina.CredentialProvider.Registration.CredProviderManager.GetManager();
try
{
if (manager.Registered())
{
if (manager.Enabled())
manager.Disable();
else
manager.Enable();
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
this.UpdateCpStatus();
}
private void btnGinaBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "DLL Files (*.dll)|*.dll";
ofd.Multiselect = false;
ofd.Title = "Select GINA to be chained";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
m_txtGinaChain.Text = ofd.FileName;
}
}
private void SaveGinaSettings()
{
Settings.Get.ChainedGinaPath = m_txtGinaChain.Text;
Settings.Get.EnableSpecialActionButton = chkSpecialButton.Checked;
if (radioShutdown.Checked)
Settings.Get.SpecialAction = "Shutdown";
else if (radioRestart.Checked)
Settings.Get.SpecialAction = "Restart";
else if (radioSleep.Checked)
Settings.Get.SpecialAction = "Sleep";
else if (radioHibernate.Checked)
Settings.Get.SpecialAction = "Hibernate";
}
private void SaveCpSettings()
{
List<CredProv> credProvs = (List<CredProv>)dgvCredProvFilter.DataSource;
CredProvFilterConfig.SaveFilterSettings(credProvs);
}
private void chkSpecialButton_CheckedChanged(object sender, EventArgs e)
{
radioSleep.Enabled = chkSpecialButton.Checked;
radioShutdown.Enabled = chkSpecialButton.Checked;
radioRestart.Enabled = chkSpecialButton.Checked;
radioHibernate.Enabled = chkSpecialButton.Checked;
}
private void showTextResultPasswordCB_CheckedChanged(object sender, EventArgs e)
{
this.m_passwordResult.UseSystemPasswordChar = ! this.showTextResultPasswordCB.Checked;
}
private void viewLogBtn_Click(object sender, EventArgs e)
{
this.logWindow.Visible = true;
}
private void enableMotdCB_CheckedChanged(object sender, EventArgs e)
{
this.motdTB.Enabled = this.enableMotdCB.Checked;
}
private void Btn_help(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation.html");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using pGina.Shared.Settings;
using log4net;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace pGina.Plugin.Cbits
{
class Settings
{
private static dynamic m_settings = new pGinaDynamicSettings(PluginImpl.PluginUuid);
private static ILog m_logger = LogManager.GetLogger("CbitsSettings");
private const string url = "https://pgina.cbits.net/api/v1/auth/";
private static string DEFAULT_DOMAIN = "cbits.net";
static Settings()
{
try
{
m_settings.SetDefault("Domain", @DEFAULT_DOMAIN);
}
catch (Exception)
{
// do nothing
}
}
public static dynamic Store
{
get { return m_settings; }
}
public static string resolveSettings()
{
string domain = _urlByEnvVar();
if (domain == null)
{
// try to get URL from DNS
try
{
domain = m_settings.Domain;
m_logger.DebugFormat("Login domain from GinaSettings: {0}", domain);
}
catch (KeyNotFoundException)
{
domain = DEFAULT_DOMAIN;
m_logger.DebugFormat("Default domain server url: {0}", domain);
}
}
else
{
m_logger.DebugFormat("Default domain from ENVVar: {0}", domain);
_persist(domain);
}
return url + domain;
}
private static void _persist(string domain)
{
try
{
m_settings.SetSetting("Domain", domain);
}
catch (Exception e)
{
m_logger.ErrorFormat("Cannot save settings: {0}", e.ToString());
}
}
/*
* returns CBITSLOGINDOMAIN environment variable content if set, otherwise null.
* Setting by environment variable allows easy override of login endpoint address.
*/
private static string _urlByEnvVar()
{
try
{
return Environment.GetEnvironmentVariable("CBITSLOGINDOMAIN");
}
catch (Exception)
{
return null;
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using log4net;
using pGina.Shared.Settings;
namespace pGina.Plugin.UsernameMod.Rules
{
public enum Stage { Authentication, Authorization, Gateway };
/// <summary>
/// Represents an action to take on the username.
/// </summary>
public interface IUsernameRule
{
Stage stage { get; set; }
/// <summary>
/// Generates a string representation of the rule.
/// </summary>
/// <returns></returns>
string save();
}
/// <summary>
/// IModifyRule represents a rule that will modify the username.
/// </summary>
public interface IModifyRule : IUsernameRule
{
string modify(string username);
}
/// <summary>
/// IMatchRule represents a rule that will match against the username
/// </summary>
public interface IMatchRule : IUsernameRule
{
bool match(string username);
}
/// <summary>
/// AppendUsername will append the specified value to the username.
/// </summary>
public class AppendUsername : IModifyRule
{
public Stage stage { get; set; }
public string toAppend { get; protected set; }
public AppendUsername(Stage stage, string toAppend)
{
this.stage = stage;
this.toAppend = toAppend;
}
public string modify(string username)
{
return string.Format("{0}{1}", username, toAppend);
}
public override string ToString()
{
return string.Format("[{0}] The username will be appended with \"{1}\"", stage, toAppend);
}
public string save()
{
return string.Format("{0}\n{1}\n{2}", stage, "Append", toAppend);
}
}
/// <summary>
/// PrependUsername will prepend the specified value to the username.
/// </summary>
public class PrependUsername : IModifyRule
{
public Stage stage { get; set; }
public string toPrepend { get; protected set; }
public PrependUsername(Stage stage, string toPrepend)
{
this.stage = stage;
this.toPrepend = toPrepend;
}
public string modify(string username)
{
return string.Format("{0}{1}", toPrepend, username);
}
public override string ToString()
{
return string.Format("[{0}] The username will be prepended with \"{1}\"", stage, toPrepend);
}
public string save()
{
return string.Format("{0}\n{1}\n{2}", stage, "Prepend", toPrepend);
}
}
/// <summary>
/// TruncateUsername will truncate the username to the specified number of characters if it is over.
/// </summary>
public class TruncateUsername : IModifyRule
{
public Stage stage { get; set; }
public int numChars { get; protected set; }
public TruncateUsername(Stage stage, int numChars)
{
this.stage = stage;
this.numChars = numChars;
}
public TruncateUsername(Stage stage, string numChars)
{
this.stage = stage;
try
{
this.numChars = Convert.ToInt32(numChars);
}
catch (FormatException e)
{
throw new UsernameModPluginException("The number of characters must be an integer value.", e);
}
}
public string modify(string username)
{
if(username.Length >= numChars)
return username.Substring(0, numChars);
return username;
}
public override string ToString()
{
return string.Format("[{0}] The username will be truncated to {1} characters.", stage, numChars);
}
public string save()
{
return string.Format("{0}\n{1}\n{2}", stage, "Truncate", numChars);
}
}
/// <summary>
/// ReplaceUsername will replace the specified characters with a specified string.
/// </summary>
public class ReplaceUsername : IModifyRule
{
public Stage stage { get; set; }
public string charsToReplace { get; protected set; }
public string replaceWith { get; protected set; }
public ReplaceUsername(Stage stage, string toReplace, string toReplaceWith)
{
this.stage = stage;
charsToReplace = toReplace;
replaceWith = toReplaceWith;
}
public string modify(string username)
{
string modifiedUsername = username;
foreach (char c in charsToReplace)
{
modifiedUsername = modifiedUsername.Replace(c.ToString(), replaceWith);
}
return modifiedUsername;
}
public override string ToString()
{
return string.Format("[{0}] Each character in \"{1}\" will be replaced with \"{2}\"", stage, charsToReplace, replaceWith);
}
public string save()
{
return string.Format("{0}\n{1}\n{2}\n{3}", stage, "Replace", charsToReplace, replaceWith);
}
}
/// <summary>
/// RegexReplaceUsername will take a regex pattern and replace all matches with a specified string.
/// </summary>
public class RegexReplaceUsername : IModifyRule
{
public Stage stage { get; set; }
public string pattern { get; protected set; }
public string replaceWith { get; protected set; }
public RegexReplaceUsername(Stage stage, string regexPattern, string replaceWith)
{
this.stage = stage;
this.pattern = regexPattern;
this.replaceWith = replaceWith;
}
public string modify(string username)
{
return Regex.Replace(username, pattern, replaceWith);
}
public override string ToString()
{
return string.Format("[{0}] Each regex match for \"{1}\" will be replaced with \"{2}\"", stage, pattern, replaceWith);
}
public string save()
{
return string.Format("{0}\n{1}\n{2}\n{3}", stage, "RegEx Replace", pattern, replaceWith);
}
}
/// <summary>
/// MatchRegex will match against a regular expression.
/// </summary>
public class MatchRegex : IMatchRule
{
public Stage stage { get; set; }
public string pattern { get; protected set; }
public MatchRegex(Stage stage, string pattern)
{
this.stage = stage;
this.pattern = pattern;
}
public bool match(string username)
{
return Regex.Match(username, pattern).Success;
}
public override string ToString()
{
return string.Format("[{0}] Username must match the regex pattern \"{1}\"", stage, pattern);
}
public string save()
{
return string.Format("{0}\n{1}\n{2}", stage, "Match", pattern);
}
}
class ListOfRules
{
private static dynamic m_settings = new pGinaDynamicSettings(UsernameModPlugin.SimpleUuid);
public List<IUsernameRule> list { get; private set; }
private ILog m_logger = LogManager.GetLogger("UsernameModPlugin");
public static string[] Rules = { "Append", "Prepend", "Truncate", "Replace", "RegEx Replace", "Match" };
public ListOfRules()
{
//Read registry key, load rules
m_settings.SetDefault("rules", new string[]{});
list = new List<IUsernameRule>();
}
/// <summary>
/// Saves the list of rules to the registry.
/// </summary>
public void Save()
{
//Clear existing rules
m_settings.rules = new string[] { };
//Create new string array of rules
List<string> rules = new List<string>();
foreach (IUsernameRule rule in list){
string srule = rule.save();
m_logger.DebugFormat("Saving rule {0} as \"{1}\"", rule.ToString(), srule);
rules.Add(rule.save());
}
m_settings.rules = rules.ToArray();
}
/// <summary>
/// Loads the rules from the register into list.
/// </summary>
public void Load()
{
string[] rules = (string[])m_settings.rules;
m_logger.DebugFormat("Loaded rules from registry. {0} lines.", rules.Length);
try
{
for (int k = 0; k < rules.Length; k++)
{
m_logger.DebugFormat("Rule read: {0}", rules[k]);
string[] srule = rules[k].Split('\n');
String stage = srule[0];
string action = srule[1];
string val1 = srule[2];
string val2 = null;
if (srule.Length > 3)
val2 = srule[3];
IUsernameRule rule = CreateRule(stage, action, val1, val2);
m_logger.DebugFormat("Rule created: {0}", rule);
list.Add(rule);
}
}
catch (Exception e)
{
throw new UsernameModPluginException("Unable to load rules from registry.", e);
}
}
/// <summary>
/// Adds a rule to the list, putting it at the end of the stage
/// </summary>
/// <param name="rule"></param>
public void Add(IUsernameRule rule)
{
//Add the rule as the last item for the gateway
for (int k = 0; k < list.Count; k++)
{
if (rule.stage.CompareTo(list[k].stage) < 0)
{
list.Insert(k, rule);
return;
}
}
list.Add(rule);
}
/// <summary>
/// Moves the rule at the specified index up one (e.g. index=2 becomes index=1).
///
/// Will not move an item if it's at the top, or if it will be above a rule with an earlier step.
/// (e.g. A gateway rule can not be above a authorization rule)
/// </summary>
/// <param name="index"></param>
/// <returns>True if the move was successful</returns>
public bool MoveUp(int index)
{
IUsernameRule rule = list.ElementAt(index);
if(index > 0){
if (list.ElementAt(index - 1).stage == rule.stage)
{
list.RemoveAt(index);
list.Insert(index - 1, rule);
return true;
}
}
return false;
}
/// <summary>
/// Moves the rule at the specified index down one (e.g. index=2 becomes index=3).
///
/// Will not move an item if it's at the bottom, or if it will be below a rule with a later step.
/// (e.g. An authorization rule will not move below a gateway rule)
/// </summary>
/// <param name="index"></param>
/// <returns>True if the move was successful</returns>
public bool MoveDown(int index)
{
IUsernameRule rule = list.ElementAt(index);
if (index < list.Count - 1)
{
if (list.ElementAt(index + 1).stage == rule.stage)
{
list.RemoveAt(index);
list.Insert(index + 1, rule);
return true;
}
}
return false;
}
/// <summary>
/// Removes the rule at the specified index.
/// </summary>
/// <param name="index"></param>
public void remove(int index)
{
list.RemoveAt(index);
}
/// <summary>
/// Creates a IUsernameRule based on the string representation of the stage, action, and values.
/// </summary>
/// <param name="stage"></param>
/// <param name="action"></param>
/// <param name="val1"></param>
/// <param name="val2"></param>
/// <returns></returns>
public static IUsernameRule CreateRule(string stage, string action, string val1, string val2)
{
Stage estage;
switch (stage)
{
case "Authorization":
estage = Stage.Authorization;
break;
case "Authentication":
estage = Stage.Authentication;
break;
case "Gateway":
estage = Stage.Gateway;
break;
default:
throw new UsernameModPluginException("Invalid stage.");
}
return CreateRule(estage, action, val1, val2);
}
/// <summary>
/// Creates an IUsernameRule based on the Stage value, and string representation of the rule
/// </summary>
/// <param name="stage"></param>
/// <param name="action"></param>
/// <param name="val1"></param>
/// <param name="val2"></param>
/// <returns></returns>
public static IUsernameRule CreateRule(Stage stage, string action, string val1, string val2)
{ //Rules = { "Append", "Prepend", "Truncate", "Replace", "RegEx Replace", "Match" };
switch (action)
{
case "Append":
return new AppendUsername(stage, val1);
case "Prepend":
return new PrependUsername(stage, val1);
case "Truncate":
return new TruncateUsername(stage, val1);
case "Replace":
return new ReplaceUsername(stage, val1, val2);
case "RegEx Replace":
return new RegexReplaceUsername(stage, val1, val2);
case "Match":
return new MatchRegex(stage, val1);
default:
throw new UsernameModPluginException(string.Format("Unable to generate rule from \"{0}/{1}/{2}/{3}\"", stage, action, val1, val2));
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Reflection;
using System.ComponentModel;
using Microsoft.Win32;
namespace Abstractions.Settings
{
public class DynamicSetting : DynamicObject
{
private object m_value = null;
private string m_name = null;
public DynamicSetting(string name, object value)
{
m_name = name;
m_value = value;
}
public object RawValue
{
get { return m_value; }
set { m_value = value; }
}
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var descr = TypeDescriptor.GetProperties(m_value);
if (descr[binder.Name] != null)
{
result = descr[binder.Name].GetValue(m_value);
return true;
}
result = null;
return false;
}
public override string ToString()
{
if (m_value != null)
{
return m_value.ToString();
}
return base.ToString();
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
result = null;
if (m_value == null)
return true;
// 1:1 conversion
Type ourType = m_value.GetType();
if (binder.Type == ourType)
{
result = m_value;
return true;
}
// If caller wants a bool we have to do a little
// conversion, as there is no native Reg bool type,
// instead it saves them as strings.
if (binder.Type == typeof(bool))
{
if(ourType == typeof(string))
{
result = bool.Parse((string)m_value);
return true;
}
if (ourType == typeof(Int32))
{
result = (((int)m_value) != 0);
return true;
}
}
// We could potentially offer some standard conversions here? For now,
// we just fail.
return false;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
Type ourType = m_value.GetType();
try
{
result = ourType.InvokeMember(
binder.Name,
BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
null, m_value, args);
return true;
}
catch
{
result = null;
return false;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace pGina.Plugin.HttpAuth
{
public partial class Configuration : Form
{
public Configuration()
{
InitializeComponent();
SettingsToUi();
}
public void SettingsToUi()
{
Loginserver_textBox.Text = Settings.Store.Loginserver;
}
private void Form_Load(object sender, EventArgs e)
{
ToolTip toolTip1 = new ToolTip();
toolTip1.AutoPopDelay = 10000;
toolTip1.InitialDelay = 0;
toolTip1.ReshowDelay = 0;
toolTip1.ShowAlways = true;
toolTip1.SetToolTip(this.Loginserver_textBox, "The Authentication server address");
}
public bool UiToSettings()
{
if (String.IsNullOrEmpty(Loginserver_textBox.Text))
{
MessageBox.Show(this, "Loginserver is empty", "Loginserver", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
Settings.Store.Loginserver = Loginserver_textBox.Text;
return true;
}
private void Btn_Save(object sender, EventArgs e)
{
if (UiToSettings())
this.Close();
}
private void Btn_Cancel(object sender, EventArgs e)
{
this.Close();
}
private void Btn_help(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/httpauth.html");
}
}
}
<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <Windows.h>
#include "Gina.h"
#include "GinaWrapper.h"
#include "Winlogon.h"
#include "WinlogonProxy.h"
namespace pGina
{
namespace GINA
{
// Gina implementation that loads another gina dll that hooks
// (and stubs) msgina.dll for customization (ui etc). We are both
// a Gina() interface (for winlogon) and a WinlogonProxy (for our
// chained GINA).
class GinaChain : public Gina, public WinlogonProxy
{
public:
GinaChain(WinlogonInterface *pWinLogonIface);
virtual ~GinaChain();
// Queries from winlogon
virtual bool IsLockOk();
virtual bool IsLogoffOk();
virtual bool GetConsoleSwitchCredentials(PVOID pCredInfo);
// Notifications from winlogon
virtual void ReconnectNotify();
virtual void DisconnectNotify();
virtual void Logoff();
virtual bool ScreenSaverNotify(BOOL * pSecure);
virtual void Shutdown(DWORD ShutdownType);
// Notices/Status messages
virtual void DisplaySASNotice();
virtual void DisplayLockedNotice();
virtual bool DisplayStatusMessage(HDESK hDesktop, DWORD dwOptions, PWSTR pTitle, PWSTR pMessage);
virtual bool GetStatusMessage(DWORD * pdwOptions, PWSTR pMessage, DWORD dwBufferSize);
virtual bool RemoveStatusMessage();
// SAS handling
virtual int LoggedOutSAS(DWORD dwSasType, PLUID pAuthenticationId, PSID pLogonSid, PDWORD pdwOptions,
PHANDLE phToken, PWLX_MPR_NOTIFY_INFO pMprNotifyInfo, PVOID *pProfile);
virtual int LoggedOnSAS(DWORD dwSasType, PVOID pReserved);
virtual int WkstaLockedSAS(DWORD dwSasType);
// Things to do when winlogon says to...
virtual bool ActivateUserShell(PWSTR pszDesktopName, PWSTR pszMprLogonScript, PVOID pEnvironment);
virtual bool StartApplication(PWSTR pszDesktopName, PVOID pEnvironment, PWSTR pszCmdLine);
virtual bool NetworkProviderLoad(PWLX_MPR_NOTIFY_INFO pNprNotifyInfo);
// Winlogon callbacks that we hook
virtual int WlxDialogBoxParam(HANDLE hInst, LPWSTR lpszTemplate, HWND hwndOwner, DLGPROC dlgprc, LPARAM dwInitParam);
private:
GinaWrapper * m_wrappedGina;
bool m_passthru;
// Check for auto-logon registry settings.
bool IsAutoLogonEnabled();
};
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Abstractions.Logging
{
public static class LibraryLogging
{
public delegate void MessageHandler(string message, params object[] args);
public enum Level
{
Info,
Debug,
Warn,
Error
}
private static object s_mutex = new object();
private static event MessageHandler InfoEvent;
private static event MessageHandler DebugEvent;
private static event MessageHandler WarnEvent;
private static event MessageHandler ErrorEvent;
public static void Info(string message, params object[] args)
{
if(InfoEvent != null)
InfoEvent(message, args);
}
public static void Debug(string message, params object[] args)
{
if (DebugEvent != null)
DebugEvent(message, args);
}
public static void Warn(string message, params object[] args)
{
if (WarnEvent != null)
WarnEvent(message, args);
}
public static void Error(string message, params object[] args)
{
if (ErrorEvent != null)
ErrorEvent(message, args);
}
public static void AddListener(Level level, MessageHandler handler)
{
lock(s_mutex)
{
switch(level)
{
case Level.Info:
InfoEvent += handler;
break;
case Level.Debug:
DebugEvent += handler;
break;
case Level.Warn:
WarnEvent += handler;
break;
case Level.Error:
ErrorEvent += handler;
break;
}
}
}
public static void RemoveListener(Level level, MessageHandler handler)
{
lock(s_mutex)
{
switch(level)
{
case Level.Info:
InfoEvent -= handler;
break;
case Level.Debug:
DebugEvent -= handler;
break;
case Level.Warn:
WarnEvent -= handler;
break;
case Level.Error:
ErrorEvent -= handler;
break;
}
}
}
}
}
<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <Windows.h>
#include <WinWlx.h>
#include "Winlogon.h"
namespace pGina
{
namespace GINA
{
// This WinlogonInterface is useful when you want to intercept a subset of
// the winlogon interface calls made by a stubbed/hooked gina. Any you
// don't implement just get called straight through to the 'actual' iface
// provided. Just inherit from this class, be sure to call the protected
// constructor with the actual iface, then implement any of the WinlogonInterface
// methods you care to be involved in.
class WinlogonProxy : public WinlogonInterface
{
public:
virtual void WlxUseCtrlAltDel() { m_iface->WlxUseCtrlAltDel(); }
virtual void WlxSetContextPointer(void *newContext) { m_iface->WlxSetContextPointer(newContext); }
virtual void WlxSasNotify(DWORD sas) { m_iface->WlxSasNotify(sas); }
virtual bool WlxSetTimeout(DWORD newTimeout) { return m_iface->WlxSetTimeout(newTimeout); }
virtual int WlxAssignShellProtection(HANDLE token, HANDLE process, HANDLE thread) { return m_iface->WlxAssignShellProtection(token, process, thread); }
virtual int WlxMessageBox(HWND owner, LPWSTR text, LPWSTR title, UINT style) { return m_iface->WlxMessageBox(owner, text, title, style); }
virtual int WlxDialogBox(HANDLE hInst, LPWSTR lpszTemplate, HWND hwndOwner, DLGPROC dlgprc) { return m_iface->WlxDialogBox(hInst, lpszTemplate, hwndOwner, dlgprc); }
virtual int WlxDialogBoxParam(HANDLE hInst, LPWSTR lpszTemplate, HWND hwndOwner, DLGPROC dlgprc, LPARAM dwInitParam) { return m_iface->WlxDialogBoxParam(hInst, lpszTemplate, hwndOwner, dlgprc, dwInitParam); }
virtual int WlxDialogBoxIndirect(HANDLE hInst, LPCDLGTEMPLATE hDialogTemplate, HWND hwndOwner, DLGPROC dlgprc) { return m_iface->WlxDialogBoxIndirect(hInst, hDialogTemplate, hwndOwner, dlgprc); }
virtual int WlxDialogBoxIndirectParam(HANDLE hInst, LPCDLGTEMPLATE hDialogTemplate, HWND hwndOwner, DLGPROC dlgprc, LPARAM dwInitParam) { return m_iface->WlxDialogBoxIndirectParam(hInst, hDialogTemplate, hwndOwner, dlgprc, dwInitParam); }
virtual int WlxSwitchDesktopToUser() { return m_iface->WlxSwitchDesktopToUser(); }
virtual int WlxSwitchDesktopToWinlogon() { return m_iface->WlxSwitchDesktopToWinlogon(); }
virtual int WlxChangePasswordNotify(PWLX_MPR_NOTIFY_INFO pMprInfo, DWORD dwChangeInfo) { return m_iface->WlxChangePasswordNotify(pMprInfo, dwChangeInfo); }
virtual bool WlxGetSourceDesktop(PWLX_DESKTOP *ppDesktop) { return m_iface->WlxGetSourceDesktop(ppDesktop); }
virtual bool WlxSetReturnDesktop(PWLX_DESKTOP pDesktop) { return m_iface->WlxSetReturnDesktop(pDesktop); }
virtual bool WlxCreateUserDesktop(HANDLE hToken, DWORD Flags, PWSTR pszDesktopName, PWLX_DESKTOP *ppDesktop) { return m_iface->WlxCreateUserDesktop(hToken, Flags, pszDesktopName, ppDesktop); }
virtual int WlxChangePasswordNotifyEx(PWLX_MPR_NOTIFY_INFO pMprInfo, DWORD dwChangeInfo, PWSTR ProviderName, PVOID Reserved) { return m_iface->WlxChangePasswordNotifyEx(pMprInfo, dwChangeInfo, ProviderName, Reserved); }
virtual bool WlxCloseUserDesktop(PWLX_DESKTOP pDesktop, HANDLE hToken) { return m_iface->WlxCloseUserDesktop(pDesktop, hToken); }
virtual bool WlxSetOption(DWORD Option, ULONG_PTR Value, ULONG_PTR *OldValue) { return m_iface->WlxSetOption(Option, Value, OldValue); }
virtual bool WlxGetOption(DWORD Option, ULONG_PTR *Value) { return m_iface->WlxGetOption(Option, Value); }
virtual void WlxWin31Migrate() { m_iface->WlxWin31Migrate(); }
virtual bool WlxQueryClientCredentials(PWLX_CLIENT_CREDENTIALS_INFO_V1_0 pCred) { return m_iface->WlxQueryClientCredentials(pCred); }
virtual bool WlxQueryInetConnectorCredentials(PWLX_CLIENT_CREDENTIALS_INFO_V1_0 pCred) { return m_iface->WlxQueryInetConnectorCredentials(pCred); }
virtual bool WlxDisconnect() { return m_iface->WlxDisconnect(); }
virtual int WlxQueryTerminalServicesData(PWLX_TERMINAL_SERVICES_DATA pTSData, WCHAR *UserName, WCHAR *Domain) { return m_iface->WlxQueryTerminalServicesData(pTSData, UserName, Domain); }
virtual int WlxQueryConsoleSwitchCredentials(PWLX_CONSOLESWITCH_CREDENTIALS_INFO_V1_0 pCred) { return m_iface->WlxQueryConsoleSwitchCredentials(pCred); }
virtual bool WlxQueryTsLogonCredentials(PWLX_CLIENT_CREDENTIALS_INFO_V2_0 pCred) { return m_iface->WlxQueryTsLogonCredentials(pCred); }
protected:
WinlogonProxy(WinlogonInterface *iface) :
m_iface(iface) {}
private:
WinlogonInterface * m_iface;
};
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace Abstractions.Helpers
{
public class ObjectCache<KeyType, ValueType> : IDisposable
{
protected class CacheEntry
{
public KeyType Key;
public ValueType Value;
}
protected Dictionary<KeyType, CacheEntry> m_cache = new Dictionary<KeyType, CacheEntry>();
public ObjectCache()
{
}
public List<KeyType> GetAll()
{
List<KeyType> ret = new List<KeyType>();
foreach (KeyValuePair<KeyType, CacheEntry> entry in m_cache)
{
ret.Add(entry.Key);
}
return ret;
}
protected virtual CacheEntry WrapValue(KeyType key, ValueType value)
{
return new CacheEntry()
{
Key = key,
Value = value,
};
}
public virtual void Add(KeyType key, ValueType value)
{
CacheEntry ce = WrapValue(key, value);
lock (m_cache)
{
if (m_cache.ContainsKey(key))
m_cache[key] = ce;
else
m_cache.Add(key, ce);
}
}
public virtual ValueType Get(KeyType key)
{
if (Exists(key))
return m_cache[key].Value;
return (ValueType)Activator.CreateInstance(typeof(ValueType));
}
public virtual void Remove(KeyType key)
{
lock (m_cache)
{
if (m_cache.ContainsKey(key))
{
m_cache.Remove(key);
}
}
}
public virtual bool Exists(KeyType key)
{
lock (m_cache)
{
return m_cache.ContainsKey(key);
}
}
private bool m_disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!m_disposed)
{
m_disposed = true;
if (disposing)
{
m_cache.Clear();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~ObjectCache()
{
Dispose(false);
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using pGina.Shared.Settings;
namespace pGina.Core
{
public static class Settings
{
public static dynamic s_settings = new pGinaDynamicSettings();
public static dynamic Get
{
get { return s_settings; }
}
public static void Init()
{
string curPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
s_settings.SetDefault("PluginDirectories", new string[] { string.Format("{0}\\Plugins", curPath) });
s_settings.SetDefault("ServicePipeName", "pGinaPipe");
s_settings.SetDefault("MaxClients", 25);
s_settings.SetDefault("TraceMsgTraffic", false);
s_settings.SetDefault("SessionHelperExe", "pGina.Service.SessionHelper.exe");
s_settings.SetDefault("EnableMotd", true);
s_settings.SetDefault("Motd", "pGina Version: %v");
s_settings.SetDefault("GinaPassthru", false);
s_settings.SetDefault("ChainedGinaPath", "MSGINA.DLL");
s_settings.SetDefault("EnableSpecialActionButton", false);
s_settings.SetDefault("SpecialAction", "Shutdown");
s_settings.SetDefault("ShowServiceStatusInLogonUi", true);
s_settings.SetDefault("notify_smtp", ""); //used in Abstractions.Windows.Networking
s_settings.SetDefault("notify_email", ""); //used in Abstractions.Windows.Networking
s_settings.SetDefault("notify_user", ""); //used in Abstractions.Windows.Networking
s_settings.SetDefaultEncryptedSetting("notify_pass", ""); //used in Abstractions.Windows.Networking
s_settings.SetDefault("notify_cred", false); //used in Abstractions.Windows.Networking
s_settings.SetDefault("notify_ssl", false); //used in Abstractions.Windows.Networking
s_settings.SetDefault("ntpservers", new string[] { "" });
s_settings.SetDefault("LastUsername", "");
s_settings.SetDefault("LastUsernameEnable", false);
s_settings.SetDefault("PreferLocalAuthentication", false);
s_settings.SetDefault("CredentialProviderFilters", new string[] { });
// Default setup is local machine plugin as enabled for auth and gateway
s_settings.SetDefault("IPluginAuthentication_Order", new string[] { "12FA152D-A2E3-4C8D-9535-5DCD49DFCB6D" });
s_settings.SetDefault("IPluginAuthenticationGateway_Order", new string[] { "12FA152D-A2E3-4C8D-9535-5DCD49DFCB6D" });
s_settings.SetDefault("12FA152D-A2E3-4C8D-9535-5DCD49DFCB6D",
(int) (Core.PluginLoader.State.AuthenticateEnabled | Core.PluginLoader.State.GatewayEnabled));
s_settings.SetDefault("UseOriginalUsernameInUnlockScenario", false);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using log4net;
/* This class conforms to the following RFCs:
* RFC 2865 - Remote Authentication Dial In User Service (RADIUS) - http://tools.ietf.org/html/rfc2865
* RFC 2866 - RADIUS Accounting - http://tools.ietf.org/html/rfc2866
*/
namespace pGina.Plugin.RADIUS
{
class RADIUSClient
{
public string[] servers { get; set; }
public int authenticationPort { get; set; }
public int accountingPort { get; set; }
public string sharedKey { get; set; } //Private shared key for server
public int timeout { get; set; } //timeout in ms
public int maxRetries { get; set; } //Number of times to retry sending packet
public string sessionId { get; set; } //SessionId is required for accounting
public Packet lastReceievedPacket { get; private set; } //Last packet received from server
public bool authenticated { get; private set; } //Whether username was successfully authenticated
public DateTime accountingStartTime { get; set; }
public byte[] NAS_IP_Address { get; set; }
public string NAS_Identifier { get; set; }
public string called_station_id { get; set; }
//identifier refers to the identifier number, unique for each new packet
private byte _id;
public byte identifier
{
get{ return _id++; }
set { _id = value; }
}
public string ipAddressRegex { get; set; }
private static Random r = new Random();
private ILog m_logger = LogManager.GetLogger("RADIUSPlugin");
public RADIUSClient(string[] servers, int authport, int acctingport, string sharedKey, string NAS_Id) :
this(servers, authport, acctingport, sharedKey, timeout: 3000, retry: 3, sessionId:null, NAS_IP_Address:null, NAS_Identifier: NAS_Id, called_station_id:null)
{
}
public RADIUSClient(string[] servers, int authport, int acctingport, string sharedKey, string sessionId, string NAS_Id) :
this(servers, authport, acctingport, sharedKey, timeout: 3000, retry: 3, sessionId: sessionId, NAS_IP_Address: null, NAS_Identifier: NAS_Id, called_station_id:null)
{
}
public RADIUSClient(string[] servers, int authport, int acctingport, string sharedKey,
int timeout, int retry, string sessionId, byte[] NAS_IP_Address, string NAS_Identifier, string called_station_id)
{
this.servers = servers;
this.authenticationPort = authport;
this.accountingPort = acctingport;
this.sharedKey = sharedKey;
this.timeout = timeout;
this.maxRetries = retry;
this.identifier = (byte)r.Next(Byte.MaxValue + 1);
this.sessionId = sessionId;
this.authenticated = false;
this.NAS_IP_Address = NAS_IP_Address;
this.NAS_Identifier = NAS_Identifier;
this.called_station_id = called_station_id;
}
//Connects to the RADIUS server and attempts to authenticate the specified user info
//Sets username value and authenticated members IFF successful
public bool Authenticate(string username, string password)
{
Packet authPacket = new Packet(Packet.Code.Access_Request, identifier, sharedKey);
authPacket.sharedKey = sharedKey;
authPacket.addAttribute(Packet.AttributeType.User_Name, username);
authPacket.addAttribute(Packet.AttributeType.User_Password, <PASSWORD>);
if(!String.IsNullOrEmpty(sessionId))
authPacket.addAttribute(Packet.AttributeType.Acct_Session_Id, sessionId);
if (String.IsNullOrEmpty(NAS_Identifier) && NAS_IP_Address == null)
throw new RADIUSException("A NAS_Identifier or NAS_IP_Address (or both) must be supplied.");
if(NAS_IP_Address != null)
authPacket.addAttribute(Packet.AttributeType.NAS_IP_Address, NAS_IP_Address);
if (!String.IsNullOrEmpty(NAS_Identifier))
authPacket.addAttribute(Packet.AttributeType.NAS_Identifier, NAS_Identifier);
if (!String.IsNullOrEmpty(called_station_id))
authPacket.addAttribute(Packet.AttributeType.Called_Station_Id, called_station_id);
m_logger.DebugFormat("Attempting to send {0} for user {1}", authPacket.code, username);
for (int retryCt = 0; retryCt <= maxRetries; retryCt++)
{
foreach (string server in servers)
{
UdpClient client = new UdpClient(server, authenticationPort);
client.Client.SendTimeout = timeout;
client.Client.ReceiveTimeout = timeout;
try
{
client.Send(authPacket.toBytes(), authPacket.length);
//Listen for response, since the server has been specified, we don't need to re-specify server
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] respBytes = client.Receive(ref RemoteIpEndPoint);
Packet responsePacket = new Packet(respBytes);
//Verify packet authenticator is correct
if (!responsePacket.verifyResponseAuthenticator(authPacket.authenticator, sharedKey))
throw new RADIUSException(String.Format("Received response to authentication with code: {0}, but an incorrect response authenticator was supplied.", responsePacket.code));
lastReceievedPacket = responsePacket;
client.Close();
m_logger.DebugFormat("Received authentication response: {0} for user {1}", responsePacket.code, username);
if (responsePacket.code == Packet.Code.Access_Accept)
{
this.authenticated = true;
return true;
}
else
return false;
}
//SocketException is thrown if the server does not respond by end of timeout
catch (SocketException se)
{
m_logger.DebugFormat("Authentication attempt {0}/{1} using {2} failed. Reason: {3}", retryCt + 1, maxRetries + 1, server, se.Message);
}
catch (Exception e)
{
throw new RADIUSException("Unexpected error while trying to authenticate.", e);
}
}
}
throw new RADIUSException(String.Format("No response from server(s) after {0} tries.", maxRetries + 1));
}
//Sends a start accounting request to the RADIUS server, returns true on acknowledge of request
public bool startAccounting(string username, Packet.Acct_Authentic authType)
{
//Create accounting request packet
Packet accountingRequest = new Packet(Packet.Code.Accounting_Request, identifier, sharedKey);
accountingRequest.addAttribute(Packet.AttributeType.User_Name, username);
accountingRequest.addAttribute(Packet.AttributeType.Acct_Status_Type, (int)Packet.Acct_Status_Type.Start);
if (String.IsNullOrEmpty(sessionId)) //Create new guid
sessionId = Guid.NewGuid().ToString();
accountingRequest.addAttribute(Packet.AttributeType.Acct_Session_Id, sessionId);
if (String.IsNullOrEmpty(NAS_Identifier) && NAS_IP_Address == null)
throw new RADIUSException("A NAS_Identifier or NAS_IP_Address (or both) must be supplied.");
if (NAS_IP_Address != null)
accountingRequest.addAttribute(Packet.AttributeType.NAS_IP_Address, NAS_IP_Address);
if (!String.IsNullOrEmpty(NAS_Identifier))
accountingRequest.addAttribute(Packet.AttributeType.NAS_Identifier, NAS_Identifier);
if (!String.IsNullOrEmpty(called_station_id))
accountingRequest.addAttribute(Packet.AttributeType.Called_Station_Id, called_station_id);
if (authType != Packet.Acct_Authentic.Not_Specified)
accountingRequest.addAttribute(Packet.AttributeType.Acct_Authentic, (int)authType);
//m_logger.DebugFormat("Attempting to send {0} for user {1}", accountingRequest.code, username);
for (int retryCt = 0; retryCt <= maxRetries; retryCt++)
{
foreach (string server in servers)
{
//Accounting request packet created, sending data...
UdpClient client = new UdpClient(server, accountingPort);
client.Client.SendTimeout = timeout;
client.Client.ReceiveTimeout = timeout;
try
{
client.Send(accountingRequest.toBytes(), accountingRequest.length);
//Listen for response, since the server has been specified, we don't need to re-specify server
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] respBytes = client.Receive(ref RemoteIpEndPoint);
Packet responsePacket = new Packet(respBytes);
//Verify packet response is good, authenticator should be MD5(Code+ID+Length+RequestAuth+Attributes+Secret)
if (!responsePacket.verifyResponseAuthenticator(accountingRequest.authenticator, sharedKey))
throw new RADIUSException(String.Format("Received response to accounting request with code: {0}, but an incorrect response authenticator was supplied.", responsePacket.code));
lastReceievedPacket = responsePacket;
client.Close();
m_logger.DebugFormat("Received accounting response: {0} for user {1}", responsePacket.code, username);
if (responsePacket.code == Packet.Code.Accounting_Response)
accountingStartTime = DateTime.Now;
return responsePacket.code == Packet.Code.Accounting_Response;
}
//SocketException is thrown if the server does not respond by end of timeout
catch (SocketException se)
{
m_logger.DebugFormat("Accounting start attempt {0}/{1} using {2} failed. Reason: {3}", retryCt + 1, maxRetries + 1, server, se.Message);
}
catch (Exception e)
{
throw new RADIUSException("Unexpected error while trying start accounting.", e);
}
}
}
throw new RADIUSException(String.Format("No response from server(s) after {0} tries.", maxRetries + 1));
}
public bool interimUpdate(string username)
{
Packet p = new Packet(Packet.Code.Accounting_Request, this.identifier, this.sharedKey);
p.addAttribute(Packet.AttributeType.User_Name, username);
if (String.IsNullOrEmpty(sessionId))
throw new RADIUSException("Session ID must be present for accounting.");
p.addAttribute(Packet.AttributeType.Acct_Session_Id, sessionId);
p.addAttribute(Packet.AttributeType.Acct_Status_Type, (int)Packet.Acct_Status_Type.Interim_Update);
p.addAttribute(Packet.AttributeType.Acct_Session_Time, (int)(DateTime.Now - accountingStartTime).TotalSeconds);
if (NAS_IP_Address != null)
p.addAttribute(Packet.AttributeType.NAS_IP_Address, NAS_IP_Address);
if (!String.IsNullOrEmpty(NAS_Identifier))
p.addAttribute(Packet.AttributeType.NAS_Identifier, NAS_Identifier);
if (!String.IsNullOrEmpty(called_station_id))
p.addAttribute(Packet.AttributeType.Called_Station_Id, called_station_id);
m_logger.DebugFormat("Attempting to send interim-update for user {0}", username);
for (int retryCt = 0; retryCt <= maxRetries; retryCt++)
{
foreach (string server in servers)
{
//Accounting request packet created, sending data...
UdpClient client = new UdpClient(server, accountingPort);
client.Client.SendTimeout = timeout;
client.Client.ReceiveTimeout = timeout;
try
{
client.Send(p.toBytes(), p.length);
//Listen for response, since the server has been specified, we don't need to re-specify server
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] respBytes = client.Receive(ref RemoteIpEndPoint);
Packet responsePacket = new Packet(respBytes);
//Verify packet response is good, authenticator should be MD5(Code+ID+Length+RequestAuth+Attributes+Secret)
if (!responsePacket.verifyResponseAuthenticator(p.authenticator, sharedKey))
throw new RADIUSException(String.Format("Received response to interim-update with code: {0}, but an incorrect response authenticator was supplied.", responsePacket.code));
lastReceievedPacket = responsePacket;
client.Close();
m_logger.DebugFormat("Received interim-update response: {0} for user {1}", responsePacket.code, username);
return responsePacket.code == Packet.Code.Accounting_Response;
//SocketException is thrown if the server does not respond by end of timeout
}
catch (SocketException se)
{
m_logger.DebugFormat("Accounting interim-update attempt {0}/{1} using {2} failed. Reason: {3}", retryCt + 1, maxRetries + 1, server, se.Message);
}
catch (Exception e)
{
throw new RADIUSException("Unexpected error while sending interim-update.", e);
}
}
}
throw new RADIUSException(String.Format("No response from server(s) after {0} tries.", maxRetries + 1));
}
public bool stopAccounting(string username, Packet.Acct_Terminate_Cause? terminateCause)
{
Packet accountingRequest = new Packet(Packet.Code.Accounting_Request, identifier, sharedKey);
accountingRequest.addAttribute(Packet.AttributeType.User_Name, username);
if(String.IsNullOrEmpty(sessionId))
throw new RADIUSException("Session ID must be present for accounting.");
accountingRequest.addAttribute(Packet.AttributeType.Acct_Session_Id, sessionId);
accountingRequest.addAttribute(Packet.AttributeType.Acct_Status_Type, (int)Packet.Acct_Status_Type.Stop);
if(terminateCause != null)
accountingRequest.addAttribute(Packet.AttributeType.Acct_Terminate_Cause, (int) Packet.Acct_Terminate_Cause.User_Request);
if (NAS_IP_Address != null)
accountingRequest.addAttribute(Packet.AttributeType.NAS_IP_Address, NAS_IP_Address);
if (!String.IsNullOrEmpty(NAS_Identifier))
accountingRequest.addAttribute(Packet.AttributeType.NAS_Identifier, NAS_Identifier);
if (!String.IsNullOrEmpty(called_station_id))
accountingRequest.addAttribute(Packet.AttributeType.Called_Station_Id, called_station_id);
accountingRequest.addAttribute(Packet.AttributeType.Acct_Session_Time, (int)(DateTime.Now - accountingStartTime).TotalSeconds);
m_logger.DebugFormat("Attempting to send session-stop for user {0}", username);
for (int retryCt = 0; retryCt <= maxRetries; retryCt++)
{
foreach (string server in servers)
{
//Accounting request packet created, sending data...
UdpClient client = new UdpClient(server, accountingPort);
client.Client.SendTimeout = timeout;
client.Client.ReceiveTimeout = timeout;
try
{
client.Send(accountingRequest.toBytes(), accountingRequest.length);
//Listen for response, since the server has been specified, we don't need to re-specify server
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] respBytes = client.Receive(ref RemoteIpEndPoint);
Packet responsePacket = new Packet(respBytes);
//Verify packet response is good, authenticator should be MD5(Code+ID+Length+RequestAuth+Attributes+Secret)
if (!responsePacket.verifyResponseAuthenticator(accountingRequest.authenticator, sharedKey))
throw new RADIUSException(String.Format("Received response to accounting request with code: {0}, but an incorrect response authenticator was supplied.", responsePacket.code));
lastReceievedPacket = responsePacket;
client.Close();
m_logger.DebugFormat("Received accounting response: {0} for user {1}", responsePacket.code, username);
return responsePacket.code == Packet.Code.Accounting_Response;
//SocketException is thrown if the server does not respond by end of timeout
}
catch (SocketException se)
{
m_logger.DebugFormat("Accounting stop attempt {0}/{1} using {2} failed. Reason: {3}", retryCt + 1, maxRetries + 1, server, se.Message);
}
catch (Exception e)
{
throw new RADIUSException("Unexpected error while trying stop accounting.", e);
}
}
}
throw new RADIUSException(String.Format("No response from server(s) after {0} tries.", maxRetries + 1));
}
}
class RADIUSException : Exception {
public RADIUSException(string msg) : base(msg) { }
public RADIUSException(string msg, Exception innerException) : base(msg, innerException) { }
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using MySql.Data;
using MySql.Data.MySqlClient;
using log4net;
using pGina.Shared.Types;
namespace pGina.Plugin.MySqlLogger
{
class EventLoggerMode : ILoggerMode
{
private ILog m_logger = LogManager.GetLogger("MySqlLoggerPlugin");
public static readonly string UNKNOWN_USERNAME = "--Unknown--";
private MySqlConnection m_conn;
public EventLoggerMode() { }
//Logs the event if it's an event we track according to the registry.
public bool Log(int SessionId, System.ServiceProcess.SessionChangeReason Reason, pGina.Shared.Types.SessionProperties properties)
{
//Get the logging message for this event.
string msg = null;
switch (Reason)
{
case System.ServiceProcess.SessionChangeReason.SessionLogon:
msg = LogonEvent(SessionId, properties);
break;
case System.ServiceProcess.SessionChangeReason.SessionLogoff:
msg = LogoffEvent(SessionId, properties);
break;
case System.ServiceProcess.SessionChangeReason.SessionLock:
msg = SessionLockEvent(SessionId, properties);
break;
case System.ServiceProcess.SessionChangeReason.SessionUnlock:
msg = SessionUnlockEvent(SessionId, properties);
break;
case System.ServiceProcess.SessionChangeReason.SessionRemoteControl:
msg = SesionRemoteControlEvent(SessionId, properties);
break;
case System.ServiceProcess.SessionChangeReason.ConsoleConnect:
msg = ConsoleConnectEvent(SessionId, properties);
break;
case System.ServiceProcess.SessionChangeReason.ConsoleDisconnect:
msg = ConsoleDisconnectEvent(SessionId, properties);
break;
case System.ServiceProcess.SessionChangeReason.RemoteConnect:
msg = RemoteConnectEvent(SessionId, properties);
break;
case System.ServiceProcess.SessionChangeReason.RemoteDisconnect:
msg = RemoteDisconnectEvent(SessionId, properties);
break;
}
m_logger.DebugFormat("SessionChange({0}) - Message: {1}", Reason.ToString(), msg);
//Check if there is a message to log
if (!string.IsNullOrEmpty(msg))
{
if (m_conn == null)
throw new InvalidOperationException("No MySQL Connection present.");
//Send it to the server
logToServer(msg);
}
return true; //No msg to log
}
//Tests the table based on the registry data. Returns a string indicating the table status.
public string TestTable()
{
if (m_conn == null)
throw new InvalidOperationException("No MySQL Connection present.");
try
{
if (m_conn.State != System.Data.ConnectionState.Open)
m_conn.Open();
//Get list of tables and check if the event table name exists
MySqlCommand cmd = new MySqlCommand("SHOW TABLES", m_conn);
string table = Settings.Store.EventTable;
bool tableExists = false;
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (Convert.ToString(rdr[0]) == table)
tableExists = true;
}
rdr.Close();
if (!tableExists)
return "Connection was successful, but no table exists. Click \"Create Table\" to create the required table.";
//Table exists, verify columns
string[] columns = { "TimeStamp", "Host", "Ip", "Machine", "Message" };
cmd = new MySqlCommand("DESCRIBE " + table, m_conn);
rdr = cmd.ExecuteReader();
int colCt = 0;
while (rdr.Read())
{
string colName = Convert.ToString(rdr[0]);
if (!columns.Contains(colName))
{
rdr.Close();
return "Table exists, but has incorrect columns.";
}
colCt++;
}
rdr.Close();
if (colCt == columns.Length)
return "Table exists and is setup correctly.";
else
return "Table exists, but appears to have incorrect columns.";
}
catch (MySqlException ex)
{
return String.Format("Connection failed: {0}", ex.Message);
}
}
//Creates the table based on the registry data. Returns a string indicating the table status.
public string CreateTable()
{
if (m_conn == null)
throw new InvalidOperationException("No MySQL Connection present.");
try
{
if(m_conn.State != System.Data.ConnectionState.Open)
m_conn.Open();
string table = Settings.Store.EventTable;
string sql = string.Format(
"CREATE TABLE {0} (" +
" TimeStamp DATETIME, " +
" Host TINYTEXT, " +
" Ip VARCHAR(15), " +
" Machine TINYTEXT, " +
" Message TEXT )", table);
MySqlCommand cmd = new MySqlCommand(sql, m_conn);
cmd.ExecuteNonQuery();
return "Table created.";
}
catch (MySqlException ex)
{
return String.Format("Error: {0}", ex.Message);
}
}
//Provides the MySQL connection to use
public void SetConnection(MySqlConnection m_conn)
{
this.m_conn = m_conn;
}
//Connects to the server and logs the message.
private bool logToServer(string message) {
if (m_conn.State != System.Data.ConnectionState.Open)
m_conn.Open();
string hostName = Dns.GetHostName();
string table = Settings.Store.EventTable;
// Prepare statement
string machine = Environment.MachineName;
string sql = String.Format("INSERT INTO {0}(TimeStamp, Host, Ip, Machine, Message) " +
"VALUES (NOW(), @host, @ip, @machine, @message)", table);
MySqlCommand m_command = new MySqlCommand(sql, m_conn);
m_command.Prepare();
m_command.Parameters.AddWithValue("@host", hostName);
m_command.Parameters.AddWithValue("@ip", getIPAddress());
m_command.Parameters.AddWithValue("@machine", machine);
m_command.Parameters.Add("@message", MySqlDbType.Text);
m_logger.DebugFormat("Logging: {0}", message);
m_command.Parameters["@message"].Value = message;
m_command.ExecuteNonQuery();
m_logger.DebugFormat("Event logged: {1}", message);
return true;
}
//Returns the current IPv4 address
private string getIPAddress()
{
IPAddress[] ipList = Dns.GetHostAddresses("");
string m_ip = "";
// Grab the first IPv4 address in the list
foreach (IPAddress addr in ipList)
{
if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
m_ip = addr.ToString();
break;
}
}
return m_ip;
}
//The following functions determine if the specified event should be logged, and returns the logging message if so
private string LogonEvent(int sessionId, SessionProperties properties)
{
bool okToLog = Settings.Store.EvtLogon;
// Get the username
string userName = getUsername(properties);
// Since the username is not available at logoff time, we cache it
// (tied to the session ID) so that we can get it back at the logoff
// event.
//if (userName != null)
// m_usernameCache.Add(sessionId, userName);
if (userName == null)
userName = UNKNOWN_USERNAME;
if (okToLog)
return string.Format("[{0}] Logon user: {1}", sessionId, userName);
return "";
}
private string LogoffEvent(int sessionId, SessionProperties properties)
{
bool okToLog = Settings.Store.EvtLogoff;
string userName = "";
userName = getUsername(properties);
// Delete the username from the cache because we are logging off?
if (userName == null)
userName = UNKNOWN_USERNAME;
if (okToLog)
return string.Format("[{0}] Logoff user: {1}", sessionId, userName);
return "";
}
private string ConsoleConnectEvent(int sessionId, SessionProperties properties)
{
bool okToLog = Settings.Store.EvtConsoleConnect;
if (okToLog)
return string.Format("[{0}] Console connect", sessionId);
return "";
}
private string ConsoleDisconnectEvent(int sessionId, SessionProperties properties)
{
bool okToLog = Settings.Store.EvtConsoleDisconnect;
if (okToLog)
return string.Format("[{0}] Console disconnect", sessionId);
return "";
}
private string RemoteDisconnectEvent(int sessionId, SessionProperties properties)
{
bool okToLog = Settings.Store.EvtRemoteDisconnect;
string userName = "";
userName = getUsername(properties);
if (userName == null)
userName = UNKNOWN_USERNAME;
if (okToLog)
return string.Format("[{0}] Remote disconnect user: {1}", sessionId, userName);
return "";
}
private string RemoteConnectEvent(int sessionId, SessionProperties properties)
{
bool okToLog = Settings.Store.EvtRemoteConnect;
string userName = "";
userName = getUsername(properties);
if (userName == null)
userName = UNKNOWN_USERNAME;
if (okToLog)
return string.Format("[{0}] Remote connect user: {1}", sessionId, userName);
return "";
}
private string SesionRemoteControlEvent(int sessionId, SessionProperties properties)
{
bool okToLog = Settings.Store.EvtRemoteControl;
string userName = "";
userName = getUsername(properties);
if (userName == null)
userName = UNKNOWN_USERNAME;
if (okToLog)
return string.Format("[{0}] Remote control user: {1}", sessionId, userName);
return "";
}
private string SessionUnlockEvent(int sessionId, SessionProperties properties)
{
bool okToLog = Settings.Store.EvtUnlock;
string userName = "";
userName = getUsername(properties);
if (userName == null)
userName = UNKNOWN_USERNAME;
if (okToLog)
return string.Format("[{0}] Session unlock user: {1}", sessionId, userName);
return "";
}
private string SessionLockEvent(int sessionId, SessionProperties properties)
{
bool okToLog = Settings.Store.EvtLock;
string userName = "";
userName = getUsername(properties);
if (userName == null)
userName = UNKNOWN_USERNAME;
if (okToLog)
return string.Format("[{0}] Session lock user: {1}", sessionId, userName);
return "";
}
private string getUsername(SessionProperties properties)
{
if (properties == null)
return UNKNOWN_USERNAME;
bool useModifiedName = Settings.Store.UseModifiedName;
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
if (useModifiedName)
return userInfo.Username;
else
return userInfo.OriginalUsername;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
using pGina.Shared.Types;
using log4net;
using System.Text;
namespace pGina.Plugin.HttpAuth
{
public class HttpAccessor
{
private static Dictionary<string, UInfo> resps = new Dictionary<string, UInfo>();
private static ILog m_logger = LogManager.GetLogger("HttpAuthAccessor");
static HttpAccessor()
{
}
public static BooleanResult getResponse(String uname, String pwd)
{
try
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(Settings.resolveSettings());
// Set the Method property of the request to POST.
request.Method = "POST";
request.Timeout = 2000;
// Create POST data and convert it to a byte array.
string postData = "{\"username\":\"" + uname + "\",\"password\":\"" + pwd + "\"}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
// Get the response.
using (WebResponse response = request.GetResponse())
{
using (Stream dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
using (StreamReader reader = new StreamReader(dataStream))
{
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
m_logger.InfoFormat("Response: {0}", responseFromServer);
// save it for later use
if (resps.ContainsKey(uname))
{
resps.Remove(uname);
}
resps.Add(uname, UInfo.parseResponse(responseFromServer));
}
}
}
return new BooleanResult() { Success = true };
}
catch(WebException webx)
{
m_logger.ErrorFormat("Accessor.WebException: {0}", webx.Message);
using (HttpWebResponse res = (HttpWebResponse)webx.Response)
{
if (res != null)
{
using (StreamReader resReader = new StreamReader(res.GetResponseStream()))
{
string responseBody = resReader.ReadLine();
if (responseBody.Length > 0)
{
return new BooleanResult() { Success = false, Message = responseBody };
}
}
}
}
return new BooleanResult() { Success = false, Message = webx.Message };
}
catch (Exception e)
{
// very bad scenario
m_logger.ErrorFormat("Accessor.Exception: {0}", e.StackTrace);
return new BooleanResult() { Success = false, Message = e.Message };
}
}
public static BooleanResult getPwChangeResponse(String uname, String pwd, String old)
{
try
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(Settings.resolveSettings());
// Set the Method property of the request to POST.
request.Method = "POST";
request.Timeout = 2000;
// Create POST data and convert it to a byte array.
string postData = "{\"username\":\"" + uname + "\",\"password\":\"" + pwd + "\",\"old\":\"" + pwd + "\"}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
// Get the response.
using (WebResponse response = request.GetResponse())
{
using (Stream dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
using (StreamReader reader = new StreamReader(dataStream))
{
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
m_logger.InfoFormat("PWDCHResponse: {0}", responseFromServer);
return new BooleanResult() { Success = true, Message = responseFromServer };
}
}
}
}
catch (WebException webx)
{
m_logger.ErrorFormat("PWDCHAccessor.WebException: {0}", webx.Message);
using (HttpWebResponse res = (HttpWebResponse)webx.Response)
{
if (res != null)
{
using (StreamReader resReader = new StreamReader(res.GetResponseStream()))
{
string responseBody = resReader.ReadLine();
if (responseBody.Length > 0)
{
return new BooleanResult() { Success = false, Message = responseBody };
}
}
}
}
return new BooleanResult() { Success = false, Message = webx.Message };
}
catch (Exception e)
{
// very bad scenario
m_logger.ErrorFormat("PWDCHAccessor.Exception: {0}", e.StackTrace);
return new BooleanResult() { Success = false, Message = e.Message };
}
}
public static UInfo getUserInfo(String uname)
{
if (! resps.ContainsKey(uname))
{
return null;
}
return resps[uname];
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include <assert.h>
#include "Message.h"
#include "MessageProperty.h"
#include "BinaryReader.h"
#include "BinaryWriter.h"
#define CURRENT_MESSAGE_FORMAT_VERSION 0x01
namespace pGina
{
namespace Messaging
{
Message::Message()
{
}
Message::~Message()
{
for(PropertyMap::iterator itr = m_properties.begin(); itr != m_properties.end(); ++itr)
{
// Release the property object we own
delete itr->second;
}
m_properties.clear();
}
/* static */
Message * Message::Demarshal(pGina::Memory::Buffer *buffer)
{
if(buffer == 0)
return 0;
return Demarshal(*buffer);
}
/* static */
Message * Message::Demarshal(pGina::Memory::Buffer &buffer)
{
// Cannot be empty
if(buffer.Raw() == 0 || buffer.Length() == 0)
return 0;
pGina::Memory::BinaryReader reader(buffer);
unsigned char messageFormatVersion = reader.ReadByte();
if(messageFormatVersion != CURRENT_MESSAGE_FORMAT_VERSION)
return 0;
Message * msg = new Message();
while(!reader.EndOfBuffer())
{
std::wstring propertyName = reader.ReadUnicodeString();
PropertyType propertyType = static_cast<PropertyType>(reader.ReadByte());
switch(propertyType)
{
case Boolean:
msg->Property<bool>(propertyName, reader.ReadBool(), Boolean);
break;
case Byte:
msg->Property<unsigned char>(propertyName, reader.ReadByte(), Byte);
break;
case EmptyString:
msg->Property<std::wstring>(propertyName, L"", String);
break;
case Integer:
msg->Property<int>(propertyName, reader.ReadInt32(), Integer);
break;
case String:
msg->Property<std::wstring>(propertyName, reader.ReadUnicodeString(), String);
break;
}
}
return msg;
}
/* static */
pGina::Memory::Buffer * Message::Marshal(Message *msg)
{
int length = MarshalToBuffer(msg, 0);
pGina::Memory::Buffer * buffer = new pGina::Memory::Buffer(length);
if(MarshalToBuffer(msg, buffer) != length)
assert(0);
return buffer;
}
/* static */
int Message::MarshalToBuffer(Message * msg, pGina::Memory::Buffer * buffer)
{
pGina::Memory::BinaryWriter writer(buffer);
writer.Write((unsigned char) CURRENT_MESSAGE_FORMAT_VERSION);
PropertyMap& properties = msg->Properties();
for(Message::PropertyMap::iterator itr = properties.begin(); itr != properties.end(); ++itr)
{
// Property name
writer.Write(itr->first);
PropertyBase * propBase = itr->second;
// Special case, if its a string, and its empty, we want to write
// nothing for value
if(propBase->Type() == String)
{
pGina::Messaging::Property<std::wstring> * prop = static_cast<pGina::Messaging::Property<std::wstring> *>(propBase);
if(prop->Value().empty())
propBase->Type(EmptyString);
}
// Property type
writer.Write((unsigned char)propBase->Type());
// now work out type/value
switch(propBase->Type())
{
case Boolean:
{
pGina::Messaging::Property<bool> * prop = static_cast<pGina::Messaging::Property<bool> *>(propBase);
writer.Write(prop->Value());
}
break;
case Byte:
{
pGina::Messaging::Property<unsigned char> * prop = static_cast<pGina::Messaging::Property<unsigned char> *>(propBase);
writer.Write(prop->Value());
}
break;
case EmptyString:
// Do nothing, no value here
break;
case Integer:
{
pGina::Messaging::Property<int> * prop = static_cast<pGina::Messaging::Property<int> *>(propBase);
writer.Write(prop->Value());
}
break;
case String:
{
pGina::Messaging::Property<std::wstring> * prop = static_cast<pGina::Messaging::Property<std::wstring> *>(propBase);
writer.Write(prop->Value());
}
break;
}
}
return writer.BytesWritten();
}
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using Microsoft.Win32;
using System.Diagnostics;
using System.Threading;
using System.Net;
using System.Text.RegularExpressions;
using Abstractions;
using pGina.Shared.Types;
using log4net;
namespace pGina.Plugin.pgSMB2
{
public class Roaming
{
private ILog m_logger = LogManager.GetLogger("pgSMB2[Roaming]");
public BooleanResult get(Dictionary<string,string> settings, string username, string password)
{
m_logger = LogManager.GetLogger(String.Format("pgSMB2[Roaming:{0}]", username));
if (!UserCanBeUsed(username))
{
// user exists and was not created by pgina
m_logger.InfoFormat("user {0} does already exist on this system and does not contain a comment of \"pGina created pgSMB2\"", username);
return new BooleanResult() { Success = true };
}
if (!Connect2share(settings["SMBshare"], username, password, Convert.ToUInt32(settings["ConnectRetry"]), false))
{
return new BooleanResult() { Success = false, Message = string.Format("Unable to connect to {0}", settings["RoamingSource"]) };
}
try
{
if (!Directory.Exists(settings["RoamingSource"]))
{
try
{
Directory.CreateDirectory(settings["RoamingSource"]);
}
catch (Exception ex)
{
m_logger.DebugFormat("CreateDirectory({0}) failed {1}", settings["RoamingSource"], ex.Message);
}
}
string remote_file = settings["RoamingSource"] + "\\" + settings["Filename"];
if (File.Exists(remote_file) || File.Exists(remote_file + ".bak"))
{
// there is a remote file
Boolean loadprofile = true;
// what file to use ?
if (File.Exists(remote_file))
{
settings.Add("Filename_real", settings["Filename"]);
}
else
{
settings.Add("Filename_real", settings["Filename"] + ".bak");
remote_file += ".bak";
}
// is there a local roaming profile (there shouldnt be any)
string ProfDir = GetExistingUserProfile(username, password);
// is this a temp profile
if (!String.IsNullOrEmpty(ProfDir))
{
Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4 userinfo4 = new Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4();
if (Abstractions.WindowsApi.pInvokes.UserGet(username, ref userinfo4))
{
if (userinfo4.comment.EndsWith(" tmp"))
{
m_logger.InfoFormat("delete temp profile {0}", ProfDir);
DirectoryDel(ProfDir, 3);
}
}
}
if (File.Exists(ProfDir + "\\ntuser.dat")) //worst case "\\ntuser.dat"
{
// there is a local profile of this user
// we need to compare the write date between the profile and the compressed remote roaming profile
// to be sure that we dont overwrite a newer profile with an old one
// possibly reason is a BSOD/hard reset ...
m_logger.Debug("User " + username + " still own a lokal profile UTCdate:" + File.GetLastWriteTimeUtc(ProfDir + "\\ntuser.dat"));
m_logger.Debug("User " + username + " compressed remote profile UTCdate:" + File.GetLastWriteTimeUtc(remote_file));
if (DateTime.Compare(File.GetLastWriteTimeUtc(ProfDir + "\\ntuser.dat"), File.GetLastWriteTimeUtc(remote_file)) >= 0)
{
m_logger.DebugFormat("the local profile ('{0}') is newer/equal than the remote one, im not downloading the remote one", ProfDir);
loadprofile = false;
}
else
{
m_logger.Debug("the local profile is older than the remote one");
}
}
if (!userAdd(settings, username, password, "<PASSWORD> created pgSMB2"))
{
userDel(settings, username, password);
return new BooleanResult() { Success = false, Message = string.Format("Unable to add user {0}", username) };
}
if (loadprofile)
{
if (!GetProfile(ref settings, username, password))
{
return new BooleanResult() { Success = false, Message = string.Format("Unable to get the Profile {0} from {1}", settings["Filename"], settings["RoamingSource"]) };
}
if (!Connect2share(settings["SMBshare"], null, null, 0, true))
{
m_logger.WarnFormat("unable to disconnect from {0}", settings["RoamingSource"]);
}
if (!SetACL(settings["UserProfilePath"], username, password, Convert.ToUInt32(settings["MaxStore"]), Convert.ToUInt32(settings["ConnectRetry"])))
{
userDel(settings, username, password);
return new BooleanResult() { Success = false, Message = string.Format("Unable to set ACL for user {0}", username) };
}
}
}
else
{
m_logger.DebugFormat("there is no {0}\\{1} or {2}\\{3}{4}", settings["RoamingSource"], settings["Filename"], settings["RoamingSource"], settings["Filename"], ".bak");
if (!userAdd(settings, username, password, "pGina created pgSMB2"))
{
userDel(settings, username, password);
return new BooleanResult() { Success = false, Message = string.Format("Unable to add user {0}", username) };
}
}
}
catch (Exception ex)
{
return new BooleanResult() { Success = false, Message = string.Format("Unable to get the Roaming Profile from {0}\nError: {1}", settings["RoamingSource"], ex.Message) };
}
finally
{
if (!Connect2share(settings["SMBshare"], null, null, 0, true))
{
m_logger.WarnFormat("unable to disconnect from {0}", settings["RoamingSource"]);
}
}
return new BooleanResult() { Success = true };
}
public BooleanResult put(Dictionary<string, string> settings, string username, string password, string LocalProfilePath, SecurityIdentifier SID)
{
m_logger = LogManager.GetLogger(String.Format("pgSMB2[Roaming:{0}]", username));
try
{
BooleanResult result = PutProfile(settings, username, password, LocalProfilePath, SID);
if (!result.Success)
{
return new BooleanResult() { Success = false, Message = string.Format("Unable to upload the profile {0}", result.Message) };
}
}
catch (Exception ex)
{
return new BooleanResult() { Success = false, Message = string.Format("Error {0} during profile upload", ex.ToString()) };
}
return new BooleanResult() { Success = true };
}
private BooleanResult PutProfile(Dictionary<string, string> settings, string username, string password, string LocalProfilePath, SecurityIdentifier SID)
{
int ret_code = -1;
string uPath = LocalProfilePath; // should be set by sessionlogon
if (String.IsNullOrEmpty(LocalProfilePath))
{
m_logger.InfoFormat("LocalProfilePath is empty re-evaluate");
uPath = GetExistingUserProfile(username, password, SID.Value);
}
if (!File.Exists(uPath + "\\NTUSER.DAT"))
{
return new BooleanResult() { Success = false, Message = String.Format("Unable to find \"{0}{1}\"", uPath, "\\NTUSER.DAT") };
}
if (!settings["MaxStore"].Equals("0"))
{
long uPath_size = GetDirectorySize(uPath, settings["MaxStoreExclude"]);
if (uPath_size == 0)
{
return new BooleanResult() { Success = false, Message = String.Format("User directory:{0} size returned:0", uPath) };
}
uPath_size = Convert.ToInt64(uPath_size / 1024);
if (uPath_size > Convert.ToInt64(settings["MaxStore"]))
{
return new BooleanResult() { Success = false, Message = String.Format("User directory:{0} MaxStore:{1} kbyte exceeded:{2} kbyte", uPath, Convert.ToInt64(settings["MaxStore"]), uPath_size) };
}
}
//crappy windows cant open 2 connection to the same server
//we need to fool win to think the server is a different one
//simply by using IP or FQDN
string[] server = {null, null};
for (uint x = 0; x < Convert.ToUInt32(settings["ConnectRetry"]); x++)
{
server = SMBserver(settings["SMBshare"], true);
if (!String.IsNullOrEmpty(server[0]) && !String.IsNullOrEmpty(server[1]))
{
break;
}
Thread.Sleep(new TimeSpan(0, 0, 3));
}
if (String.IsNullOrEmpty(server[0]) || String.IsNullOrEmpty(server[1]))
{
m_logger.InfoFormat("can't resolve IP or FQDN from {0} I will try to continue, but the upload my fail with System Error 1219", settings["SMBshare"]);
}
else
{
if (!server[0].Equals(server[1]))
{
// dont replace any accurance except the first
server[0] = @"\\" + server[0];
server[1] = @"\\" + server[1];
settings["SMBshare"] = settings["SMBshare"].ToLower().Replace(server[0].ToLower(), server[1]);
settings["RoamingSource"] = settings["RoamingSource"].ToLower().Replace(server[0].ToLower(), server[1]);
// fooled you
}
else
{
m_logger.InfoFormat("can't fool windows to think {0} is a different server. I will try to continue but the upload my fail with System Error 1219", server[0]);
}
}
for (uint x = 0; x < Convert.ToUInt32(settings["ConnectRetry"]); x++)
{
// run imagex in capture mode
string stdmerge = "";
m_logger.DebugFormat("Run {0} {1}", settings["Compressor"], settings["CompressCLI"].Replace("%z",uPath));
ret_code = RunWait(settings["Compressor"], settings["CompressCLI"].Replace("%z", uPath), out stdmerge);
if (ret_code == 0)
{
break;
}
m_logger.DebugFormat("Exitcode:{0}\n{1}", ret_code, tail(stdmerge, 10));
if (x < Convert.ToUInt32(settings["ConnectRetry"]))
{
Thread.Sleep(new TimeSpan(0, 0, 30));
}
}
//where is the compressed profile now?
string ThereIsTheProfile = null;
string[] array = settings["CompressCLI"].Split(' ');
foreach (string element in array)
{
if (element.ToLower().Contains(settings["Filename"].ToLower()))
{
ThereIsTheProfile = element.Trim(new char[] { '"', '\'', '`', ' ', '\t' });
m_logger.InfoFormat("The file is stored at {0}", ThereIsTheProfile);
}
}
if (String.IsNullOrEmpty(ThereIsTheProfile))
{
return new BooleanResult() { Success = false, Message = String.Format("Unable to find the file \"{0}\" in your compress command {1}", settings["Filename"], settings["CompressCLI"]) };
}
else
{
if (ret_code != 0)
{
m_logger.DebugFormat("File.Delete {0}", ThereIsTheProfile);
File.Delete(ThereIsTheProfile);
}
}
if (ret_code == 0)
{
if (!Connect2share(settings["SMBshare"], username, password, Convert.ToUInt32(settings["ConnectRetry"]), false))
{
return new BooleanResult() { Success = false, Message = String.Format("Unable to connect to {0}", settings["RoamingSource"]) };
}
if (!Directory.Exists(settings["RoamingSource"]))
{
if (!Connect2share(settings["SMBshare"], null, null, 0, true))
{
m_logger.WarnFormat("unable to disconnect from {0}", settings["RoamingSource"]);
}
return new BooleanResult() { Success = false, Message = String.Format("Can't find {0}", settings["RoamingSource"]) };
}
string remoteFile = settings["RoamingSource"] + "\\" + settings["Filename"];
string remoteFileBAK = settings["RoamingSource"] + "\\" + settings["Filename"] + ".bak";
//while (File.Exists(remoteFileBAK) && File.Exists(remoteFile))
for (uint x = 0; x < Convert.ToUInt32(settings["ConnectRetry"]); x++)
{
// if there is a remote image and a bak image, delete the bak
if (File.Exists(remoteFileBAK) && File.Exists(remoteFile))
{
try
{
m_logger.DebugFormat("File.Delete {0}", remoteFileBAK);
File.Delete(remoteFileBAK);
}
catch (Exception ex)
{
m_logger.Debug(ex.Message);
Thread.Sleep(new TimeSpan(0, 0, 1));
}
}
}
//while (File.Exists(remoteFile))
for (uint x = 0; x < Convert.ToUInt32(settings["ConnectRetry"]); x++)
{
// if there is a remote wim, rename it to bak
if (File.Exists(remoteFile))
{
try
{
m_logger.DebugFormat("File.Move {0} {1}", remoteFile, remoteFileBAK);
File.Move(remoteFile, remoteFileBAK);
break;
}
catch (Exception ex)
{
m_logger.Debug(ex.Message);
Thread.Sleep(new TimeSpan(0, 0, 1));
}
}
}
// check share space
long wimbak_size = 0;
long wim_size = 0;
if (File.Exists(remoteFileBAK))
{
FileInfo fwimbak = new FileInfo(remoteFileBAK);
wimbak_size = fwimbak.Length;
}
FileInfo fwim = new FileInfo(ThereIsTheProfile);
wim_size = fwim.Length;
long[] freespace = Abstractions.WindowsApi.pInvokes.GetFreeShareSpace(settings["SMBshare"]);
if (freespace[0] > -1)
{
if (wim_size > freespace[0])
{
if ((wim_size - wimbak_size) < freespace[0])
{
m_logger.InfoFormat("I'll store the bak file at {0} instead of {1}, because there is not enough space on {2} {3} bytes", ThereIsTheProfile + ".bak", remoteFileBAK, settings["SMBshare"], freespace);
try
{
m_logger.InfoFormat("File.Copy {0} {1}", remoteFileBAK, ThereIsTheProfile + ".bak");
File.Copy(remoteFileBAK, ThereIsTheProfile + ".bak", true);
m_logger.InfoFormat("File.Delete {0}", remoteFileBAK);
File.Delete(remoteFileBAK);
Abstractions.Windows.Security.ReplaceFileSecurity(ThereIsTheProfile + ".bak", new IdentityReference[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null) }, FileSystemRights.FullControl, AccessControlType.Allow, InheritanceFlags.None, PropagationFlags.None);
}
catch (Exception ex)
{
m_logger.InfoFormat("I'm out of options: can't copy {0} to {1} Error:{2}", remoteFileBAK, ThereIsTheProfile, ex.Message);
}
}
else
{
m_logger.InfoFormat("not enough space on {0} to store {1} with size {2}", settings["SMBshare"], ThereIsTheProfile, wim_size);
}
}
}
for (uint x = 0; x < Convert.ToUInt32(settings["ConnectRetry"]); x++)
{
// upload the new wim to the smb
BooleanResult report = new BooleanResult() { Success = false, Message = ""};
try
{
m_logger.DebugFormat("File.Copy {0} {1}", ThereIsTheProfile, remoteFile);
File.Copy(ThereIsTheProfile, remoteFile, true);
break;
}
catch (Exception ex)
{
report.Message = ex.Message;
m_logger.Debug(ex.Message);
}
if (x == Convert.ToUInt32(settings["ConnectRetry"]) - 1)
{
if (!Connect2share(settings["SMBshare"], null, null, 0, true))
{
m_logger.WarnFormat("unable to disconnect from {0}", settings["RoamingSource"]);
}
Abstractions.Windows.Security.ReplaceFileSecurity(ThereIsTheProfile, new IdentityReference[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null) }, FileSystemRights.FullControl, AccessControlType.Allow, InheritanceFlags.None, PropagationFlags.None);
return report;
}
else
{
Thread.Sleep(new TimeSpan(0, 0, 1));
}
}
try
{
// make a timestamp with the current ntp time
// a different computer can have a different time/date and so its better to use ntp time
DateTime ntpTime = Abstractions.Windows.Networking.GetNetworkTime(settings["ntp"].Split(' '));
if (ntpTime != DateTime.MinValue)
{
File.SetLastWriteTimeUtc(remoteFile, ntpTime);
File.SetLastWriteTimeUtc(uPath + "\\NTUSER.DAT", ntpTime);
}
// cleanup local user
m_logger.DebugFormat("File.Delete {0}", ThereIsTheProfile);
File.Delete(ThereIsTheProfile);
}
catch (Exception ex)
{
m_logger.Debug(ex.Message);
}
finally
{
if (!Connect2share(settings["SMBshare"], null, null, 0, true))
{
m_logger.WarnFormat("unable to disconnect from {0}", settings["RoamingSource"]);
}
}
return new BooleanResult() { Success = true, Message = "" };
}
return new BooleanResult() { Success = false, Message = "failed to compress the profile" };
}
private Boolean GetProfile(ref Dictionary<string,string> settings, string username, string password)
{
int ret_code = -1;
m_logger.DebugFormat("User {0} owns a remote profile", username);
IntPtr huser = Abstractions.WindowsApi.pInvokes.GetUserToken(username, "", password);
if (huser == null)
{
m_logger.ErrorFormat("can't get token from user {0}", username);
return false;
}
string uPath = Abstractions.WindowsApi.pInvokes.CreateUserProfileDir(huser, username);
Abstractions.WindowsApi.pInvokes.CloseHandle(huser);
if (uPath == null)
{
uPath = GetExistingUserProfile(username, password);
}
uPath = uPath.Trim();
if (String.IsNullOrEmpty(uPath))
{
m_logger.ErrorFormat("can't find {0} profile directory", username);
return false;
}
if (Directory.Exists(uPath))
{
DirectoryDel(uPath, Convert.ToUInt32(settings["ConnectRetry"]));
}
if (!CreateRoamingFolder(uPath, username))
{
m_logger.ErrorFormat("failed to create directory {0} for {1}", uPath, username);
return false;
}
settings.Add("UserProfilePath", uPath);
for (uint x = 0; x < Convert.ToUInt32(settings["ConnectRetry"]); x++)
{
// run imagex in apply mode
string stdmerge = "";
string args = "";
if (settings.ContainsKey("Filename_real"))
{
args = settings["UncompressCLI"].Replace(settings["Filename"], settings["Filename_real"]); //"%u.wim.bak"
}
else
{
args = settings["UncompressCLI"];
}
args = args.Replace("%z", uPath);
m_logger.DebugFormat("Run {0} {1}", settings["Compressor"], args);
ret_code = RunWait(settings["Compressor"], args, out stdmerge);
if (ret_code == 0)
{
break;
}
m_logger.DebugFormat("Exitcode:{0}\n{1}", ret_code, tail(stdmerge,10));
Thread.Sleep(new TimeSpan(0, 0, 30));
}
if (ret_code != 0)
{
// Uncompessing failed, clean and disconnect
// mark the image as tmp and prevent the upload
DirectoryDel(uPath, Convert.ToUInt32(settings["ConnectRetry"]));
return false;
}
return true;
}
private string GetExistingUserProfile(string username, string password, string userSID = "")
{
Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4 userinfo4 = new Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4();
if (String.IsNullOrEmpty(userSID))
{
if (!Abstractions.WindowsApi.pInvokes.UserGet(username, ref userinfo4))
{
m_logger.DebugFormat("Can't get userinfo for user {0}", username);
return "";
}
try
{
userSID = new SecurityIdentifier(userinfo4.user_sid).Value;
}
catch (Exception ex)
{
m_logger.ErrorFormat("failed to convert SID for \"{0}\":{1}", userinfo4.name, ex.ToString());
return "";
}
}
m_logger.InfoFormat("SID found:{0}", userSID);
if (!Abstractions.Windows.User.FixProfileList(userSID))
{
m_logger.DebugFormat("Error in FixProfileList {0}", userSID);
}
return Abstractions.Windows.User.GetProfileDir(username, password, new SecurityIdentifier(userSID));
}
public Boolean userAdd(Dictionary<string,string> settings, string username, string password, string comment)
{
Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4 userinfo4 = new Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4();
//create user
if (!Abstractions.WindowsApi.pInvokes.UserExists(username))
{
if (!Abstractions.WindowsApi.pInvokes.UserADD(username, password, comment))
{
m_logger.DebugFormat("Can't add user {0}", username);
return false;
}
}
//get userinfo
if (!Abstractions.WindowsApi.pInvokes.UserGet(username, ref userinfo4))
{
m_logger.DebugFormat("Can't get userinfo for user {0}", username);
return false;
}
//fill userinfo
userinfo4.profile = null;
if (!String.IsNullOrEmpty(settings["HomeDir"]))
userinfo4.home_dir = settings["HomeDir"];
if (!String.IsNullOrEmpty(settings["HomeDirDrive"]))
userinfo4.home_dir_drive = settings["HomeDirDrive"];
if (!String.IsNullOrEmpty(settings["ScriptPath"]))
userinfo4.script_path = null;
//userinfo4.script_path = settings["ScriptPath"];
/*if (Convert.ToInt32(settings["MaxStore"]) > 0)
userinfo4.max_storage = Convert.ToInt32(settings["MaxStore"]);
else
userinfo4.max_storage = -1;*/
userinfo4.password = <PASSWORD>;
userinfo4.comment = comment;
userinfo4.flags |= Abstractions.WindowsApi.pInvokes.structenums.UserFlags.UF_NORMAL_ACCOUNT;
userinfo4.acct_expires = -1;
userinfo4.logon_hours = IntPtr.Zero;
//apply userinfo
if (!Abstractions.WindowsApi.pInvokes.UserMod(username, userinfo4))
{
m_logger.DebugFormat("Can't modify user {0}", username);
return false;
}
m_logger.InfoFormat("user {0} created", username);
return true;
}
private Boolean UserCanBeUsed(string username)
{
Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4 userinfo4 = new Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4();
//get userinfo
if (!Abstractions.WindowsApi.pInvokes.UserGet(username, ref userinfo4))
{
return true;
}
//check if this is a pgina user
if (userinfo4.comment.Contains("pGina created pgSMB2"))
{
return true;
}
else
{
return false;
}
}
public Boolean userDel(Dictionary<string, string> settings, string username, string password)
{
if (!Abstractions.WindowsApi.pInvokes.UserDel(username))
{
m_logger.WarnFormat("Can't delete userAccount {0}", username);
}
return true;
}
public Boolean DirectoryDel(string path, uint retry)
{
for (uint x = 1; x <= retry; x++)
{
if (Directory.Exists(path))
{
try
{
Directory.Delete(path, true);
return true;
}
catch (Exception ex)
{
if (x == retry)
{
m_logger.WarnFormat("unable to delete {0} error {1}", path, ex.Message);
}
if (!Abstractions.Windows.Security.SetDirOwner(path, new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null).Translate(typeof(NTAccount))))
{
if (x == retry)
{
m_logger.DebugFormat("failed to set directory owner for {0} at {1}", WindowsIdentity.GetCurrent().Name, path);
}
}
if (!Abstractions.Windows.Security.ReplaceDirectorySecurity(path, new IdentityReference[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null) }, FileSystemRights.FullControl, AccessControlType.Allow, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None))
{
if (x == retry)
{
m_logger.DebugFormat("failed to set DirectorySecurity for {0} at {1}", WindowsIdentity.GetCurrent().Name, path);
}
}
else
{
if (!Abstractions.Windows.Security.SetRecDirAttrib(new DirectoryInfo(path), FileAttributes.Normal))
{
if (x == retry)
{
m_logger.DebugFormat("failed to set Attributes at {0}", path);
}
}
}
}
if (x == retry)
{
try
{//do better
Process.Start("cmd", "/c rd /S /Q \"" + path + "\"");
}
catch (Exception ex)
{
m_logger.InfoFormat("failed to run rd /s /q \"{0}\":{1}", path, ex.Message);
}
}
}
else
{
return true;
}
Thread.Sleep(new TimeSpan(0, 0, 3));
}
return false;
}
private Boolean SetACL(string dir, string username, string password, uint maxstore, uint retry)
{
m_logger.InfoFormat("modify ACE");
Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4 userinfo4 = new Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4();
if (!Abstractions.WindowsApi.pInvokes.UserGet(username, ref userinfo4))
{
m_logger.DebugFormat("Can't get userinfo for user {0}", username);
return false;
}
IdentityReference userIref = new SecurityIdentifier(userinfo4.user_sid).Translate(typeof(NTAccount));
if (!Abstractions.Windows.Security.SetDirOwner(dir, new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Translate(typeof(NTAccount))))
{
m_logger.WarnFormat("Can't set owner for Directory {0}", dir);
return false;
}
if (!Abstractions.Windows.Security.ReplaceDirectorySecurity(dir, new IdentityReference[] { new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), userIref }, FileSystemRights.FullControl, AccessControlType.Allow, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None))
{
m_logger.WarnFormat("Can't set ACL for Directory {0}", dir);
return false;
}
if (!Abstractions.Windows.Security.RemoveAccRuleFromUnknownUser(dir))
{
m_logger.InfoFormat("Can't remove unknown users from {0} ACL", dir);
//not critical
}
if (!SetACLquotaREGfile(dir + "\\NTUSER.DAT", retry, username, maxstore, true, true))
{
return false;
}
if (File.Exists(dir + @"\AppData\Local\Microsoft\Windows\UsrClass.dat"))
{
if (!SetACLquotaREGfile(dir + @"\AppData\Local\Microsoft\Windows\UsrClass.dat", retry, username, maxstore, false, true))
{
return false;
}
}
return true;
}
private bool SetACLquotaREGfile(string file, uint retry, string username, uint quotasize, bool quota, bool acl)
{
bool work = false;
bool critical = true;
for (int x = 1; x <= retry; x++)
{
if (!Abstractions.WindowsApi.pInvokes.RegistryLoad(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation.HKEY_LOCAL_MACHINE, username, file))
{
m_logger.WarnFormat("Can't load regfile {0}", file);
Thread.Sleep(new TimeSpan(0, 0, 10));
work = false;
continue;
}
else
{
work = true;
}
Thread.Sleep(new TimeSpan(0, 0, 3));
break;
}
if (!work)
{
return false;
}
if (quota)
{
if (!Abstractions.Windows.User.SetQuota(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation.HKEY_LOCAL_MACHINE, username, quotasize))
{
m_logger.WarnFormat("Can't set quota");
critical = false;
}
}
if (acl)
{
if (!Abstractions.Windows.Security.RegSec(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation.HKEY_LOCAL_MACHINE, username, username))
{
m_logger.WarnFormat("Can't set ACL for regkey {0}\\{1}", Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation.HKEY_LOCAL_MACHINE.ToString(), username);
critical = false;
}
}
for (int x = 1; x <= retry; x++)
{
if (!Abstractions.WindowsApi.pInvokes.RegistryUnLoad(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation.HKEY_LOCAL_MACHINE, username))
{
m_logger.WarnFormat("Can't unload regkey {0}", file);
Thread.Sleep(new TimeSpan(0, 0, 10));
work = false;
continue;
}
else
{
work = true;
}
Thread.Sleep(new TimeSpan(0, 0, 3));
break;
}
if (!work || !critical)
{
return false;
}
return true;
}
private string[] SMBserver(string share, Boolean visversa)
{
string[] ret = { null, null };
string[] server;
try
{
server = share.Trim('\\').Split('\\');
}
catch
{
m_logger.DebugFormat("can't split servername {0}", share);
return ret;
}
if (!String.IsNullOrEmpty(server[0]))
{
ret[0] = server[0];
ret[1] = server[0];
if (!visversa)
{
return ret;
}
try
{
IPHostEntry hostFQDN = Dns.GetHostEntry(server[0]);
if (hostFQDN.HostName.Equals(server[0], StringComparison.CurrentCultureIgnoreCase))
{
IPAddress[] hostIPs = Dns.GetHostAddresses(server[0]);
ret[1] = hostIPs[0].ToString();
}
else
{
ret[1] = hostFQDN.HostName;
}
}
catch (Exception ex)
{
m_logger.ErrorFormat("can't resolve FQDN of {0}:{1}", server[0], ex.Message);
return new string[] { null, null };
}
}
else
{
m_logger.DebugFormat("first token of servername {0} is null", share);
}
return ret;
}
private Boolean Connect2share(string share, string username, string password, uint retry, Boolean DISconnect)
{
if (DISconnect)
{
m_logger.DebugFormat("disconnecting from {0}", share);
if (!Abstractions.WindowsApi.pInvokes.DisconnectNetworkDrive(share))
{
m_logger.WarnFormat("unable to disconnect from {0}", share);
}
return true;
}
else
{
string[] server = SMBserver(share, false);
if (String.IsNullOrEmpty(server[0]))
{
m_logger.ErrorFormat("Can't extract SMB server from {0}", share);
return false;
}
string dusername = server[0] + "\\" + username;
for (int x = 1; x <= retry; x++)
{
try
{
m_logger.DebugFormat("{0}. try to connect to {1} as {2}", x, share, dusername);
if (!Abstractions.WindowsApi.pInvokes.MapNetworkDrive(share, dusername, password))
{
m_logger.ErrorFormat("Failed to connect to share {0}", share);
if (x < retry)
Thread.Sleep(new TimeSpan(0, 0, 30));
continue;
}
if (Directory.Exists(share))
return true;
}
catch (Exception ex)
{
m_logger.Error(ex.Message);
}
Thread.Sleep(new TimeSpan(0, 0, 3));
}
return false;
}
}
private Boolean CreateRoamingFolder(string dir, string username)
{
if (!Directory.Exists(dir))
{
try
{
Directory.CreateDirectory(dir);
}
catch
{
m_logger.WarnFormat("Can't create Directory {0}", dir);
return false;
}
}
Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4 userinfo4 = new Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4();
if (!Abstractions.WindowsApi.pInvokes.UserGet(username, ref userinfo4))
{
m_logger.WarnFormat("Can't get userinfo4 from {0}", username);
return false;
}
IdentityReference userIref = new SecurityIdentifier(userinfo4.user_sid).Translate(typeof(NTAccount));
if (!Abstractions.Windows.Security.SetDirOwner(dir, new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Translate(typeof(NTAccount))))
{
m_logger.WarnFormat("Can't set owner {0} for Directory {1}", username, dir);
return false;
}
if (!Abstractions.Windows.Security.SetDirectorySecurity(dir, new IdentityReference[] { userIref }, FileSystemRights.Write | FileSystemRights.ReadAndExecute, AccessControlType.Allow, InheritanceFlags.None, PropagationFlags.None))
{
m_logger.WarnFormat("Can't set ACL for Directory {0}", dir);
return false;
}
return true;
}
private int RunWait(string application, string arguments, out string stdmerge)
{
stdmerge = "";
string stdout = "";
string stderr = "";
int ret = -1;
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = application;
startInfo.Arguments = arguments;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
try
{
using (Process p = Process.Start(startInfo))
{
using (StreamReader streamReader = p.StandardOutput)
{
stdout = streamReader.ReadToEnd();
}
using (StreamReader streamReader = p.StandardError)
{
stderr = streamReader.ReadToEnd();
}
p.WaitForExit();
ret = p.ExitCode;
}
}
catch (Exception ex)
{
m_logger.ErrorFormat("RunWait failed error:{0}", ex.Message);
return -1;
}
stdmerge += String.Format("{0}\r\n{1}", stdout.TrimEnd(), stderr.TrimEnd()).TrimEnd();
return ret;
}
private string tail(string input, int lines)
{
string ret = "";
string t = input.Replace("\r", "");
while (t.Contains("\n\n"))
{
t = t.Replace("\n\n", "\n");
}
string[] s = t.Split('\n');
if (s.Length >= lines)
{
ret = "";
for (int x = s.Length - lines; x < s.Length; x++)
{
ret += s[x] + "\r\n";
}
}
else
{
foreach (string line in s)
{
ret += line + "\r\n";
}
}
return ret.TrimEnd();
}
public List<string> GetDirectories(string d, string exclude)
{
List<string> ret = new List<string>();
try
{
string[] dirs = Directory.GetDirectories(d, "*", System.IO.SearchOption.TopDirectoryOnly);
foreach (string dir in dirs)
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
if (!dirInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
if (!Regex.IsMatch(dir, exclude))
{
ret.Add(dir);
ret.AddRange(GetDirectories(dir, exclude));
}
}
}
}
catch (Exception ex)
{
m_logger.ErrorFormat("GetDirectories() error:", ex.Message);
}
return ret;
}
public Dictionary<string, long> GetFiles(string d, string exclude)
{
List<string> dirs = new List<string>() { d };
dirs.AddRange(GetDirectories(d, exclude));
Dictionary<string, long> ret = new Dictionary<string, long>();
try
{
foreach (string dir in dirs)
{
//Console.WriteLine("dir:{0}", dir);
string[] files = Directory.GetFiles(dir, "*", System.IO.SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
ret.Add(file, new FileInfo(file).Length);
}
}
}
catch (Exception ex)
{
m_logger.ErrorFormat("GetFiles() error:", ex.Message);
}
return ret;
}
public long GetDirectorySize(string d, string exclude)
{
Dictionary<string, long> files = GetFiles(d, exclude);
long ret = 0;
try
{
foreach ( KeyValuePair<string, long> pair in files )
{
ret += pair.Value;
}
}
catch (Exception ex)
{
m_logger.ErrorFormat("GetDirectorySize() error:", ex.Message);
}
return ret;
}
public long GetDirectorySize(Dictionary<string, long> files)
{
long ret = 0;
try
{
foreach (KeyValuePair<string, long> pair in files)
{
ret += pair.Value;
}
}
catch (Exception ex)
{
m_logger.ErrorFormat("GetDirectorySize() error:", ex.Message);
}
return ret;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Security.Principal;
using System.Security.AccessControl;
using System.IO;
using Microsoft.Win32;
using System.Threading;
using System.Net;
using pGina.Shared.Types;
using Abstractions;
namespace pGina.Plugin.LocalMachine
{
public class LocalAccount
{
private static ILog m_logger = null;
private static DirectoryEntry m_sam = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
private static PrincipalContext m_machinePrincipal = new PrincipalContext(ContextType.Machine);
private static Random randGen = new Random();
public class GroupSyncException : Exception
{
public GroupSyncException(Exception e)
{
RootException = e;
}
public Exception RootException { get; private set; }
};
private UserInformation m_userInfo = null;
public UserInformation UserInfo
{
get { return m_userInfo; }
set
{
m_userInfo = value;
m_logger = LogManager.GetLogger(string.Format("LocalAccount[{0}]", m_userInfo.Username));
}
}
static LocalAccount()
{
m_logger = LogManager.GetLogger("LocalAccount");
}
public LocalAccount(UserInformation userInfo)
{
UserInfo = userInfo;
}
/// <summary>
/// Finds and returns the UserPrincipal object if it exists, if not, returns null.
/// This method uses PrincipalSearcher because it is faster than UserPrincipal.FindByIdentity.
/// The username comparison is case insensitive.
/// </summary>
/// <param name="username">The username to search for.</param>
/// <returns>The UserPrincipal object, or null if not found.</returns>
public static UserPrincipal GetUserPrincipal(string username)
{
if (string.IsNullOrEmpty(username)) return null;
// Since PrincipalSearcher is case sensitive, and we want a case insensitive
// search, we get a list of all users and compare the names "manually."
using (PrincipalSearcher searcher = new PrincipalSearcher(new UserPrincipal(m_machinePrincipal)))
{
PrincipalSearchResult<Principal> sr = searcher.FindAll();
foreach (Principal p in sr)
{
if (p is UserPrincipal)
{
UserPrincipal user = (UserPrincipal)p;
if (user.Name.Equals(username, StringComparison.CurrentCultureIgnoreCase))
return user;
}
}
}
return null;
}
public static UserPrincipal GetUserPrincipal(SecurityIdentifier sid)
{
// This could be updated to use PrincipalSearcher, but the method is currently
// unused.
return UserPrincipal.FindByIdentity(m_machinePrincipal, IdentityType.Sid, sid.ToString());
}
/// <summary>
/// Finds and returns the GroupPrincipal object if it exists, if not, returns null.
/// This method uses PrincipalSearcher because it is faster than GroupPrincipal.FindByIdentity.
/// The group name comparison is case insensitive.
/// </summary>
/// <param name="groupname"></param>
/// <returns></returns>
public static GroupPrincipal GetGroupPrincipal(string groupname)
{
if (string.IsNullOrEmpty(groupname)) return null;
// In order to do a case insensitive search, we need to scan all
// groups "manually."
using(PrincipalSearcher searcher = new PrincipalSearcher(new GroupPrincipal(m_machinePrincipal)))
{
PrincipalSearchResult<Principal> sr = searcher.FindAll();
foreach (Principal p in sr)
{
if (p is GroupPrincipal)
{
GroupPrincipal group = (GroupPrincipal)p;
if (group.Name.Equals(groupname, StringComparison.CurrentCultureIgnoreCase) || group.Sid.ToString().Equals(groupname, StringComparison.CurrentCultureIgnoreCase))
return group;
}
}
}
return null;
}
public static GroupPrincipal GetGroupPrincipal(SecurityIdentifier sid)
{
using (PrincipalSearcher searcher = new PrincipalSearcher(new GroupPrincipal(m_machinePrincipal)))
{
PrincipalSearchResult<Principal> sr = searcher.FindAll();
foreach (Principal p in sr)
{
if (p is GroupPrincipal)
{
GroupPrincipal group = (GroupPrincipal)p;
if (group.Sid == sid)
return group;
}
}
}
return null;
}
public static DirectoryEntry GetUserDirectoryEntry(string username)
{
return m_sam.Children.Find(username, "User");
}
public void ScrambleUsersPassword(string username)
{
using (DirectoryEntry userDe = GetUserDirectoryEntry(username))
{
userDe.Invoke("SetPassword", GenerateRandomPassword(30));
userDe.CommitChanges();
}
}
/// <summary>
/// Generates a random password that meets most of the requriements of Windows
/// Server when password policy complexity requirements are in effect.
///
/// http://technet.microsoft.com/en-us/library/cc786468%28v=ws.10%29.aspx
///
/// This generates a string with at least two of each of the following character
/// classes: uppercase letters, lowercase letters, and digits.
///
/// However, this method does not check for the existence of the username or
/// display name within the
/// generated password. The probability of that occurring is somewhat remote,
/// but could happen. If that is a concern, this method could be called repeatedly
/// until a string is returned that does not contain the username or display name.
/// </summary>
/// <param name="length">Password length, must be at least 6.</param>
/// <returns>The generated password</returns>
public static string GenerateRandomPassword(int length)
{
if (length < 6) throw new ArgumentException("length must be at least 6.");
StringBuilder pass = new StringBuilder();
// Temporary array containing our character set:
// uppercase letters, lowercase letters, and digits
char[] charSet = new char[62];
for( int i = 0; i < 26; i++) charSet[i] = (char)('A' + i); // Uppercase letters
for( int i = 26; i < 52; i++) charSet[i] = (char)('a' + i - 26); // Lowercase letters
for( int i = 52; i < 62; i++) charSet[i] = (char)('0' + i - 52); // Digits
// We generate two of each character class.
pass.Append(charSet[randGen.Next(0,26)]); // uppercase
pass.Append(charSet[randGen.Next(0, 26)]); // uppercase
pass.Append(charSet[randGen.Next(26, 52)]); // lowercase
pass.Append(charSet[randGen.Next(26, 52)]); // lowercase
pass.Append(charSet[randGen.Next(52,62)]); // digit
pass.Append(charSet[randGen.Next(52,62)]); // digit
// The rest of the password is randomly generated from the full character set
for (int i = pass.Length; i < length; i++ )
{
pass.Append(charSet[randGen.Next(0, charSet.Length)]);
}
// Shuffle the password using the Fisher-Yates random permutation technique
for (int i = 0; i < pass.Length; i++ )
{
int j = randGen.Next(i, pass.Length);
// Swap i and j
char tmp = pass[i];
pass[i] = pass[j];
pass[j] = tmp;
}
return pass.ToString();
}
// Non recursive group check (immediate membership only currently)
private bool IsUserInGroup(string username, string groupname)
{
using(GroupPrincipal group = GetGroupPrincipal(groupname))
{
if (group == null) return false;
using(UserPrincipal user = GetUserPrincipal(username))
{
if (user == null) return false;
return IsUserInGroup(user, group);
}
}
}
// Non recursive group check (immediate membership only currently)
private static bool IsUserInGroup(UserPrincipal user, GroupPrincipal group)
{
if (user == null || group == null) return false;
// This may seem a convoluted and strange way to check group membership.
// Especially because I could just call user.IsMemberOf(group).
// The reason for all of this is that IsMemberOf will throw an exception
// if there is an unresolvable SID in the list of group members. Unfortunately,
// even looping over the members with a standard foreach loop doesn't allow
// for catching the exception and continuing. Therefore, we need to use the
// IEnumerator object and iterate through the members carefully, catching the
// exception if it is thrown. I throw in a sanity check because there's no
// guarantee that MoveNext will actually move the enumerator forward when an
// exception occurs, although it has done so in my tests.
//
// For additional details, see the following bug:
// https://connect.microsoft.com/VisualStudio/feedback/details/453812/principaloperationexception-when-enumerating-the-collection-groupprincipal-members
PrincipalCollection members = group.Members;
bool ok = true;
int errorCount = 0; // This is a sanity check in case the loop gets out of control
IEnumerator<Principal> membersEnum = members.GetEnumerator();
while (ok)
{
try { ok = membersEnum.MoveNext(); }
catch (PrincipalOperationException)
{
m_logger.ErrorFormat("PrincipalOperationException when checking group membership for user {0} in group {1}." +
" This usually means that you have an unresolvable SID as a group member." +
" I strongly recommend that you fix this problem as soon as possible by removing the SID from the group. " +
" Ignoring the exception and continuing.",
user.Name, group.Name);
// Sanity check to avoid infinite loops
errorCount++;
if (errorCount > 1000) return false;
continue;
}
if (ok)
{
Principal principal = membersEnum.Current;
if (principal is UserPrincipal && principal.Sid == user.Sid)
return true;
}
}
return false;
}
private bool IsUserInGroup(UserPrincipal user, GroupInformation groupInfo)
{
using (GroupPrincipal group = GetGroupPrincipal(groupInfo.Name))
{
return IsUserInGroup(user, group);
}
}
private GroupPrincipal CreateOrGetGroupPrincipal(GroupInformation groupInfo)
{
GroupPrincipal group = null;
// If we have a SID, use that, otherwise name
group = GetGroupPrincipal(groupInfo.Name);
if (group == null)
{
// We create the GroupPrincipal, but https://connect.microsoft.com/VisualStudio/feedback/details/525688/invalidoperationexception-with-groupprincipal-and-sam-principalcontext-for-setting-any-property-always
// prevents us from then setting stuff on it.. so we then have to locate its relative DE
// and modify *that* instead. Oi.
using (group = new GroupPrincipal(m_machinePrincipal))
{
group.Name = groupInfo.Name;
group.Save();
using (DirectoryEntry newGroupDe = m_sam.Children.Add(groupInfo.Name, "Group"))
{
if (!string.IsNullOrEmpty(groupInfo.Description))
{
newGroupDe.Properties["Description"].Value = groupInfo.Description;
newGroupDe.CommitChanges();
}
}
// We have to re-fetch to get changes made via underlying DE
return GetGroupPrincipal(group.Name);
}
}
return group;
}
private UserPrincipal CreateOrGetUserPrincipal(UserInformation userInfo)
{
UserPrincipal user = null;
if ( ! LocalAccount.UserExists(userInfo.Username) )
{
// See note about MS bug in CreateOrGetGroupPrincipal to understand the mix of DE/Principal here:
using (user = new UserPrincipal(m_machinePrincipal))
{
user.Name = userInfo.Username;
user.SetPassword(userInfo.Password);
user.Description = "pGina created";
userInfo.Description = user.Description;
if (userInfo.PasswordEXP)
user.ExpirePasswordNow();
user.Save();
// Sync via DE
SyncUserPrincipalInfo(userInfo);
// We have to re-fetch to get changes made via underlying DE
return GetUserPrincipal(user.Name);
}
}
user = GetUserPrincipal(userInfo.Username);
if (user == null)
m_logger.ErrorFormat("Unable to get user principal for account that apparently exists: {0}", userInfo.Username);
return user;
}
private void SyncUserPrincipalInfo(UserInformation info)
{
using(DirectoryEntry userDe = m_sam.Children.Find(info.Username, "User"))
{
if (!string.IsNullOrEmpty(info.Description)) userDe.Properties["Description"].Value = info.Description;
if (!string.IsNullOrEmpty(info.Fullname)) userDe.Properties["FullName"].Value = info.Fullname;
if (!string.IsNullOrEmpty(info.usri4_home_dir)) userDe.Properties["HomeDirectory"].Value = info.usri4_home_dir.Replace("%u", info.Username);
if (!string.IsNullOrEmpty(info.usri4_home_dir_drive)) userDe.Properties["HomeDirDrive"].Value = info.usri4_home_dir_drive;
if (!info.Description.Contains("pgSMB"))
if (!string.IsNullOrEmpty(info.usri4_profile)) userDe.Properties["Profile"].Value = info.usri4_profile;
userDe.Invoke("SetPassword", new object[] { info.Password });
userDe.Properties["PasswordExpired"].Value = Convert.ToInt32(info.PasswordEXP);
userDe.CommitChanges();
}
}
private void AddUserToGroup(UserPrincipal user, GroupPrincipal group)
{
group.Members.Add(user);
group.Save();
}
private void RemoveUserFromGroup(UserPrincipal user, GroupPrincipal group)
{
group.Members.Remove(user);
group.Save();
}
public void SyncToLocalUser()
{
m_logger.Debug("SyncToLocalUser()");
using (UserPrincipal user = CreateOrGetUserPrincipal(UserInfo))
{
// Force password and fullname match (redundant if we just created, but oh well)
SyncUserPrincipalInfo(UserInfo);
try
{
List<SecurityIdentifier> ignoredSids = new List<SecurityIdentifier>(new SecurityIdentifier[] {
new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), // "Authenticated Users"
new SecurityIdentifier("S-1-1-0"), // "Everyone"
});
// First remove from any local groups they aren't supposed to be in
m_logger.Debug("Checking for groups to remove.");
List<GroupPrincipal> localGroups = LocalAccount.GetGroups(user);
foreach (GroupPrincipal group in localGroups)
{
m_logger.DebugFormat("Remove {0}?", group.Name);
// Skip ignored sids
if (!ignoredSids.Contains(group.Sid))
{
GroupInformation gi = new GroupInformation() { Name = group.Name, SID = group.Sid, Description = group.Description };
if (!UserInfo.InGroup(gi))
{
m_logger.DebugFormat("Removing user {0} from group {1}", user.Name, group.Name);
RemoveUserFromGroup(user, group);
}
}
group.Dispose();
}
// Now add to any they aren't already in that they should be
m_logger.Debug("Checking for groups to add");
foreach (GroupInformation groupInfo in UserInfo.Groups)
{
m_logger.DebugFormat("Add {0}?", groupInfo.Name);
if (!IsUserInGroup(user, groupInfo))
{
using (GroupPrincipal group = CreateOrGetGroupPrincipal(groupInfo))
{
m_logger.DebugFormat("Adding user {0} to group {1}", user.Name, group.Name);
AddUserToGroup(user, group);
}
}
}
}
catch (Exception e)
{
throw new GroupSyncException(e);
}
}
//set ntuser.dat permissions
if (!String.IsNullOrEmpty(UserInfo.usri4_profile) && !UserInfo.Description.Contains("pgSMB"))
{
Abstractions.WindowsApi.pInvokes.structenums.OSVERSIONINFOW verinfo = Abstractions.WindowsApi.pInvokes.VersionsInfo();
if (verinfo.dwMajorVersion == 0)
{
m_logger.WarnFormat("SyncToLocalUser: VersionsInfo() failed. I'm unable to detect OS beyond Windows 8.0");
verinfo.dwBuildNumber = Environment.OSVersion.Version.Build;
verinfo.dwMajorVersion = Environment.OSVersion.Version.Major;
verinfo.dwMinorVersion = Environment.OSVersion.Version.Minor;
verinfo.dwPlatformId = Environment.OSVersion.Version.Build;
}
string ProfileExtension = (Environment.OSVersion.Version.Major == 6) ? (verinfo.dwMinorVersion > 3)/*greater than 8.1*/ ? ".V5" : ".V2" : "";
if (Connect2share(UserInfo.usri4_profile + ProfileExtension, UserInfo.Username, UserInfo.Password, 3, false))
{
if (File.Exists(UserInfo.usri4_profile + ProfileExtension + "\\NTUSER.DAT"))
{
SetACL(UserInfo, ProfileExtension);
Connect2share(UserInfo.usri4_profile + ProfileExtension, null, null, 0, true);
}
else
{
Connect2share(UserInfo.usri4_profile + ProfileExtension, null, null, 0, true);
}
}
}
m_logger.Debug("End SyncToLocalUser()");
}
public static void SyncUserInfoToLocalUser(UserInformation userInfo)
{
LocalAccount la = new LocalAccount(userInfo);
la.SyncToLocalUser();
}
// Load userInfo.Username's group list and populate userInfo.Groups accordingly
public static void SyncLocalGroupsToUserInfo(UserInformation userInfo)
{
ILog logger = LogManager.GetLogger("LocalAccount.SyncLocalGroupsToUserInfo");
try
{
SecurityIdentifier EveryoneSid = new SecurityIdentifier("S-1-1-0");
SecurityIdentifier AuthenticatedUsersSid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
if (LocalAccount.UserExists(userInfo.Username))
{
using (UserPrincipal user = LocalAccount.GetUserPrincipal(userInfo.Username))
{
foreach (GroupPrincipal group in LocalAccount.GetGroups(user))
{
// Skip "Authenticated Users" and "Everyone" as these are generated
if (group.Sid == EveryoneSid || group.Sid == AuthenticatedUsersSid)
continue;
userInfo.AddGroup(new GroupInformation()
{
Name = group.Name,
Description = group.Description,
SID = group.Sid
});
}
}
}
}
catch(Exception e)
{
logger.ErrorFormat("Unexpected error while syncing local groups, skipping rest: {0}", e);
}
}
public void RemoveUserAndProfile(string user, int sessionID)
{
// First we have to work out where the users profile is on disk.
try
{
if (!String.IsNullOrEmpty(UserInfo.LocalProfilePath))
{
// instead of while (true)
if (File.Exists(UserInfo.LocalProfilePath + "\\NTUSER.DAT"))
{
bool inuse = true;
for (int x = 0; x < 60; x++)
{
try
{
using (FileStream isunloaded = File.Open(UserInfo.LocalProfilePath + "\\NTUSER.DAT", FileMode.Open, FileAccess.Read))
{
inuse = false;
break;
}
}
catch (Exception ex)
{
m_logger.DebugFormat("loop{1}:{0}", ex.Message, x);
Thread.Sleep(1000);
}
}
if (inuse)
{
return;
}
}
m_logger.DebugFormat("User {0} has profile in {1}, giving myself delete permission", user, UserInfo.LocalProfilePath);
try { Directory.Delete(UserInfo.LocalProfilePath, true); }
catch { }
RecurseDelete(UserInfo.LocalProfilePath);
}
// Now remove it from the registry as well
Abstractions.WindowsApi.pInvokes.DeleteProfile(UserInfo.SID);
Abstractions.Windows.User.DelProfileList(UserInfo.SID.ToString());
}
catch (KeyNotFoundException)
{
m_logger.DebugFormat("User {0} has no disk profile, just removing principal", user);
}
m_logger.Debug(@"removing SessionData 'SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\SessionData\" + sessionID.ToString() + "'");
try{Registry.LocalMachine.DeleteSubKeyTree(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\SessionData\" + sessionID.ToString(), false);}
catch {}
m_logger.Debug(@"removing SessionData 'SOFTWARE\Microsoft\Windows\CurrentVersion\NetCache\PurgeAtNextLogoff\" + UserInfo.SID + "'");
try{Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\NetCache\PurgeAtNextLogoff\", true).DeleteValue(UserInfo.SID.ToString(), false);}
catch {}
m_logger.Debug(@"removing SessionData 'SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Status\" + UserInfo.SID + "'");
try{Registry.LocalMachine.DeleteSubKeyTree(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Status\" + UserInfo.SID, false);}
catch {}
m_logger.Debug(@"removing SessionData 'SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\" + UserInfo.SID + "'");
try{Registry.LocalMachine.DeleteSubKeyTree(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\" + UserInfo.SID, false);}
catch {}
m_logger.Debug(@"removing SessionData 'SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\" + UserInfo.SID + "'");
try{Registry.LocalMachine.DeleteSubKeyTree(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\" + UserInfo.SID, false);}
catch {}
m_logger.Debug(@"removing SessionData 'SOFTWARE\Microsoft\Windows\CurrentVersion\GameUX\" + UserInfo.SID + "'");
try {Registry.LocalMachine.DeleteSubKeyTree(@"SOFTWARE\Microsoft\Windows\CurrentVersion\GameUX\" + UserInfo.SID, false);}
catch {}
m_logger.Debug(@"removing SessionData 'SOFTWARE\Microsoft\IdentityStore\Cache\" + UserInfo.SID + "'");
try {Registry.LocalMachine.DeleteSubKeyTree(@"SOFTWARE\Microsoft\IdentityStore\Cache\" + UserInfo.SID, false);}
catch {}
using (UserPrincipal userPrincipal = GetUserPrincipal(user))
{
try
{
userPrincipal.Delete();
}
catch (Exception ex)
{
m_logger.ErrorFormat("userPrincipal.Delete error:{0}", ex.Message);
}
}
m_logger.Debug(@"removing Profile 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" + UserInfo.SID + "'");
try { Registry.LocalMachine.DeleteSubKeyTree(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" + UserInfo.SID, false); }
catch { }
}
private static void RecurseDelete(string directory)
{
// m_logger.DebugFormat("Dir: {0}", directory);
if (!Directory.Exists(directory))
{
return;
}
DirectorySecurity dirSecurity = Directory.GetAccessControl(directory);
dirSecurity.AddAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().Name, FileSystemRights.FullControl, AccessControlType.Allow));
Directory.SetAccessControl(directory, dirSecurity);
File.SetAttributes(directory, FileAttributes.Normal);
DirectoryInfo di = new DirectoryInfo(directory);
if ((di.Attributes & FileAttributes.ReparsePoint) != 0)
{
// m_logger.DebugFormat("{0} is a reparse point, just deleting without recursing", directory);
Directory.Delete(directory, false);
return;
}
string[] files = Directory.GetFiles(directory);
string[] dirs = Directory.GetDirectories(directory);
// Files
foreach (string file in files)
{
try
{
// m_logger.DebugFormat("File: {0}", file);
FileSecurity fileSecurity = File.GetAccessControl(file);
fileSecurity.AddAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().Name, FileSystemRights.FullControl, AccessControlType.Allow));
File.SetAccessControl(file, fileSecurity); // Set the new access settings.
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
catch (Exception ex)
{
m_logger.Debug(ex.Message);
}
}
// Recurse each dir
foreach (string dir in dirs)
{
try
{
RecurseDelete(dir);
}
catch (Exception ex)
{
m_logger.Debug(ex.Message);
}
}
try
{
Directory.Delete(directory, false);
}
catch (Exception ex)
{
m_logger.Debug(ex.Message);
}
}
private static Boolean Connect2share(string share, string username, string password, uint retry, Boolean DISconnect)
{
if (DISconnect)
{
m_logger.DebugFormat("Disconnect from {0}", share);
if (!Abstractions.WindowsApi.pInvokes.DisconnectNetworkDrive(share))
{
m_logger.WarnFormat("unable to disconnect from {0}", share);
}
return true;
}
else
{
string[] server = SMBserver(share, false);
if (String.IsNullOrEmpty(server[0]))
{
m_logger.ErrorFormat("Can't extract SMB server from {0}", share);
return false;
}
server[0] += "\\" + username;
for (int x = 1; x <= retry; x++)
{
try
{
m_logger.DebugFormat("{0}. try to connect to {1} as {2}", x, share, server[0]);
if (!Abstractions.WindowsApi.pInvokes.MapNetworkDrive(share, server[0], password))
{
m_logger.ErrorFormat("Failed to connect to share {0}", share);
}
if (Directory.Exists(share))
{
return true;
}
Thread.Sleep(new TimeSpan(0, 0, 30));
}
catch (Exception ex)
{
m_logger.Error(ex.Message);
}
}
return false;
}
}
private static Boolean SetACL(UserInformation userInfo, string ProfileExtension)
{
if (!Abstractions.WindowsApi.pInvokes.RegistryLoad(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation.HKEY_LOCAL_MACHINE, userInfo.Username, userInfo.usri4_profile + ProfileExtension/*.V2|.V5*/ + "\\NTUSER.DAT"))
{
m_logger.WarnFormat("Can't load regfile {0}", userInfo.usri4_profile + ProfileExtension/*.V2|.V5*/ + "\\NTUSER.DAT");
return false;
}
if (!Abstractions.Windows.Security.RegSec(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation.HKEY_LOCAL_MACHINE, userInfo.Username, userInfo.Username))
{
m_logger.WarnFormat("Can't set ACL for regkey {0}\\{1}", Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation.HKEY_LOCAL_MACHINE.ToString(), userInfo.Username);
return false;
}
if (!Abstractions.WindowsApi.pInvokes.RegistryUnLoad(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation.HKEY_LOCAL_MACHINE, userInfo.Username))
{
m_logger.WarnFormat("Can't unload regkey {0}\\{1}", userInfo.usri4_profile + ProfileExtension/*.V2|.V5*/, "NTUSER.DAT");
return false;
}
return true;
}
private static string[] SMBserver(string share, Boolean visversa)
{
string[] ret = { null, null };
string[] server;
try
{
server = share.Trim('\\').Split('\\');
}
catch
{
m_logger.DebugFormat("can't split servername {0}", share);
return ret;
}
if (!String.IsNullOrEmpty(server[0]))
{
ret[0] = server[0];
ret[1] = server[0];
if (!visversa)
return ret;
try
{
IPHostEntry hostFQDN = Dns.GetHostEntry(server[0]);
if (hostFQDN.HostName.Equals(server[0], StringComparison.CurrentCultureIgnoreCase))
{
IPAddress[] hostIPs = Dns.GetHostAddresses(server[0]);
ret[1] = hostIPs[0].ToString();
}
else
{
ret[1] = hostFQDN.HostName;
}
}
catch (Exception ex)
{
m_logger.ErrorFormat("can't resolve FQDN of {0}:{1}", server[0], ex.Message);
return new string[] { null, null };
}
}
else
m_logger.DebugFormat("first token of servername {0} is null", share);
return ret;
}
/// <summary>
/// This is a faster technique for determining whether or not a user exists on the local
/// machine. UserPrincipal.FindByIdentity tends to be quite slow in general, so if
/// you only need to know whether or not the account exists, this method is much
/// faster.
/// </summary>
/// <param name="strUserName">The user name</param>
/// <returns>Whether or not the account with the given user name exists on the system</returns>
public static bool UserExists(string strUserName)
{
try
{
using (DirectoryEntry userEntry = LocalAccount.GetUserDirectoryEntry(strUserName))
{
return userEntry != null;
}
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Returns a list of groups of which the user is a member. It does so in a fashion that
/// may seem strange since one can call UserPrincipal.GetGroups, but seems to be much faster
/// in my tests.
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
private static List<GroupPrincipal> GetGroups(UserPrincipal user)
{
List<GroupPrincipal> result = new List<GroupPrincipal>();
// Get all groups using a PrincipalSearcher and
GroupPrincipal filter = new GroupPrincipal(m_machinePrincipal);
using (PrincipalSearcher searcher = new PrincipalSearcher(filter))
{
PrincipalSearchResult<Principal> sResult = searcher.FindAll();
foreach (Principal p in sResult)
{
if (p is GroupPrincipal)
{
GroupPrincipal gp = (GroupPrincipal)p;
if (LocalAccount.IsUserInGroup(user, gp))
result.Add(gp);
else
gp.Dispose();
}
else
{
p.Dispose();
}
}
}
return result;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include "ClassFactory.h"
#include "Dll.h"
#include "Provider.h"
#include "CredentialProviderFilter.h"
#pragma warning(push)
#pragma warning(disable : 4995)
#include <shlwapi.h>
#pragma warning(pop)
namespace pGina
{
namespace COM
{
CClassFactory::CClassFactory() : m_referenceCount(1)
{
}
// IUnknown
IFACEMETHODIMP CClassFactory::QueryInterface(__in REFIID riid, __deref_out void **ppv)
{
// Crazy ass v-table madness, yay COM!
static const QITAB qit[] =
{
QITABENT(CClassFactory, IClassFactory),
{ 0 },
};
return QISearch(this, qit, riid, ppv);
}
IFACEMETHODIMP_(ULONG) CClassFactory::AddRef()
{
return InterlockedIncrement(&m_referenceCount);
}
IFACEMETHODIMP_(ULONG) CClassFactory::Release()
{
LONG count = InterlockedDecrement(&m_referenceCount);
if (!count)
delete this;
return count;
}
// IClassFactory
IFACEMETHODIMP CClassFactory::CreateInstance(__in IUnknown* pUnkOuter, __in REFIID riid, __deref_out void **ppv)
{
HRESULT hr = CLASS_E_NOAGGREGATION;
*ppv = NULL;
if (!pUnkOuter)
{
if( IID_ICredentialProvider == riid )
{
pGina::CredProv::Provider* pProvider = new pGina::CredProv::Provider();
if (pProvider)
{
hr = pProvider->QueryInterface(riid, ppv);
pProvider->Release();
}
else
{
hr = E_OUTOFMEMORY;
}
}
else if( IID_ICredentialProviderFilter == riid )
{
pGina::CredProv::CredentialProviderFilter* pFilter =
new pGina::CredProv::CredentialProviderFilter();
if (pFilter)
{
hr = pFilter->QueryInterface(riid, ppv);
pFilter->Release();
}
else
{
hr = E_OUTOFMEMORY;
}
}
}
return hr;
}
IFACEMETHODIMP CClassFactory::LockServer(__in BOOL bLock)
{
if (bLock)
{
AddDllReference();
}
else
{
ReleaseDllReference();
}
return S_OK;
}
CClassFactory::~CClassFactory()
{
}
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Win32;
using log4net;
namespace pGina.CredentialProvider.Registration
{
class Program
{
public static readonly string EXE_NAME = "pGina.CredentialProvider.Registration.exe";
static Program()
{
// Init logging
pGina.Shared.Logging.Logging.Init();
}
static ILog m_logger = LogManager.GetLogger("Program");
static int Main(string[] args)
{
// Default settings
CredProviderManager manager = CredProviderManager.GetManager();
try
{
// Parse command line arguments
ParseClArgs(args, manager.CpInfo);
}
catch (Exception e)
{
m_logger.ErrorFormat("{0}" + Environment.NewLine + Environment.NewLine + "{1}",
e.Message, UsageText());
return 1;
}
// Check path for sanity
DirectoryInfo pathInfo = new DirectoryInfo(manager.CpInfo.Path);
if (! pathInfo.Exists )
{
m_logger.ErrorFormat("Path {0} doesn't exist or is not a directory.", manager.CpInfo.Path);
return 1;
}
// Do the work...
try
{
manager.ExecuteDefaultAction();
}
catch (Exception e)
{
m_logger.ErrorFormat("Error: {0}" + Environment.NewLine, e);
return 1;
}
return 0;
}
public static Settings ParseClArgs(string[] args, Settings settings)
{
int nArgs = args.Count();
// Process options
int idx = 0;
while (idx < nArgs)
{
// Long form args
if (args[idx].StartsWith("--"))
{
string opt = args[idx++].Substring(2);
string value = null;
if (idx < nArgs)
{
value = args[idx++];
}
switch (opt)
{
case "guid":
settings.ProviderGuid = new Guid(value);
break;
case "path":
settings.Path = value;
break;
case "mode":
{
switch (value)
{
case "install":
settings.OpMode = OperationMode.INSTALL;
break;
case "uninstall":
settings.OpMode = OperationMode.UNINSTALL;
break;
case "enable":
settings.OpMode = OperationMode.ENABLE;
break;
case "disable":
settings.OpMode = OperationMode.DISABLE;
break;
}
}
break;
case "dll":
settings.ShortName = value;
break;
default:
throw new Exception("Unknown option: " + opt);
}
}
// Short form arguments
else if (args[idx].StartsWith("-"))
{
string opt = args[idx++].Substring(1);
switch (opt)
{
case "h":
case "?":
throw new Exception("pGina Registration App Help");
default:
throw new Exception("Unknown option: " + opt);
}
}
else
{
break;
}
}
return settings;
}
public static string UsageText()
{
return String.Format(
"Usage: {0} [options] [Mode] <short_name>" + Environment.NewLine +
"-------------------------------------------------------------------------------" + Environment.NewLine +
" --mode <mode> The operating mode. One of install, uninstall, enable or " + Environment.NewLine +
" disable. " + Environment.NewLine +
" Default: INSTALL." + Environment.NewLine +
" --dll <name> The short name of the credential provider DLL." + Environment.NewLine +
Environment.NewLine +
" Options" + Environment.NewLine +
" --guid <guid> The Guid of the credential provider to be installed." + Environment.NewLine +
" Default is the pGina default Guid." + Environment.NewLine +
" --path <dir> Full or relative path to a directory containing the " + Environment.NewLine +
" CP DLL. The DLL may be located within a" + Environment.NewLine +
" subdirectory named x64 or Win32 (64 or 32 bit)." + Environment.NewLine +
" Defaults to the current directory." + Environment.NewLine +
" -h, -? Show this help text." + Environment.NewLine
, EXE_NAME);
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Windows.Forms;
using pGina.Service.Impl;
using log4net;
namespace Service
{
public partial class pGinaServiceHost : ServiceBase
{
private Thread m_serviceThread = null;
private pGina.Service.Impl.ServiceThread m_serviceThreadObj = null;
private ILog m_logger = LogManager.GetLogger("Pgina Service");
private Abstractions.WindowsApi.pInvokes.structenums.SERVICE_STATUS myServiceStatus;
public pGinaServiceHost()
{
InitializeComponent();
FieldInfo fi = typeof(ServiceBase).GetField("acceptedCommands", BindingFlags.Instance | BindingFlags.NonPublic);
int val = (int)fi.GetValue(this) | (int)Abstractions.WindowsApi.pInvokes.structenums.ServiceAccept.SERVICE_ACCEPT_PRESHUTDOWN;
fi.SetValue(this, val);
using (ServiceController sc = new ServiceController(this.ServiceName))
{
myServiceStatus.serviceType = (int)sc.ServiceType;
myServiceStatus.controlsAccepted = val;
myServiceStatus.serviceSpecificExitCode = 0;
myServiceStatus.win32ExitCode = 0;
Abstractions.WindowsApi.pInvokes.SetPreshutdownTimeout(sc.ServiceHandle, ref myServiceStatus);
}
}
protected override void OnStart(string[] args)
{
try
{
m_serviceThreadObj = new pGina.Service.Impl.ServiceThread();
m_serviceThread = new Thread(new ThreadStart(m_serviceThreadObj.Start));
m_serviceThread.Start();
new Thread(RunMessagePump).Start();
}
catch (Exception e)
{
EventLog.WriteEntry("pGina", e.ToString(), EventLogEntryType.Error);
throw;
}
}
void RunMessagePump()
{
Application.Run(new HiddenForm(m_serviceThreadObj));
}
protected override void OnStop()
{
WaitForServiceInit();
Application.Exit();
m_serviceThreadObj.Stop();
}
protected override void OnCustomCommand(int command)
{
WaitForServiceInit();
switch (command)
{
case (int)Abstractions.WindowsApi.pInvokes.structenums.ServiceControl.SERVICE_CONTROL_PRESHUTDOWN:
Thread postpone = new Thread(SignalShutdownPending);
postpone.Start();
break;
default:
base.OnCustomCommand(command);
break;
}
}
private void SignalShutdownPending()
{
m_logger.Info("Preshutdown Event received");
//DateTime end = DateTime.Now.AddMinutes(5);
//while (end.Ticks > DateTime.Now.Ticks) //delay shutdown to n minutes, testing only
while (m_serviceThreadObj.OnCustomCommand())
{
if (Abstractions.WindowsApi.pInvokes.ShutdownPending(this.ServiceHandle, ref myServiceStatus, new TimeSpan(0, 0, 500)))
{
//m_logger.Info("RequestAdditionalTime suceeded");
}
Thread.Sleep(250);
}
m_logger.Info("RequestAdditionalTime finished");
this.OnStop();
Abstractions.WindowsApi.pInvokes.SetServiceStopped(this.ServiceHandle, ref myServiceStatus);
}
/*
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
base.OnSessionChange(changeDescription);
WaitForServiceInit();
m_serviceThreadObj.SessionChange(changeDescription);
}*/
private void WaitForServiceInit()
{
lock (this)
{
// If we are still initializing, wait
if (m_serviceThread.IsAlive)
m_serviceThread.Join();
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include "WinlogonReal.h"
namespace pGina
{
namespace GINA
{
void RealWinlogonInterface::WlxUseCtrlAltDel()
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxUseCtrlAltDel(m_hWlx);
}
void RealWinlogonInterface::WlxSetContextPointer(void *newContext)
{
((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxSetContextPointer(m_hWlx, newContext);
}
void RealWinlogonInterface::WlxSasNotify(DWORD sas)
{
((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxSasNotify(m_hWlx, sas);
}
bool RealWinlogonInterface::WlxSetTimeout(DWORD newTimeout)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxSetTimeout(m_hWlx, newTimeout) ? true : false;
}
int RealWinlogonInterface::WlxAssignShellProtection(HANDLE token, HANDLE process, HANDLE thread)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxAssignShellProtection(m_hWlx, token, process, thread);
}
int RealWinlogonInterface::WlxMessageBox(HWND owner, LPWSTR text, LPWSTR title, UINT style)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxMessageBox(m_hWlx, owner, text, title, style);
}
int RealWinlogonInterface::WlxDialogBox(HANDLE hInst, LPWSTR lpszTemplate, HWND hwndOwner, DLGPROC dlgprc)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxDialogBox(m_hWlx, hInst, lpszTemplate, hwndOwner, dlgprc);
}
int RealWinlogonInterface::WlxDialogBoxParam(HANDLE hInst, LPWSTR lpszTemplate, HWND hwndOwner, DLGPROC dlgprc, LPARAM dwInitParam)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxDialogBoxParam(m_hWlx, hInst, lpszTemplate, hwndOwner, dlgprc, dwInitParam);
}
int RealWinlogonInterface::WlxDialogBoxIndirect(HANDLE hInst, LPCDLGTEMPLATE hDialogTemplate, HWND hwndOwner, DLGPROC dlgprc)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxDialogBoxIndirect(m_hWlx, hInst, hDialogTemplate, hwndOwner, dlgprc);
}
int RealWinlogonInterface::WlxDialogBoxIndirectParam(HANDLE hInst, LPCDLGTEMPLATE hDialogTemplate, HWND hwndOwner, DLGPROC dlgprc, LPARAM dwInitParam)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxDialogBoxIndirectParam(m_hWlx, hInst, hDialogTemplate, hwndOwner, dlgprc, dwInitParam);
}
int RealWinlogonInterface::WlxSwitchDesktopToUser()
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxSwitchDesktopToUser(m_hWlx);
}
int RealWinlogonInterface::WlxSwitchDesktopToWinlogon()
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxSwitchDesktopToWinlogon(m_hWlx);
}
int RealWinlogonInterface::WlxChangePasswordNotify(PWLX_MPR_NOTIFY_INFO pMprInfo, DWORD dwChangeInfo)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxChangePasswordNotify(m_hWlx, pMprInfo, dwChangeInfo);
}
bool RealWinlogonInterface::WlxGetSourceDesktop(PWLX_DESKTOP *ppDesktop)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxGetSourceDesktop(m_hWlx, ppDesktop) ? true : false;
}
bool RealWinlogonInterface::WlxSetReturnDesktop(PWLX_DESKTOP pDesktop)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxSetReturnDesktop(m_hWlx, pDesktop) ? true : false;
}
bool RealWinlogonInterface::WlxCreateUserDesktop(HANDLE hToken, DWORD Flags, PWSTR pszDesktopName, PWLX_DESKTOP *ppDesktop)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxCreateUserDesktop(m_hWlx, hToken, Flags, pszDesktopName, ppDesktop) ? true : false;
}
int RealWinlogonInterface::WlxChangePasswordNotifyEx(PWLX_MPR_NOTIFY_INFO pMprInfo, DWORD dwChangeInfo, PWSTR ProviderName, PVOID Reserved)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxChangePasswordNotifyEx(m_hWlx, pMprInfo, dwChangeInfo, ProviderName, Reserved);
}
bool RealWinlogonInterface::WlxCloseUserDesktop(PWLX_DESKTOP pDesktop, HANDLE hToken)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxCloseUserDesktop(m_hWlx, pDesktop, hToken) ? true : false;
}
bool RealWinlogonInterface::WlxSetOption(DWORD Option, ULONG_PTR Value, ULONG_PTR *OldValue)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxSetOption(m_hWlx, Option, Value, OldValue) ? true : false;
}
bool RealWinlogonInterface::WlxGetOption(DWORD Option, ULONG_PTR *Value)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxGetOption(m_hWlx, Option, Value) ? true : false;
}
void RealWinlogonInterface::WlxWin31Migrate()
{
((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxWin31Migrate(m_hWlx);
}
bool RealWinlogonInterface::WlxQueryClientCredentials(PWLX_CLIENT_CREDENTIALS_INFO_V1_0 pCred)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxQueryClientCredentials(pCred) ? true : false;
}
bool RealWinlogonInterface::WlxQueryInetConnectorCredentials(PWLX_CLIENT_CREDENTIALS_INFO_V1_0 pCred)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxQueryInetConnectorCredentials(pCred) ? true : false;
}
bool RealWinlogonInterface::WlxDisconnect()
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxDisconnect() ? true : false;
}
int RealWinlogonInterface::WlxQueryTerminalServicesData(PWLX_TERMINAL_SERVICES_DATA pTSData, WCHAR *UserName, WCHAR *Domain)
{
return ((PWLX_DISPATCH_VERSION_1_3)m_pFuncTable)->WlxQueryTerminalServicesData(m_hWlx, pTSData, UserName, Domain);
}
int RealWinlogonInterface::WlxQueryConsoleSwitchCredentials(PWLX_CONSOLESWITCH_CREDENTIALS_INFO_V1_0 pCred)
{
// Must be at 1_4 for this call
if(WinlogonInterface::Version() <= WLX_VERSION_1_3)
return 0;
return ((PWLX_DISPATCH_VERSION_1_4)m_pFuncTable)->WlxQueryConsoleSwitchCredentials(pCred);
}
bool RealWinlogonInterface::WlxQueryTsLogonCredentials(PWLX_CLIENT_CREDENTIALS_INFO_V2_0 pCred)
{
// Must be at 1_4 for this call
if(WinlogonInterface::Version() <= WLX_VERSION_1_3)
return 0;
return ((PWLX_DISPATCH_VERSION_1_4)m_pFuncTable)->WlxQueryTsLogonCredentials(pCred) ? true : false;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using pGina.Shared.Settings;
namespace pGina.Plugin.SingleUser
{
public partial class Configuration : Form
{
public Configuration()
{
InitializeComponent();
SettingsToUi();
}
public void SettingsToUi()
{
m_txtUser.Text = Settings.Store.Username;
m_txtDomain.Text = Settings.Store.Domain;
m_txtPass.Text = Settings.Store.GetEncryptedSetting("Password", null);
substituteCB.Checked = Settings.Store.RequirePlugins;
allRB.Checked = Settings.Store.RequireAllPlugins;
anyRB.Checked = !allRB.Checked;
string[] plugins = Settings.Store.RequiredPluginList;
foreach (string uuid in plugins)
{
m_dgv.Rows.Add(new string[] { uuid });
}
maskUI();
}
public bool SaveSettings()
{
Settings.Store.Username = m_txtUser.Text;
Settings.Store.Domain = m_txtDomain.Text;
Settings.Store.SetEncryptedSetting("Password", m_<PASSWORD>, null);
Settings.Store.RequirePlugins = substituteCB.Checked;
Settings.Store.RequireAllPlugins = allRB.Checked;
List<string> uuids = new List<string>();
foreach (DataGridViewRow row in m_dgv.Rows)
{
if (row.Cells[0].Value != null)
uuids.Add((string) row.Cells[0].Value);
}
Settings.Store.RequiredPluginList = uuids.ToArray();
return true;
}
private void btnOk_Click(object sender, EventArgs e)
{
if (SaveSettings())
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
private void requirePluginCheckChange(object sender, EventArgs e)
{
maskUI();
}
private void maskUI()
{
anyRB.Enabled = substituteCB.Checked;
allRB.Enabled = substituteCB.Checked;
m_dgv.Enabled = substituteCB.Checked;
}
private void Btn_help(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/single_user.html");
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using Abstractions.Logging;
using Abstractions.WindowsApi;
using System.Security.AccessControl;
using Microsoft.Win32;
using System.IO;
namespace Abstractions.Windows
{
public static class Security
{
public static SecurityIdentifier GetWellknownSID(WellKnownSidType type)
{
return new SecurityIdentifier(type, null);
}
public static string GetWellKnownName(WellKnownSidType type)
{
return GetNameFromSID(GetWellknownSID(type));
}
public static string GetNameFromSID(SecurityIdentifier sid)
{
NTAccount ntAccount = (NTAccount)sid.Translate(typeof(NTAccount));
return ntAccount.ToString();
}
public static SecurityIdentifier GetSIDFromName(string name)
{
NTAccount ntAccount = new NTAccount(name);
return (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier));
}
/// <summary>
/// apply registry security settings to user profiles
/// </summary>
/// <param name="where"></param>
/// <param name="keyname"></param>
/// <param name="username"></param>
/// <returns></returns>
public static Boolean RegSec(pInvokes.structenums.RegistryLocation where, string keyname, string username)
{
try
{
IdentityReference UserIRef = new NTAccount(String.Format("{0}\\{1}", Environment.MachineName, username));
SecurityIdentifier UserSid = (SecurityIdentifier)UserIRef.Translate(typeof(SecurityIdentifier));
using (RegistryKey key = pInvokes.GetRegistryLocation(where).OpenSubKey(keyname, true))
{
RegistrySecurity keySecurity = key.GetAccessControl(AccessControlSections.Access);
string SDDL = keySecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All);
//LibraryLogging.Info(SDDL);
foreach (RegistryAccessRule user in keySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
{
//LibraryLogging.Info("registry ACE user: {0} {1} {2}", key.Name, user.InheritanceFlags.ToString(), user.IdentityReference.Value);
if (user.IdentityReference.Value.StartsWith("S-1-5-21-") && !user.IdentityReference.Value.Equals(UserIRef.Value))
{
//LibraryLogging.Info("mod registry ACE:{0} from unknown user:{1} to {2} {3} {4}", key.Name, user.IdentityReference.Value, username, user.RegistryRights.ToString(), user.AccessControlType.ToString());
SDDL = SDDL.Replace(user.IdentityReference.Value, UserSid.Value);
//LibraryLogging.Info(SDDL);
keySecurity.SetSecurityDescriptorSddlForm(SDDL);
key.SetAccessControl(keySecurity);
break;
}
}
foreach (string subkey in key.GetSubKeyNames())
{
if (!RegSec(where, keyname + "\\" + subkey, username))
{
return false;
}
}
}
}
catch (SystemException ex)
{
LibraryLogging.Warn("RegSec:{0} Warning {1}", keyname, ex.Message);
}
catch (Exception ex)
{
LibraryLogging.Error("RegSec:{0} Error:{1}", keyname, ex.Message);
return false;
}
return true;
}
/// <summary>
/// apply recursive attribute to directories and files
/// </summary>
/// <param name="dir"></param>
/// <param name="attrib"></param>
/// <returns></returns>
public static Boolean SetRecDirAttrib(DirectoryInfo dir, FileAttributes attrib)
{
try
{
foreach (DirectoryInfo subDirPath in dir.GetDirectories())
{
subDirPath.Attributes = attrib;
SetRecDirAttrib(subDirPath, attrib);
}
foreach (FileInfo filePath in dir.GetFiles())
{
filePath.Attributes = attrib;
}
}
catch (Exception ex)
{
LibraryLogging.Error("Cant't set attrib {0} on {1} Error:{2}", attrib, dir, ex.Message);
return false;
}
return true;
}
/// <summary>
/// remove users who are unknown to the system from the directory acl
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
public static Boolean RemoveAccRuleFromUnknownUser(string dir)
{
DirectoryInfo dInfo = new DirectoryInfo(dir);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
try
{
foreach (FileSystemAccessRule user in dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
{
//LibraryLogging.Debug("directory ACE user: {0}", user.IdentityReference.Value);
if (user.IdentityReference.Value.StartsWith("S-1-5-21-"))
{
LibraryLogging.Debug("delete unknown directory ACE from {0} in {1}", user.IdentityReference.Value, dir);
dSecurity.RemoveAccessRule(user);
}
}
}
catch (Exception ex)
{
LibraryLogging.Error("unable to RemoveAccRuleFromUnknownUser for {0} error {1}", dir, ex.Message);
return false;
}
return true;
}
public static Boolean SetDirectorySecurity(string dir, IdentityReference[] Account, FileSystemRights Rights, AccessControlType ControlType, InheritanceFlags Inherit, PropagationFlags Propagation)
{
DirectoryInfo dInfo = new DirectoryInfo(dir);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
try
{
foreach (IdentityReference account in Account)
{
dSecurity.AddAccessRule(new FileSystemAccessRule(account, Rights, Inherit, Propagation, ControlType));
}
dInfo.SetAccessControl(dSecurity);
}
catch (Exception ex)
{
LibraryLogging.Error("unable to SetDirectorySecurity for {0} error {1}", dir, ex.Message);
return false;
}
return true;
}
public static Boolean SetDirectorySecurity(string dir, string[] Account, FileSystemRights Rights, AccessControlType ControlType, InheritanceFlags Inherit, PropagationFlags Propagation)
{
DirectoryInfo dInfo = new DirectoryInfo(dir);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
try
{
foreach (string account in Account)
{
dSecurity.AddAccessRule(new FileSystemAccessRule(account, Rights, Inherit, Propagation, ControlType));
}
dInfo.SetAccessControl(dSecurity);
}
catch (Exception ex)
{
LibraryLogging.Error("unable to SetDirectorySecurity for {0} error {1}", dir, ex.Message);
return false;
}
return true;
}
public static Boolean ReplaceDirectorySecurity(string dir, IdentityReference[] Account, FileSystemRights Rights, AccessControlType ControlType, InheritanceFlags Inherit, PropagationFlags Propagation)
{
DirectoryInfo dInfo = new DirectoryInfo(dir);
DirectorySecurity dSecurity = new DirectorySecurity();
try
{
dSecurity.SetAccessRuleProtection(true, false);
foreach (IdentityReference account in Account)
{
dSecurity.ResetAccessRule(new FileSystemAccessRule(account, Rights, Inherit, Propagation, ControlType));
}
dInfo.SetAccessControl(dSecurity);
}
catch (Exception ex)
{
LibraryLogging.Error("unable to ReplaceDirectorySecurity for {0} error {1}", dir, ex.Message);
return false;
}
return true;
}
public static Boolean ReplaceDirectorySecurity(string dir, string[] Account, FileSystemRights Rights, AccessControlType ControlType, InheritanceFlags Inherit, PropagationFlags Propagation)
{
DirectoryInfo dInfo = new DirectoryInfo(dir);
DirectorySecurity dSecurity = new DirectorySecurity();
try
{
dSecurity.SetAccessRuleProtection(true, false);
foreach (string account in Account)
{
dSecurity.ResetAccessRule(new FileSystemAccessRule(account, Rights, Inherit, Propagation, ControlType));
}
dInfo.SetAccessControl(dSecurity);
}
catch (Exception ex)
{
LibraryLogging.Error("unable to ReplaceDirectorySecurity for {0} error {1}", dir, ex.Message);
return false;
}
return true;
}
public static Boolean ReplaceFileSecurity(string File, IdentityReference[] Account, FileSystemRights Rights, AccessControlType ControlType, InheritanceFlags Inherit, PropagationFlags Propagation)
{
FileInfo fInfo = new FileInfo(File);
FileSecurity fSecurity = fInfo.GetAccessControl();
try
{
fSecurity.SetAccessRuleProtection(true, false);
foreach (IdentityReference account in Account)
{
fSecurity.ResetAccessRule(new FileSystemAccessRule(account, Rights, Inherit, Propagation, ControlType));
}
fInfo.SetAccessControl(fSecurity);
}
catch (Exception ex)
{
LibraryLogging.Error("unable to ReplaceFileSecurity for {0} error {1}", File, ex.Message);
return false;
}
return true;
}
public static Boolean ReplaceFileSecurity(string File, string[] Account, FileSystemRights Rights, AccessControlType ControlType, InheritanceFlags Inherit, PropagationFlags Propagation)
{
FileInfo fInfo = new FileInfo(File);
FileSecurity fSecurity = fInfo.GetAccessControl();
try
{
fSecurity.SetAccessRuleProtection(true, false);
foreach (string account in Account)
{
fSecurity.ResetAccessRule(new FileSystemAccessRule(account, Rights, Inherit, Propagation, ControlType));
}
fInfo.SetAccessControl(fSecurity);
}
catch (Exception ex)
{
LibraryLogging.Error("unable to ReplaceFileSecurity for {0} error {1}", File, ex.Message);
return false;
}
return true;
}
public static Boolean SetDirOwner(string dir, IdentityReference Account)
{
DirectoryInfo dInfo = new DirectoryInfo(dir);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
try
{
dSecurity.SetOwner(Account);
dInfo.SetAccessControl(dSecurity);
}
catch (Exception ex)
{
LibraryLogging.Error("SetDirOwner unable to SetOwner for {0} error {1}", dir, ex.Message);
return false;
}
return true;
}
public static Boolean SetDirOwner(string dir, string Account)
{
DirectoryInfo dInfo = new DirectoryInfo(dir);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
IdentityReference User = new NTAccount(String.Format("{0}\\{1}",Environment.MachineName, Account));
try
{
dSecurity.SetOwner(User);
dInfo.SetAccessControl(dSecurity);
}
catch (Exception ex)
{
LibraryLogging.Error("SetDirOwner unable to SetOwner for {0} error {1}", dir, ex.Message);
return false;
}
return true;
}
}
}
<file_sep>using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Diagnostics;
namespace proquota
{
public partial class Form1 : Form
{
private string over_max_warning_title = "";
private string over_max_error_title = "";
private string over_max_error_text = "";
private string over_max_free = "";
private string over_max_exceeded = "";
private string over_max_userprofile = "";
private string over_max_calculate_text = "";
private string exclude_dir = "";
private System.Windows.Forms.Form top;
private Thread msg;
private Thread onchanged;
private long uPath_rest;
private bool? over_max = null;
private bool mouseover = false;
private long mouseover_timer = DateTime.UtcNow.Ticks;
private Point mouse_pos = Point.Empty;
private ReaderWriterLockSlim mouseoverlock = new ReaderWriterLockSlim();
private ReaderWriterLockSlim Calculon_Lock = new ReaderWriterLockSlim(); //does it calc == locked, or sleep == unlocked
private ReaderWriterLockSlim LastEventTriggered_lock = new ReaderWriterLockSlim();
private ReaderWriterLockSlim BallonTip_Lock = new ReaderWriterLockSlim();
private long LastEventTriggered = 0;
private const int sleep_timer = 100;
private const int Balloon_sleep = 5000;
private long mouse_hover = 0;
#region pinvoke
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool ShutdownBlockReasonCreate(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] string pwszReason);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool ShutdownBlockReasonDestroy(IntPtr hWnd);
///<summary>
/// Flags that define appearance and behaviour of a standard message box displayed by a call to the MessageBox function.
/// </summary>
[Flags]
public enum MessageBoxOptions : uint
{
OkOnly = 0x000000,
OkCancel = 0x000001,
AbortRetryIgnore = 0x000002,
YesNoCancel = 0x000003,
YesNo = 0x000004,
RetryCancel = 0x000005,
CancelTryContinue = 0x000006,
IconHand = 0x000010,
IconQuestion = 0x000020,
IconExclamation = 0x000030,
IconAsterisk = 0x000040,
UserIcon = 0x000080,
IconWarning = IconExclamation,
IconError = IconHand,
IconInformation = IconAsterisk,
IconStop = IconHand,
DefButton1 = 0x000000,
DefButton2 = 0x000100,
DefButton3 = 0x000200,
DefButton4 = 0x000300,
ApplicationModal = 0x000000,
SystemModal = 0x001000,
TaskModal = 0x002000,
Help = 0x004000,
NoFocus = 0x008000,
SetForeground = 0x010000,
DefaultDesktopOnly = 0x020000,
Topmost = 0x040000,
Right = 0x080000,
RTLReading = 0x100000
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern uint MessageBox(IntPtr hWnd, String text, String caption, MessageBoxOptions options);
#endregion
#region http://csharptest.net/1043/how-to-prevent-users-from-killing-your-service-process/
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool GetKernelObjectSecurity(IntPtr Handle, int securityInformation, [Out] byte[] pSecurityDescriptor, uint nLength, out uint lpnLengthNeeded);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool SetKernelObjectSecurity(IntPtr Handle, int securityInformation, [In] byte[] pSecurityDescriptor);
internal RawSecurityDescriptor GetProcessSecurityDescriptor(IntPtr processHandle)
{
const int DACL_SECURITY_INFORMATION = 0x00000004;
byte[] psd = new byte[0];
uint bufSizeNeeded;
RawSecurityDescriptor ret = null;
// Call with 0 size to obtain the actual size needed in bufSizeNeeded
GetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, psd, 0, out bufSizeNeeded);
if (bufSizeNeeded < 0 || bufSizeNeeded > short.MaxValue)
{
Program.Log(String.Format("GetKernelObjectSecurity get size error:{0}", Abstractions.WindowsApi.pInvokes.LastError()), EventLogEntryType.Error);
}
else
{
// Allocate the required bytes and obtain the DACL
psd = new byte[bufSizeNeeded];
if (!GetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, psd, bufSizeNeeded, out bufSizeNeeded))
{
Program.Log(String.Format("GetKernelObjectSecurity get DACL error:{0}", Abstractions.WindowsApi.pInvokes.LastError()), EventLogEntryType.Error);
}
else
{
// Use the RawSecurityDescriptor class from System.Security.AccessControl to parse the bytes:
ret = new RawSecurityDescriptor(psd, 0);
}
}
return ret;
}
internal bool SetProcessSecurityDescriptor(IntPtr processHandle, RawSecurityDescriptor dacl)
{
const int DACL_SECURITY_INFORMATION = 0x00000004;
byte[] rawsd = new byte[dacl.BinaryLength];
dacl.GetBinaryForm(rawsd, 0);
if (!SetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, rawsd))
{
Program.Log(String.Format("SetKernelObjectSecurity error:{0}", Abstractions.WindowsApi.pInvokes.LastError()), EventLogEntryType.Error);
return false;
}
return true;
}
#endregion
public void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
Program.Log(String.Format("Application_ThreadException:\n{0}", e.Exception.ToString()), EventLogEntryType.Error);
Application.Exit();
}
public Form1()
{
InitializeComponent();
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
setACE();
getSettings();
this.Text = over_max_error_title;
// wait until userinit doesnt run anymore
//Program.Log("wait for userinit", EventLogEntryType.Information);
try
{
for (int x = 0; x < 60; x++ )
{
if (Process.GetProcessesByName("userinit").Length == 0)
{
if (Process.GetProcessesByName("explorer").Length > 0)
{
break;
}
}
Thread.Sleep(1000);
}
}
catch
{
Program.Log("exception userinit", EventLogEntryType.Information);
}
//Program.Log("no userinit", EventLogEntryType.Information);
notifyIcon1.MouseMove += new MouseEventHandler(OnMouseOver);
notifyIcon1.BalloonTipShown += new EventHandler(OnBalloonTipShown);
// polling
onchanged = new Thread(Calculon);
onchanged.Start();
//mouse pos polling
Thread mousepos = new Thread(MousePos);
mousepos.Start();
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = proquota.Program.uPath;
watcher.IncludeSubdirectories = true;
watcher.Filter= "";
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.DirectoryName | NotifyFilters.FileName;
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void setACE()
{
IntPtr hProcess = System.Diagnostics.Process.GetCurrentProcess().Handle; //get handle
RawSecurityDescriptor RawSecDesc = GetProcessSecurityDescriptor(hProcess); //get current SDDL
if (RawSecDesc == null)
{
Application.Exit();
}
RawSecurityDescriptor RawSecDesc_new = new RawSecurityDescriptor("D:"); //start from scratch
foreach (CommonAce genACE in RawSecDesc.DiscretionaryAcl)
{
if (genACE.SecurityIdentifier.IsWellKnown(WellKnownSidType.LogonIdsSid)) //the logon Session
{
genACE.AccessMask &= ~(0x00040000 /*WRITE_DAC*/| 0x00080000 /*WRITE_OWNER*/| 0x0001 /*PROCESS_CREATE_PROCESS*/);
}
if (genACE.SecurityIdentifier == WindowsIdentity.GetCurrent().User) //the logged in user
{
genACE.AccessMask &= ~(0x00040000 /*WRITE_DAC*/| 0x00080000 /*WRITE_OWNER*/| 0x0001 /*PROCESS_CREATE_PROCESS*/);
}
RawSecDesc_new.DiscretionaryAcl.InsertAce(0, genACE);
}
if (!SetProcessSecurityDescriptor(hProcess, RawSecDesc_new))
{
Application.Exit();
}
}
private void getSettings()
{
try
{
Abstractions.Settings.DynamicSettings settings = new Abstractions.Settings.DynamicSettings(pGina.Plugin.pgSMB2.PluginImpl.PluginUuid, "global");
Dictionary<string,string> set = settings.GetSettings(new string[] {});
foreach (string text in set["MaxStoreText"].Split('\0'))
{
string name = text.Split(new char[] { '\t' }, 2).First();
string value = text.Split(new char[] { '\t' }, 2).Last();
switch (name)
{
case "MaxStoreUserprofile":
over_max_userprofile = value.Trim();
break;
case "MaxStorefree":
over_max_free = value.Trim();
break;
case "MaxStoreExceeded":
over_max_exceeded = value.Trim();
break;
case "MaxStoreWarningTitle":
over_max_warning_title = value.Trim();
break;
case "MaxStoreErrorTitle":
over_max_error_title = value.Trim();
break;
case "MaxStoreErrorText":
over_max_error_text = value.Trim();
break;
case "MaxStoreCalculateText":
over_max_calculate_text = value.Trim();
break;
}
}
exclude_dir = set["MaxStoreExclude"];
top = new System.Windows.Forms.Form();
msg = new Thread(() => MsgBox("is not null", "init"));
}
catch (Exception ex)
{
Program.Log(String.Format("Error in getSettings():{0}", ex.ToString()), EventLogEntryType.Error);
Application.Exit();
}
}
private void OnBalloonTipShown(object Sender, EventArgs e)
{
Thread ballon = new Thread(BalloonTipShown);
ballon.Start();
}
private void BalloonTipShown()
{
try
{
if (BallonTip_Lock.TryEnterWriteLock(Convert.ToInt32(Balloon_sleep*0.75)))
{
//Program.Log(String.Format("BalloonTipShown thread:{0} Locked", Thread.CurrentThread.ManagedThreadId), EventLogEntryType.Error);
Thread.Sleep(Balloon_sleep);
}
}
catch { }
finally
{
if (BallonTip_Lock.IsWriteLockHeld)
{
BallonTip_Lock.ExitWriteLock();
//Program.Log(String.Format("BalloonTipShown thread:{0} unlocked", Thread.CurrentThread.ManagedThreadId), EventLogEntryType.Error);
}
}
}
private void OnMouseOver(object Sender, MouseEventArgs e)
{
//win 10 crap triggers a MouseMove event on the notify icon when user got logged in
//and if you call the taskmanager from the taskbar
long now = DateTime.UtcNow.Ticks;
if (now > mouse_hover)
{
//Program.Log(String.Format("mouseover event trashed"), EventLogEntryType.Information);
mouse_hover = now + (20 * TimeSpan.TicksPerMillisecond);
return;
}
//Program.Log(String.Format("mouseover event"), EventLogEntryType.Information);
Thread mouse_over = new Thread(() => MouseOver(Cursor.Position));
mouse_over.Start();
}
private void MouseOver(Point mouse_point)
{
long now = DateTime.UtcNow.Ticks;
long delay = 3 * 1000 * TimeSpan.TicksPerMillisecond;
try
{
if (mouseoverlock.TryEnterWriteLock(0))
{
mouse_pos = mouse_point;
if (mouseover_timer + delay < now)
{
mouseover = true;
mouseover_timer = now;
//Program.Log(String.Format("mouseover enabled:{0} mouse_pos:{1}", Thread.CurrentThread.ManagedThreadId, mouse_pos.ToString()), EventLogEntryType.Information);
}
}
}
catch
{
return;
}
finally
{
if (mouseoverlock.IsWriteLockHeld)
{
mouseoverlock.ExitWriteLock();
}
}
}
private void MousePos()
{
while (true)
{
Thread.Sleep(1000);
Point mouse_pos_cur = Cursor.Position;
Point mouse_pos_old = Point.Empty;
try
{
if (mouseoverlock.TryEnterReadLock(0))
{
mouse_pos_old = mouse_pos;
}
}
catch
{
return;
}
finally
{
if (mouseoverlock.IsReadLockHeld)
{
mouseoverlock.ExitReadLock();
}
}
if (!mouse_pos_old.IsEmpty && mouse_pos_cur.X == mouse_pos_old.X && mouse_pos_cur.Y == mouse_pos_old.Y)
{
//Program.Log(String.Format("init MouseOver mouse_pos_old={0} mouse_pos_cur={1}", mouse_pos_old.ToString(), mouse_pos_cur.ToString()), EventLogEntryType.Information);
MouseOver(mouse_pos_cur);
}
}
}
private void OnChanged(object source, FileSystemEventArgs e)
{
// http://stackoverflow.com/questions/239988/filesystemwatcher-vs-polling-to-watch-for-file-changes
// The FileSystemWatcher may also miss changes during busy times, if the number of queued changes overflows the buffer provided.
// This is not a limitation of the .NET class per se, but of the underlying Win32 infrastructure.
// In our experience, the best way to minimize this problem is to dequeue the notifications as quickly as possible and deal with them on another thread.
// As mentioned by @ChillTemp above, the watcher may not work on non-Windows shares. For example, it will not work at all on mounted Novell drives.
// I agree that a good compromise is to do an occasional poll to pick up any missed changes.
// sure you can use override FileSystemWatcher.OnError (FileSystemWatcher.InternalBufferSize, InternalBufferOverflowException)
// and do a "poll" (Calculon()) to reget control of all files again
// but than you need to call your threads in order, or you will mess up
// real world: delete file -> create a file -> modify file
// unsorted threads: create a file -> modify file -> delete file
// Ill do it the other way arround
// As soon as the events triggered drops below a limit. Ill do a "poll" (Calculon()) on all files
Thread onchanged = new Thread(() => OnChanged(e, DateTime.UtcNow.Ticks));
onchanged.Start();
}
private void OnChanged(FileSystemEventArgs e, long ticks)
{
string path = e.FullPath;
string path_root = Path.GetPathRoot(path);
// is this file or folder part of our exlusion
while (!path.Equals(path_root))
{
if (Regex.IsMatch(path, exclude_dir))
{
//Program.Log(String.Format("path exclude:{0}", e.FullPath), EventLogEntryType.Warning);
return;
}
path = Path.GetDirectoryName(path);
}
// is it a directory
try
{
FileAttributes attr = File.GetAttributes(e.FullPath);
if (attr.HasFlag(FileAttributes.Directory))
{
//Program.Log(String.Format("path directory:{0}", e.FullPath), EventLogEntryType.Warning);
return;
}
}
catch { }
// its a file and we care about it
// the time may not be exact but thats not so important
try
{
if (LastEventTriggered_lock.TryEnterWriteLock(-1))
{
LastEventTriggered = ticks;
//Program.Log(String.Format("LastEventTriggered = {0}\n{1}", LastEventTriggered, e.FullPath), EventLogEntryType.Information);
}
}
catch { }
finally
{
LastEventTriggered_lock.ExitWriteLock();
}
}
private void Calculon()
{
bool domouse = true;
pGina.Plugin.pgSMB2.Roaming ro = new pGina.Plugin.pgSMB2.Roaming();
long trigger = 500 * TimeSpan.TicksPerMillisecond;
long poll = 60 * 1000 * TimeSpan.TicksPerMillisecond;
long lastrun = -1;
int sleep_write_lock = Convert.ToInt32(sleep_timer/10);
long timer = 0;
while (true)
{
Thread.Sleep(sleep_timer);
try
{
if (mouseoverlock.TryEnterReadLock(-1))
{
if (mouseover)
{
domouse = true;
mouseover = false;
}
}
}
catch { }
finally
{
mouseoverlock.ExitReadLock();
}
try
{
if (LastEventTriggered_lock.TryEnterWriteLock(sleep_write_lock))
{
long nowticks = DateTime.UtcNow.Ticks;
if (!domouse) // mouseover always force a recalculation
{
//Program.Log(String.Format("{0} == {1}", LastEventTriggered, lastrun), EventLogEntryType.Information);
if (LastEventTriggered == lastrun) // nothing happend
{
continue;
}
// es ist was pasiert
//Program.Log(String.Format("{0} > {1}", trigger, nowticks - LastEventTriggered), EventLogEntryType.Information);
if (trigger > nowticks - LastEventTriggered) // less than 500 ms have passed since the last event
{
if (timer == 0) // set timer to current time
{
timer = nowticks;
}
//Program.Log(String.Format("{0} > {1}", nowticks - timer, poll), EventLogEntryType.Information);
if (nowticks - timer < poll) // less than 60 sec have passed since we wait for events to no longer occur
{
continue;
}
}
}
}
else
{
continue;
}
}
catch { }
finally
{
if (LastEventTriggered_lock.IsWriteLockHeld)
{
LastEventTriggered_lock.ExitWriteLock();
}
}
if (domouse)
{
try
{
if (BallonTip_Lock.TryEnterReadLock(0))
{
notifyIcon1.ShowBalloonTip(1000, "", String.Format("{0}\n{1}", over_max_userprofile, over_max_calculate_text), ToolTipIcon.Info);
}
}
catch { }
finally
{
if (BallonTip_Lock.IsReadLockHeld)
{
BallonTip_Lock.ExitReadLock();
}
}
}
//Program.Log(String.Format("Calculon lastrun = {0}", lastrun), EventLogEntryType.Information);
lastrun = LastEventTriggered;
timer = 0;
try
{
if (Calculon_Lock.TryEnterWriteLock(-1))
{
long uPath_size = ro.GetDirectorySize(proquota.Program.uPath, exclude_dir);
if (uPath_size == 0)
{
continue;
}
uPath_size = Convert.ToInt64(uPath_size / 1024);
bool? over_max_old = over_max;
uPath_rest = Program.uPath_size_max - uPath_size;
if (uPath_size < Program.uPath_size_max - (Convert.ToInt64(Program.uPath_size_max / 20))) //fits
{
over_max = null;
}
else //fits barely
{
if (uPath_size > Program.uPath_size_max) //oversized
{
over_max = true;
}
else
{
over_max = false;
}
}
if (over_max != over_max_old)
{
switch (over_max)
{
case null:
notifyIcon1.Icon = new Icon(Properties.Resources._1, 16, 16);
notifyIcon1.ShowBalloonTip(1000, "", String.Format("{0}\n{1} {2} {3:0.00} {4} {5}", over_max_userprofile, uPath_rest.ToString(), "KBytes", (double)uPath_rest / 1024, "MBytes", over_max_free), ToolTipIcon.Info);
if (msg.IsAlive)
{
top.Close();
}
break;
case false:
notifyIcon1.Icon = new Icon(Properties.Resources._2, 16, 16);
notifyIcon1.ShowBalloonTip(1000, "", String.Format("{0}\n{1} {2} {3:0.00} {4} {5}", over_max_warning_title, uPath_rest.ToString(), "KBytes", (double)uPath_rest / 1024, "MBytes", over_max_free), ToolTipIcon.Info);
if (msg.IsAlive)
{
top.Close();
}
break;
case true:
notifyIcon1.Icon = new Icon(Properties.Resources._3, 16, 16);
notifyIcon1.ShowBalloonTip(1000, "", String.Format("{0}\n{1} {2} {3:0.00} {4} {5}", over_max_error_title, uPath_rest.ToString(), "KBytes", (double)uPath_rest / 1024, "MBytes", over_max_exceeded), ToolTipIcon.Info);
if (!msg.IsAlive)
{
msg = new Thread(() => MsgBox(over_max_error_text.Replace("\\n", System.Environment.NewLine), over_max_error_title));
msg.Start();
}
break;
}
domouse = false;
}
else
{
if (domouse)
{
//Program.Log("mouseover", EventLogEntryType.Information);
switch (over_max)
{
case null:
notifyIcon1.ShowBalloonTip(1000, "", String.Format("{0}\n{1} {2} {3:0.00} {4} {5}", over_max_userprofile, uPath_rest.ToString(), "KBytes", (double)uPath_rest / 1024, "MBytes", over_max_free), ToolTipIcon.Info);
break;
case false:
notifyIcon1.ShowBalloonTip(1000, "", String.Format("{0}\n{1} {2} {3:0.00} {4} {5}", over_max_warning_title, uPath_rest.ToString(), "KBytes", (double)uPath_rest / 1024, "MBytes", over_max_free), ToolTipIcon.Info);
break;
case true:
notifyIcon1.ShowBalloonTip(1000, "", String.Format("{0}\n{1} {2} {3:0.00} {4} {5}", over_max_error_title, uPath_rest.ToString(), "KBytes", (double)uPath_rest / 1024, "MBytes", over_max_exceeded), ToolTipIcon.Info);
break;
}
domouse = false;
}
}
}
}
catch { }
finally
{
Calculon_Lock.ExitWriteLock();
}
}
}
private void MsgBox(string body, string title)
{
top = new System.Windows.Forms.Form();
top.TopMost = true;
top.ShowInTaskbar = false;
MessageBox(top.Handle, body, title, MessageBoxOptions.OkOnly | MessageBoxOptions.Topmost | MessageBoxOptions.DefButton1 | MessageBoxOptions.IconError | MessageBoxOptions.SetForeground);
}
protected override void OnLoad(EventArgs e)
{
Visible = false; // Hide form window.
ShowInTaskbar = false; // Remove from taskbar.
base.OnLoad(e);
}
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = true;
ShutdownBlockReasonCreate(this.Handle, String.Format("{0}\n{1}", over_max_userprofile, over_max_calculate_text));
bool? l_over_max = true;
try
{
if (mouseoverlock.TryEnterWriteLock(-1))
{
//Program.Log("Onclosing set mouse true", EventLogEntryType.Information);
mouseover = true;
}
}
catch { }
finally
{
mouseoverlock.ExitWriteLock();
}
Thread.Sleep(Convert.ToInt32(sleep_timer + (sleep_timer / 4)));
try
{
if (Calculon_Lock.TryEnterReadLock(-1))
{
l_over_max = over_max;
}
}
catch { }
finally
{
Calculon_Lock.ExitReadLock();
}
//Program.Log("Calculon finished", EventLogEntryType.Information);
if (l_over_max == true)
{
ShutdownBlockReasonCreate(this.Handle, over_max_error_text.Replace("\\n", System.Environment.NewLine).Remove(128));
top.Close();
msg = new Thread(() => MsgBox(over_max_error_text.Replace("\\n", System.Environment.NewLine), over_max_error_title));
msg.Start();
}
else
{
top.Close();
ShutdownBlockReasonDestroy(this.Handle);
e.Cancel = false;
}
}
protected override void CreateHandle()
{
base.CreateHandle();
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include <stdio.h>
#include "pGinaTransactions.h"
#include "ObjectCleanupPool.h"
#include "PipeClient.h"
#include "Message.h"
#include "pGinaMessages.h"
#include "Registry.h"
#include "Helpers.h"
namespace pGina
{
namespace Transactions
{
/* static */
void Log::Debug(const wchar_t *format, ...)
{
wchar_t buffer[2048];
memset(buffer, 0, sizeof(buffer));
va_list args;
va_start(args, format);
_vsnwprintf_s( buffer, sizeof(buffer) / sizeof(WORD), _TRUNCATE, format, args);
LogInternal(L"Debug", buffer);
}
/* static */
void Log::Info(const wchar_t *format, ...)
{
wchar_t buffer[2048];
memset(buffer, 0, sizeof(buffer));
va_list args;
va_start(args, format);
_vsnwprintf_s( buffer, sizeof(buffer) / sizeof(WORD), _TRUNCATE, format, args);
LogInternal(L"Info", buffer);
}
/* static */
void Log::Warn(const wchar_t *format, ...)
{
wchar_t buffer[2048];
memset(buffer, 0, sizeof(buffer));
va_list args;
va_start(args, format);
_vsnwprintf_s( buffer, sizeof(buffer) / sizeof(WORD), _TRUNCATE, format, args);
LogInternal(L"Warn", buffer);
}
/* static */
void Log::Error(const wchar_t *format, ...)
{
wchar_t buffer[2048];
memset(buffer, 0, sizeof(buffer));
va_list args;
va_start(args, format);
_vsnwprintf_s( buffer, sizeof(buffer) / sizeof(WORD), _TRUNCATE, format, args);
LogInternal(L"Error", buffer);
}
/* static */
void Log::LogInternal(const wchar_t *level, const wchar_t *message)
{
// Call outputdebugstring, after appending a \n and truncating
wchar_t ods_buffer[4096 - 6]; // Max output to OutputDebugString
_snwprintf_s(ods_buffer, sizeof(ods_buffer) / sizeof(WORD), _TRUNCATE, L"%s\n", message);
OutputDebugString(ods_buffer);
// Write a log message to the service
std::wstring pipeName = pGina::Registry::GetString(L"ServicePipeName", L"Unknown");
std::wstring pipePath = L"\\\\.\\pipe\\";
pipePath += pipeName;
pGina::NamedPipes::PipeClient pipeClient(pipePath, 100);
if(pipeClient.Connect())
{
// Start a cleanup pool for messages we collect along the way
pGina::Memory::ObjectCleanupPool cleanup;
// Always send hello first, expect hello in return
pGina::Protocol::HelloMessage hello;
pGina::Protocol::MessageBase * reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, hello);
cleanup.Add(reply);
if(reply && reply->Type() != pGina::Protocol::Hello)
return;
// Then send a log message, expect ack in return
pGina::Protocol::LogMessage log(L"NativeLib", level, message);
reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, log);
cleanup.Add(reply);
if(reply && reply->Type() != pGina::Protocol::Ack)
return;
// Send disconnect, expect ack, then close
pGina::Protocol::DisconnectMessage disconnect;
reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, disconnect);
cleanup.Add(reply);
// We close regardless, no need to check reply type..
pipeClient.Close();
}
}
/* static */
bool Service::Ping()
{
std::wstring pipeName = pGina::Registry::GetString(L"ServicePipeName", L"Unknown");
std::wstring pipePath = L"\\\\.\\pipe\\";
pipePath += pipeName;
pGina::NamedPipes::PipeClient pipeClient(pipePath, 100);
if(pipeClient.Connect())
{
// Start a cleanup pool for messages we collect along the way
pGina::Memory::ObjectCleanupPool cleanup;
// Always send hello first, expect hello in return
pGina::Protocol::HelloMessage hello;
pGina::Protocol::MessageBase * reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, hello);
cleanup.Add(reply);
if(reply && reply->Type() != pGina::Protocol::Hello)
return false;
// Send disconnect, expect ack, then close
pGina::Protocol::DisconnectMessage disconnect;
reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, disconnect);
cleanup.Add(reply);
// We close regardless, no need to check reply type..
pipeClient.Close();
return true;
}
return false;
}
/* static */
User::LoginResult User::ProcessLoginForUser(const wchar_t *username, const wchar_t *domain, const wchar_t *password, pGina::Protocol::LoginRequestMessage::LoginReason reason)
{
// Write a log message to the service
std::wstring pipeName = pGina::Registry::GetString(L"ServicePipeName", L"Unknown");
std::wstring pipePath = L"\\\\.\\pipe\\";
pipePath += pipeName;
// Start a cleanup pool for messages we collect along the way
pGina::Memory::ObjectCleanupPool cleanup;
pGina::NamedPipes::PipeClient pipeClient(pipePath, 100);
if(pipeClient.Connect())
{
// Always send hello first, expect hello in return
pGina::Protocol::HelloMessage hello;
pGina::Protocol::MessageBase * reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, hello);
cleanup.Add(reply);
if(reply && reply->Type() != pGina::Protocol::Hello)
return LoginResult();
// Then send a loging request message, expect a loginresult message
pGina::Protocol::LoginRequestMessage request(username, domain, password, reason);
reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, request);
cleanup.Add(reply);
if(reply && reply->Type() != pGina::Protocol::LoginResponse)
return LoginResult();
// Did they login?
pGina::Protocol::LoginResponseMessage * responseMsg = static_cast<pGina::Protocol::LoginResponseMessage *>(reply);
// Send disconnect, expect ack, then close
pGina::Protocol::DisconnectMessage disconnect;
reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, disconnect);
cleanup.Add(reply);
// We close regardless, no need to check reply type..
pipeClient.Close();
// If a domain was not specified, we must set it to local machine else no u/p will work regardless
if(responseMsg->Domain().length() == 0)
{
Log::Warn(L"Plugins did not set a domain name, assuming local machine!");
responseMsg->Domain(pGina::Helpers::GetMachineName());
}
// If we failed, and the 'LocalAdminFallback' option is on, try this with LogonUser iff the username is an
// admin locally. In fact, it is so rare that this should be turned off, that we don't expose it in the UI
// even.. woah!
if(!responseMsg->Result())
{
if(pGina::Registry::GetBool(L"LocalAdminFallback", false))
{
Log::Warn(L"Unable to authenticate %s, checking to see if local admin fallback applies", request.Username().c_str());
if(pGina::Helpers::IsUserLocalAdmin(request.Username()))
{
Log::Info(L"%s is a local admin, falling back to system auth", request.Username().c_str());
if(LocalLoginForUser(request.Username().c_str(), request.Password().c_str()))
{
Log::Info(L"Local login succeeded");
return LoginResult(true, request.Username(), request.Password(), pGina::Helpers::GetMachineName(), L"");
}
else
{
Log::Error(L"Local login failed");
}
}
}
}
return LoginResult(responseMsg->Result(), responseMsg->Username(), responseMsg->Password(), responseMsg->Domain(), responseMsg->Message());
}
else
{
Log::Warn(L"Unable to connect to pGina service pipe - LastError: 0x%08x, falling back on LogonUser()", GetLastError());
if(LocalLoginForUser(username, password))
return LoginResult(true, username ? username : L"", password ? <PASSWORD> : L"", pGina::Helpers::GetMachineName(), L"");
}
return LoginResult();
}
/* static */
bool User::LocalLoginForUser(const wchar_t *username, const wchar_t *password)
{
std::wstring domainName = pGina::Helpers::GetMachineName();
Log::Debug(L"Using LogonUser(%s, %s, *****)", username, domainName.c_str());
HANDLE token = NULL;
if(LogonUser(username, domainName.c_str(), password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &token) == TRUE)
{
CloseHandle(token);
return true;
}
return false;
}
/* static */
std::wstring TileUi::GetDynamicLabel(const wchar_t *labelName)
{
// Write a log message to the service
std::wstring pipeName = pGina::Registry::GetString(L"ServicePipeName", L"Unknown");
std::wstring pipePath = L"\\\\.\\pipe\\";
pipePath += pipeName;
pGina::NamedPipes::PipeClient pipeClient(pipePath, 100);
std::wstring labelText = L"";
if( pipeClient.Connect() )
{
// Start a cleanup pool for messages we collect along the way
pGina::Memory::ObjectCleanupPool cleanup;
// Always send hello first, expect hello in return
pGina::Protocol::HelloMessage hello;
pGina::Protocol::MessageBase * reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, hello);
cleanup.Add(reply);
if(reply && reply->Type() != pGina::Protocol::Hello)
return labelText;
// Then send a label request message, expect a labelresponse message
pGina::Protocol::DynamicLabelRequestMessage request(labelName);
reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, request);
cleanup.Add(reply);
if(reply && reply->Type() != pGina::Protocol::DynLabelResponse)
return labelText;
// Get the reply
pGina::Protocol::DynamicLabelResponseMessage * responseMsg =
static_cast<pGina::Protocol::DynamicLabelResponseMessage *>(reply);
labelText = responseMsg->Text();
// Send disconnect, expect ack, then close
pGina::Protocol::DisconnectMessage disconnect;
reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, disconnect);
cleanup.Add(reply);
// We close regardless, no need to check reply type..
pipeClient.Close();
}
else
{
Log::Warn(L"Unable to connect to pGina service pipe - LastError: 0x%08x, giving up.", GetLastError());
}
return labelText;
}
/* static */
LoginInfo::UserInformation LoginInfo::GetUserInformation(int session_id)
{
// Write a log message to the service
std::wstring pipeName = pGina::Registry::GetString(L"ServicePipeName", L"Unknown");
std::wstring pipePath = L"\\\\.\\pipe\\";
pipePath += pipeName;
pGina::NamedPipes::PipeClient pipeClient(pipePath, 100);
if( pipeClient.Connect() )
{
// Start a cleanup pool for messages we collect along the way
pGina::Memory::ObjectCleanupPool cleanup;
// Always send hello first, expect hello in return
pGina::Protocol::HelloMessage hello;
pGina::Protocol::MessageBase * reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, hello);
cleanup.Add(reply);
if(reply && reply->Type() != pGina::Protocol::Hello)
return UserInformation();
// Then send a request message, expect a response message
pGina::Protocol::UserInformationRequestMessage request(session_id);
reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, request);
cleanup.Add(reply);
if(reply && reply->Type() != pGina::Protocol::UserInfoResponse)
return UserInformation();
// Get the reply
pGina::Protocol::UserInformationResponseMessage * responseMsg =
static_cast<pGina::Protocol::UserInformationResponseMessage *>(reply);
// Send disconnect, expect ack, then close
pGina::Protocol::DisconnectMessage disconnect;
reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, disconnect);
cleanup.Add(reply);
// We close regardless, no need to check reply type..
pipeClient.Close();
return UserInformation(responseMsg->OriginalUsername(), responseMsg->Username(), responseMsg->Domain());
}
else
{
Log::Warn(L"Unable to connect to pGina service pipe - LastError: 0x%08x, giving up.", GetLastError());
}
return UserInformation();
}
/* static */
void LoginInfo::Move(const wchar_t *username, const wchar_t *domain, const wchar_t *password, int old_session, int new_session)
{
std::wstring pipeName = pGina::Registry::GetString(L"ServicePipeName", L"Unknown");
std::wstring pipePath = L"\\\\.\\pipe\\";
pipePath += pipeName;
pGina::NamedPipes::PipeClient pipeClient(pipePath, 100);
std::wstring labelText = L"";
if( pipeClient.Connect() )
{
// Start a cleanup pool for messages we collect along the way
pGina::Memory::ObjectCleanupPool cleanup;
// Always send hello first, expect hello in return
pGina::Protocol::HelloMessage hello;
pGina::Protocol::MessageBase * reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, hello);
cleanup.Add(reply);
if(reply && reply->Type() != pGina::Protocol::Hello)
return;
pGina::Protocol::LoginInfoChangeMessage request(username, domain, password);
request.FromSession(old_session);
request.ToSession(new_session);
reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, request);
cleanup.Add(reply);
if(reply && reply->Type() != pGina::Protocol::Ack)
return;
// Send disconnect, expect ack, then close
pGina::Protocol::DisconnectMessage disconnect;
reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, disconnect);
cleanup.Add(reply);
// We close regardless, no need to check reply type..
pipeClient.Close();
}
else
{
Log::Warn(L"Unable to connect to pGina service pipe - LastError: 0x%08x, giving up.", GetLastError());
}
}
ServiceStateThread::ServiceStateThread() :
m_serviceRunning(false),
m_callback(NULL)
{
}
void ServiceStateThread::SetCallback(NOTIFY_STATE_CHANGE_CALLBACK callback)
{
m_callback = callback;
}
DWORD ServiceStateThread::ThreadMain()
{
while(Running())
{
bool runningNow = Service::Ping();
bool runningWas = IsServiceRunning();
SetServiceRunning(runningNow);
if(runningNow != runningWas && m_callback != NULL)
{
m_callback(runningNow);
}
SetServiceRunning(runningNow);
Sleep(pGina::Registry::GetDword(L"PingSleepTime", 5000));
}
return 0;
}
void ServiceStateThread::SetServiceRunning(bool b)
{
pGina::Threading::ScopedLock lock(m_mutex);
m_serviceRunning = b;
}
bool ServiceStateThread::IsServiceRunning()
{
pGina::Threading::ScopedLock lock(m_mutex);
return m_serviceRunning;
}
/* static */
User::LoginResult User::ProcessChangePasswordForUser(const wchar_t *username, const wchar_t *domain,
const wchar_t *oldPassword, const wchar_t *newPassword)
{
// Write a log message to the service
std::wstring pipeName = pGina::Registry::GetString(L"ServicePipeName", L"Unknown");
std::wstring pipePath = L"\\\\.\\pipe\\";
pipePath += pipeName;
// Start a cleanup pool for messages we collect along the way
pGina::Memory::ObjectCleanupPool cleanup;
pGina::NamedPipes::PipeClient pipeClient(pipePath, 100);
if(pipeClient.Connect())
{
// Always send hello first, expect hello in return
pGina::Protocol::HelloMessage hello;
pGina::Protocol::MessageBase * reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, hello);
cleanup.Add(reply);
if(reply && reply->Type() != pGina::Protocol::Hello)
return LoginResult();
// Then send a change password request message, expect a loginresult message
pGina::Protocol::ChangePasswordRequestMessage request(username, domain, oldPassword, newPassword);
reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, request);
cleanup.Add(reply);
if(reply && reply->Type() != pGina::Protocol::ChangePasswordResponse)
return LoginResult();
pGina::Protocol::ChangePasswordResponseMessage * responseMsg =
static_cast<pGina::Protocol::ChangePasswordResponseMessage *>(reply);
// Send disconnect, expect ack, then close
pGina::Protocol::DisconnectMessage disconnect;
reply = pGina::Protocol::SendRecvPipeMessage(pipeClient, disconnect);
cleanup.Add(reply);
// We close regardless, no need to check reply type..
pipeClient.Close();
// If a domain was not specified, we must set it to local machine else no u/p will work regardless
if(responseMsg->Domain().length() == 0)
{
Log::Warn(L"Plugins did not set a domain name, assuming local machine!");
responseMsg->Domain(pGina::Helpers::GetMachineName());
}
// Password is ignored by credential provider.
return LoginResult(responseMsg->Result(),
responseMsg->Username(),
responseMsg->OldPassword(),
responseMsg->Domain(),
responseMsg->Message());
}
else
{
Log::Warn(L"Unable to connect to pGina service pipe - LastError: 0x%08x, giving up.", GetLastError());
}
return LoginResult();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace pGina.Plugin.MySQLAuth
{
public partial class TextBoxInfoDialog : Form
{
public TextBoxInfoDialog()
{
InitializeComponent();
}
public void AppendText(string text)
{
this.textBox.AppendText(text);
}
public void AppendLine(string line)
{
this.textBox.AppendText(line + Environment.NewLine);
}
public void ClearText()
{
this.textBox.Text = "";
}
private void closeButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using pGina.Shared.Settings;
namespace pGina.Plugin.Email
{
class Settings
{
public static dynamic Store
{
get { return m_settings; }
}
private static dynamic m_settings;
static Settings()
{
m_settings = new pGinaDynamicSettings(EmailAuthPlugin.SimpleUuid);
// Set default values for settings (if not already set)
m_settings.SetDefault("Server", "");
m_settings.SetDefault("UseSsl", true);
m_settings.SetDefault("Protocol", "POP3");
m_settings.SetDefault("Port", "");
m_settings.SetDefault("AppendDomain", false);
m_settings.SetDefault("Domain", "");
m_settings.SetDefault("NetworkTimeout", 10000); // timeout in ms
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using pGina.Shared.Settings;
namespace pGina.Plugin.scripting
{
public class Settings
{
private static dynamic m_settings = new pGinaDynamicSettings(PluginImpl.PluginUuid);
static Settings()
{
// Authentication step settings:
m_settings.SetDefault("authe_sys", new string[] { @"True cmd.exe /c echo %USERNAME% %u %p %i %Ae %Ao %Gw authe>>%SystemDrive%\sys.txt" });
// Authorization step settings
m_settings.SetDefault("autho_sys", new string[] { @"False cmd.exe /c echo %USERNAME% %u %p %i %Ae %Ao %Gw autho>>%SystemDrive%\sys.txt" });
// Gateway step settings
m_settings.SetDefault("gateway_sys", new string[] { @"True cmd.exe /c echo %USERNAME% %u %p %i %Ae %Ao %Gw gateway>>%SystemDrive%\sys.txt" });
// Notification
m_settings.SetDefault("notification_sys", new string[] { @"True True False cmd.exe /c echo %USERNAME% %u %p %s %e %i %Ae %Ao %Gw logon %p >>%PUBLIC%\sys.txt", @"False True False cmd.exe /c echo %USERNAME% %u %p %s %e %i %Ae %Ao %Gw logon>>%PUBLIC%\sys.txt", @"True False True cmd.exe /c echo %USERNAME% %u %p %s %e %i %Ae %Ao %Gw logoff %p>>%PUBLIC%\sys.txt", @"False False True cmd.exe /c echo %USERNAME% %u %p %s %e %i %Ae %Ao %Gw logoff>>%PUBLIC%\sys.txt" });
m_settings.SetDefault("notification_usr", new string[] { @"True False True cmd.exe /c echo %USERNAME% %u %p %s %e %i %Ae %Ao %Gw logoff %p >>%PUBLIC%\usr.txt", @"False False True cmd.exe /c echo %USERNAME% %u %p %s %e %i %Ae %Ao %Gw logoff>>%PUBLIC%\usr.txt", @"True True False cmd.exe /c echo %USERNAME% %u %p %s %e %i %Ae %Ao %Gw logon %p >>%PUBLIC%\usr.txt", @"False True False cmd.exe /c echo %USERNAME% %u %p %s %e %i %Ae %Ao %Gw logon>>%PUBLIC%\usr.txt" });
// change password
m_settings.SetDefault("changepwd_sys", new string[] { });
m_settings.SetDefault("changepwd_usr", new string[] { });
}
public static dynamic Store
{
get { return m_settings; }
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using pGina.Plugin.Ldap;
using System.DirectoryServices.Protocols;
using NUnit.Framework;
using pGina.Shared.Types;
namespace pGina.Plugin.Ldap.Test
{
[TestFixture]
public class LdapTests
{
static dynamic m_settings;
static readonly string[] host = { "192.168.56.101" };
static readonly int port = 389;
static readonly bool useSsl = false;
static readonly bool validateCert = false;
static readonly string searchDN = ""; // anonymous bind
static readonly string searchPW = "";
static readonly Guid BogusSessionId = new Guid("9B599C0B-08C4-43F0-A2DB-42C73A3C59F5");
private LdapPlugin m_plugin;
private SessionProperties m_props;
[TestFixtureSetUp]
public void InitFixture()
{
pGina.Shared.Logging.Logging.Init();
m_settings = new pGina.Shared.Settings.pGinaDynamicSettings(Ldap.LdapPlugin.LdapUuid);
m_plugin = new LdapPlugin();
m_plugin.Starting();
}
[TestFixtureTearDown]
public void TearDownFixture()
{
m_plugin.Stopping();
}
[SetUp]
public void InitTest()
{
// Default test settings, reset for each test
m_settings.LdapHost = host;
m_settings.LdapPort = port;
m_settings.LdapTimeout = 10;
m_settings.UseSsl = useSsl;
m_settings.RequireCert = validateCert;
m_settings.SearchDN = searchDN;
m_settings.SetEncryptedSetting("SearchPW", searchPW);
m_settings.GroupDnPattern = "cn=%g,ou=Group,dc=example,dc=com";
m_settings.GroupMemberAttrib = "memberUid";
// Authentication
m_settings.AllowEmptyPasswords = false;
m_settings.DnPattern = "uid=%u,ou=People,dc=example,dc=com";
m_settings.DoSearch = false;
m_settings.SearchFilter = "";
m_settings.SearchContexts = new string[] { };
// Authorization
m_settings.GroupAuthzRules = new string[] { (new GroupAuthzRule(true)).ToRegString() };
m_settings.AuthzRequireAuth = false;
m_settings.AuthzAllowOnError = true;
// Gateway
m_settings.GroupGatewayRules = new string[] { };
// Set up session props
m_props = new SessionProperties(BogusSessionId);
UserInformation userInfo = new UserInformation();
m_props.AddTrackedSingle<UserInformation>(userInfo);
userInfo.Username = "kirkj";
userInfo.Password = "<PASSWORD>";
PluginActivityInformation actInfo = new PluginActivityInformation();
m_props.AddTrackedSingle<PluginActivityInformation>(actInfo);
}
[TearDown]
public void TearDown()
{
}
// A simple authentication, no frills.
[Test] public void AuthSimple()
{
m_plugin.BeginChain(m_props);
BooleanResult result = m_plugin.AuthenticateUser(m_props);
m_plugin.EndChain(m_props);
Assert.That(result.Success, result.Message);
}
// Disallow empty passwords (default)
[Test]
public void AuthEmpty()
{
// Modify settings
UserInformation userInfo = m_props.GetTrackedSingle<UserInformation>();
userInfo.Password = "";
m_plugin.BeginChain(m_props);
BooleanResult result = m_plugin.AuthenticateUser(m_props);
m_plugin.EndChain(m_props);
Assert.That(!result.Success, result.Message);
Assert.That(result.Message, Is.EqualTo("Authentication failed due to empty password."));
}
[Test]
public void AuthSimpleFail()
{
// Modify settings
UserInformation userInfo = m_props.GetTrackedSingle<UserInformation>();
userInfo.Password = "<PASSWORD>";
m_plugin.BeginChain(m_props);
BooleanResult result = m_plugin.AuthenticateUser(m_props);
m_plugin.EndChain(m_props);
Assert.That(!result.Success, result.Message);
}
// An authentication where we need to search for the DN
[Test]
public void AuthSearch()
{
m_settings.DoSearch = true;
m_settings.SearchFilter = "(uid=%u)";
m_settings.SearchContexts = new string[] { "ou=People,dc=example,dc=com" };
m_plugin.BeginChain(m_props);
BooleanResult result = m_plugin.AuthenticateUser(m_props);
m_plugin.EndChain(m_props);
Assert.That(result.Success, result.Message);
}
// A failed authentication where we need to search for the DN
[Test]
public void AuthSearchFail()
{
// Modify settings
UserInformation userInfo = m_props.GetTrackedSingle<UserInformation>();
userInfo.Password = "<PASSWORD>";
m_settings.DoSearch = true;
m_settings.SearchFilter = "(uid=%u)";
m_settings.SearchContexts = new string[] { "ou=People,dc=example,dc=com" };
m_plugin.BeginChain(m_props);
BooleanResult result = m_plugin.AuthenticateUser(m_props);
m_plugin.EndChain(m_props);
Assert.That(!result.Success, result.Message);
}
// Unable to find the DN
[Test]
public void AuthSearchFailDnSearch()
{
m_settings.DoSearch = true;
m_settings.SearchFilter = "(uid=%u)";
m_settings.SearchContexts = new string[] { "ou=Group,dc=example,dc=com" };
m_plugin.BeginChain(m_props);
BooleanResult result = m_plugin.AuthenticateUser(m_props);
m_plugin.EndChain(m_props);
Assert.That(!result.Success, result.Message);
Assert.That(result.Message, Is.EqualTo("Unable to determine the user's LDAP DN for authentication.") );
}
// Deny when LDAP auth fails
[Test]
public void AuthzDenyAuth()
{
m_settings.AuthzRequireAuth = true;
m_plugin.BeginChain(m_props);
PluginActivityInformation actInfo = m_props.GetTrackedSingle<PluginActivityInformation>();
actInfo.AddAuthenticateResult(LdapPlugin.LdapUuid, new BooleanResult { Success = false });
BooleanResult result = m_plugin.AuthorizeUser(m_props);
m_plugin.EndChain(m_props);
Assert.That(!result.Success, result.Message);
Assert.That(result.Message, Is.EqualTo("Deny because LDAP authentication failed."));
}
// Deny when LDAP auth doesn't execute
[Test]
public void AuthzDenyAuthNoExecute()
{
m_settings.AuthzRequireAuth = true;
m_plugin.BeginChain(m_props);
BooleanResult result = m_plugin.AuthorizeUser(m_props);
m_plugin.EndChain(m_props);
Assert.That(!result.Success, result.Message);
Assert.That(result.Message, Is.EqualTo("Deny because LDAP auth did not execute, and configured to require LDAP auth."));
}
[Test]
public void AuthzAllowGroup()
{
// Allow by default rule (not a member of "good")
m_settings.GroupAuthzRules = new string[] {
new GroupAuthzRule("good", GroupRule.Condition.MEMBER_OF, true, "(&(objectclass=*))", SearchScope.Base).ToRegString(),
(new GroupAuthzRule(true)).ToRegString()
};
m_plugin.BeginChain(m_props);
BooleanResult result = m_plugin.AuthorizeUser(m_props);
m_plugin.EndChain(m_props);
Assert.That(result.Success, result.Message);
}
[Test]
public void AuthzAllowGroup01()
{
// Allow because I'm not a member of group "good"
m_settings.GroupAuthzRules = new string[] {
new GroupAuthzRule("good", GroupRule.Condition.NOT_MEMBER_OF, true, "(&(objectclass=*))", SearchScope.Base).ToRegString(),
(new GroupAuthzRule(true)).ToRegString()
};
m_plugin.BeginChain(m_props);
BooleanResult result = m_plugin.AuthorizeUser(m_props);
m_plugin.EndChain(m_props);
Assert.That(result.Success, result.Message);
}
[Test]
public void AuthzDenyGroup()
{
// Deny because I'm a member of group "bad"
m_settings.GroupAuthzRules = new string[] {
new GroupAuthzRule("bad", GroupRule.Condition.MEMBER_OF, false, "(&(objectclass=*))", SearchScope.Base).ToRegString(),
(new GroupAuthzRule(true)).ToRegString()
};
m_plugin.BeginChain(m_props);
BooleanResult result = m_plugin.AuthorizeUser(m_props);
m_plugin.EndChain(m_props);
Assert.That(!result.Success, result.Message);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace pGina.Configuration
{
public partial class LogViewWindow : Form
{
internal TextBox LogTextBox { get { return logTextArea; } }
public LogViewWindow()
{
InitializeComponent();
}
private void saveBtn_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text File (.txt)|*.txt|All Files (*.*)|*.*";
sfd.CheckPathExists = true;
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter file = new StreamWriter(sfd.FileName))
{
file.Write(logTextArea.Text);
}
MessageBox.Show(string.Format("File saved successfully: {0}", sfd.FileName), "Log Export", MessageBoxButtons.OK);
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include <assert.h>
#include <Macros.h>
#include "Provider.h"
#include "Dll.h"
#pragma warning(push)
#pragma warning(disable : 4995)
#include <shlwapi.h>
#pragma warning(pop)
#include "TileUiLogon.h"
#include "TileUiUnlock.h"
#include "TileUiChangePassword.h"
#include "ProviderGuid.h"
#include "SerializationHelpers.h"
#include "ServiceStateHelper.h"
#include <wincred.h>
namespace pGina
{
namespace CredProv
{
/*static */ bool Provider::m_redraw;
IFACEMETHODIMP Provider::QueryInterface(__in REFIID riid, __deref_out void **ppv)
{
// And more crazy ass v-table madness, yay COM again!
static const QITAB qit[] =
{
QITABENT(Provider, ICredentialProvider),
{0},
};
return QISearch(this, qit, riid, ppv);
}
IFACEMETHODIMP_(ULONG) Provider::AddRef()
{
// Win 10 workaround to redraw the CP after an error
if (m_redraw)
{
m_redraw = false;
m_logonUiCallbackEvents->CredentialsChanged(m_logonUiCallbackContext);
}
return InterlockedIncrement(&m_referenceCount);
}
IFACEMETHODIMP_(ULONG) Provider::Release()
{
LONG count = InterlockedDecrement(&m_referenceCount);
if (!count)
delete this;
return count;
}
Provider::Provider() :
m_referenceCount(1),
m_usageScenario(CPUS_INVALID),
m_logonUiCallbackEvents(NULL),
m_logonUiCallbackContext(0),
m_credential(NULL),
m_usageFlags(0),
m_setSerialization(NULL)
{
AddDllReference();
pDEBUG(L"Starting service state helper thread");
pGina::Service::StateHelper::AddTarget(this);
pGina::Service::StateHelper::Start();
}
Provider::~Provider()
{
pDEBUG(L"Stopping service state helper thread (if necessary)");
if (pGina::Service::StateHelper::GetLoginChangePassword())
pGina::Transactions::LoginInfo::Move(pGina::Service::StateHelper::GetUsername().c_str(), L"", L"", pGina::Helpers::GetCurrentSessionId(), -1);
pGina::Service::StateHelper::RemoveTarget(this);
pGina::Service::StateHelper::Stop();
UnAdvise();
ReleaseDllReference();
if(m_credential)
{
m_credential->Release();
m_credential = NULL;
}
if(m_setSerialization)
{
LocalFree(m_setSerialization);
m_setSerialization = NULL;
}
}
// Poorly named, should be QueryUsageScenarioSupport - LogonUI calls this to find out whether the provided
// scenario is one which our provider supports. It also doubles as our shot to do anything before being
// called for the scenario in question.
IFACEMETHODIMP Provider::SetUsageScenario(__in CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus, __in DWORD dwFlags)
{
pDEBUG(L"Provider::SetUsageScenario(%d, 0x%08x)", cpus, dwFlags);
// Returning E_NOTIMPL indicates no support for the requested scenario, otherwise S_OK suffices.
switch(cpus)
{
case CPUS_LOGON:
case CPUS_UNLOCK_WORKSTATION:
case CPUS_CREDUI:
m_usageScenario = cpus;
m_usageFlags = dwFlags;
return S_OK;
case CPUS_CHANGE_PASSWORD:
m_usageScenario = cpus;
m_usageFlags = dwFlags;
return S_OK;
case CPUS_PLAP:
case CPUS_INVALID:
return E_NOTIMPL;
default:
return E_INVALIDARG; // Say wha?
}
}
IFACEMETHODIMP Provider::SetSerialization(__in const CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION* pcpcs)
{
pDEBUG(L"SetSerialization(%p)", pcpcs);
HRESULT result = E_NOTIMPL;
if ((CLSID_CpGinaProvider != pcpcs->clsidCredentialProvider) && (m_usageScenario == CPUS_CREDUI))
{
return E_INVALIDARG;
}
// Must match our auth package (negotiate)
ULONG authPackage = 0;
result = Microsoft::Sample::RetrieveNegotiateAuthPackage(&authPackage);
if(!SUCCEEDED(result))
{
pDEBUG(L"Failed to retrieve negotiate auth package");
return result;
}
// Slightly modified behavior depending on flags provided to SetUsageScenario
if(m_usageScenario == CPUS_CREDUI)
{
// Must support the auth package specified in CREDUIWIN_IN_CRED_ONLY and CREDUIWIN_AUTHPACKAGE_ONLY
if( ((m_usageFlags & CREDUIWIN_IN_CRED_ONLY) || (m_usageFlags & CREDUIWIN_AUTHPACKAGE_ONLY))
&& authPackage != pcpcs->ulAuthenticationPackage)
{
pDEBUG(L"Invalid auth package (%x)", pcpcs->ulAuthenticationPackage);
return E_INVALIDARG;
}
// CREDUIWIN_AUTHPACKAGE_ONLY should NOT return S_OK unless we can serialize correctly,
// so we default to S_FALSE here and change to S_OK on success.
if(m_usageFlags & CREDUIWIN_AUTHPACKAGE_ONLY)
{
pDEBUG(L"CPUS_CREDUI but flags doesn't indicate CREDUIWIN_AUTHPACKAGE_ONLY");
result = S_FALSE;
}
}
// As long as the package matches, and there is something to read from
pDEBUG(L"authPackage: 0x%08x serializedPackage: 0x%08x serializedBytes: 0x%08x @ %p", authPackage, pcpcs->ulAuthenticationPackage, pcpcs->cbSerialization, pcpcs->rgbSerialization);
if(authPackage == pcpcs->ulAuthenticationPackage && pcpcs->cbSerialization > 0 && pcpcs->rgbSerialization)
{
KERB_INTERACTIVE_UNLOCK_LOGON* pkil = (KERB_INTERACTIVE_UNLOCK_LOGON*) pcpcs->rgbSerialization;
if(pkil->Logon.MessageType == KerbInteractiveLogon)
{
// Must have a username
if(pkil->Logon.UserName.Length && pkil->Logon.UserName.Buffer)
{
BYTE * nativeSerialization = NULL;
DWORD nativeSerializationSize = 0;
// Do we need to repack in native format? (32 bit client talking to 64 bit host or vice versa)
if(m_usageScenario == CPUS_CREDUI && (CREDUIWIN_PACK_32_WOW & m_usageFlags))
{
if(!SUCCEEDED(Microsoft::Sample::KerbInteractiveUnlockLogonRepackNative(pcpcs->rgbSerialization, pcpcs->cbSerialization,
&nativeSerialization, &nativeSerializationSize)))
{
return result;
}
}
else
{
nativeSerialization = (BYTE*) LocalAlloc(LMEM_ZEROINIT, pcpcs->cbSerialization);
nativeSerializationSize = pcpcs->cbSerialization;
if(!nativeSerialization)
return E_OUTOFMEMORY;
CopyMemory(nativeSerialization, pcpcs->rgbSerialization, pcpcs->cbSerialization);
}
Microsoft::Sample::KerbInteractiveUnlockLogonUnpackInPlace((KERB_INTERACTIVE_UNLOCK_LOGON *) nativeSerialization, nativeSerializationSize);
if(m_setSerialization) LocalFree(m_setSerialization);
m_setSerialization = (KERB_INTERACTIVE_UNLOCK_LOGON *) nativeSerialization;
pDEBUG(L"m_setSerialization = %p", m_setSerialization);
result = S_OK; // All is well!
}
}
}
return result;
}
IFACEMETHODIMP Provider::Advise(__in ICredentialProviderEvents* pcpe, __in UINT_PTR upAdviseContext)
{
// If we already have a callback handle, release our reference to it
UnAdvise();
// Store what we've been given
m_logonUiCallbackEvents = pcpe;
m_logonUiCallbackContext = upAdviseContext;
// Up ref count as we hold a pointer to this guy
if(m_logonUiCallbackEvents)
{
if (pGina::Service::StateHelper::GetLoginChangePassword())
{
if (m_usageScenario != CPUS_CHANGE_PASSWORD)
{
pGina::Transactions::LoginInfo::Move(pGina::Service::StateHelper::GetUsername().c_str(), L"", L"", pGina::Helpers::GetCurrentSessionId(), -1);
pGina::Service::StateHelper::PushUsername(L"", L"", false);
m_credential = new Credential();
m_credential->Initialize(m_usageScenario, s_logonFields, m_usageFlags, NULL, NULL);
}
else
{
if (m_credential)
{
m_credential->Initialize(m_usageScenario, s_changePasswordFields, m_usageFlags, pGina::Service::StateHelper::GetUsername().c_str(), pGina::Service::StateHelper::GetPassword().c_str());
}
}
m_logonUiCallbackEvents->CredentialsChanged(m_logonUiCallbackContext);
}
pDEBUG(L"Provider::Advise(%p, %p) - provider events callback reference added", pcpe, upAdviseContext);
m_logonUiCallbackEvents->AddRef();
}
return S_OK;
}
IFACEMETHODIMP Provider::UnAdvise()
{
if(m_logonUiCallbackEvents)
{
pDEBUG(L"Provider::UnAdvise() - provider events callback reference released");
m_logonUiCallbackEvents->Release();
m_logonUiCallbackEvents = NULL;
m_logonUiCallbackContext = 0;
}
return S_OK;
}
IFACEMETHODIMP Provider::GetFieldDescriptorCount(__out DWORD* pdwCount)
{
// # of fields depends on our usage scenario:
switch(m_usageScenario)
{
case CPUS_LOGON:
case CPUS_CREDUI:
*pdwCount = LUIFI_NUM_FIELDS;
return S_OK;
case CPUS_UNLOCK_WORKSTATION:
*pdwCount = LOIFI_NUM_FIELDS;
return S_OK;
case CPUS_CHANGE_PASSWORD:
*pdwCount = CPUIFI_NUM_FIELDS;
return S_OK;
default:
pERROR(L"Provider::GetFieldDescriptorCount: No UI known for the usage scenario: 0x%08x", m_usageScenario);
return S_FALSE;
}
// Should never reach this
assert(0);
return S_FALSE;
}
IFACEMETHODIMP Provider::GetFieldDescriptorAt(__in DWORD dwIndex, __deref_out CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR** ppcpfd)
{
switch(m_usageScenario)
{
case CPUS_LOGON:
case CPUS_CREDUI:
return GetFieldDescriptorForUi(s_logonFields, dwIndex, ppcpfd);
case CPUS_UNLOCK_WORKSTATION:
return GetFieldDescriptorForUi(s_unlockFields, dwIndex, ppcpfd);
case CPUS_CHANGE_PASSWORD:
return GetFieldDescriptorForUi(s_changePasswordFields, dwIndex, ppcpfd);
default:
return E_INVALIDARG;
}
// Should never reach this
assert(0);
return S_FALSE;
}
IFACEMETHODIMP Provider::GetCredentialCount(__out DWORD* pdwCount, __out_range(<,*pdwCount) DWORD* pdwDefault, __out BOOL* pbAutoLogonWithDefault)
{
// We currently always support only a single tile
*pdwCount = 1;
*pdwDefault = 0;
*pbAutoLogonWithDefault = FALSE;
// If we were given creds via SetSerialization, and they appear complete, then we can
// make that credential our default and attempt an autologon.
if(SerializedUserNameAvailable() && SerializedPasswordAvailable() && !pGina::Service::StateHelper::GetLoginChangePassword())
{
*pdwDefault = 0;
*pbAutoLogonWithDefault = TRUE;
}
return S_OK;
}
IFACEMETHODIMP Provider::GetCredentialAt(__in DWORD dwIndex, __deref_out ICredentialProviderCredential** ppcpc)
{
// Currently we have just the one, we lazy init it here when first requested
if(!m_credential)
{
m_credential = new Credential();
pGina::Memory::ObjectCleanupPool cleanup;
PWSTR serializedUser, serializedPass, serializedDomain;
GetSerializedCredentials(&serializedUser, &serializedPass, &serializedDomain);
if(serializedUser != NULL)
cleanup.Add(new pGina::Memory::LocalFreeCleanup(serializedUser));
if(serializedPass != NULL)
cleanup.Add(new pGina::Memory::LocalFreeCleanup(serializedPass));
if(serializedDomain != NULL)
cleanup.Add(new pGina::Memory::LocalFreeCleanup(serializedDomain));
switch(m_usageScenario)
{
case CPUS_LOGON:
case CPUS_CREDUI:
m_credential->Initialize(m_usageScenario, s_logonFields, m_usageFlags, serializedUser, serializedPass);
break;
case CPUS_UNLOCK_WORKSTATION:
m_credential->Initialize(m_usageScenario, s_unlockFields, m_usageFlags, serializedUser, serializedPass);
break;
case CPUS_CHANGE_PASSWORD:
m_credential->Initialize(m_usageScenario, s_changePasswordFields, m_usageFlags, serializedUser, serializedPass);
break;
default:
return E_INVALIDARG;
}
}
// Did we fail to create it? OOM
if(!m_credential) return E_OUTOFMEMORY;
// Better be index 0 (we only have 1 currently)
if(dwIndex != 0 || !ppcpc)
return E_INVALIDARG;
// Alright... QueryIface for ICredentialProviderCredential
if (m_usageScenario == CPUS_CREDUI)
{
return m_credential->QueryInterface(IID_ICredentialProviderCredential, reinterpret_cast<void **>(ppcpc));
}
return m_credential->QueryInterface(IID_IConnectableCredentialProviderCredential, reinterpret_cast<void **>(ppcpc));
}
IFACEMETHODIMP Provider::GetFieldDescriptorForUi(UI_FIELDS const& fields, DWORD index, CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR **ppcpfd)
{
// Must be in our count of fields, and we have to have somewhere to stuff the result
if(index >= fields.fieldCount && ppcpfd) return E_INVALIDARG;
// Should we fail, we want to return a NULL for result
*ppcpfd = NULL;
// Use CoTaskMemAlloc for the resulting value, then copy in our descriptor
DWORD structSize = sizeof(**ppcpfd);
CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *pcpfd = (CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *) CoTaskMemAlloc(structSize);
if(pcpfd == NULL) return E_OUTOFMEMORY;
// Use compilers struct copy, in case fields change down the road
*pcpfd = fields.fields[index].fieldDescriptor;
// But now we have to fixup the label, which is a ptr, we'll use SHStrDupW which does CoTask alloc
if(pcpfd->pszLabel)
{
if(!SUCCEEDED(SHStrDupW(fields.fields[index].fieldDescriptor.pszLabel, &pcpfd->pszLabel)))
{
// Dup failed, free up what we've got so far, then get out
CoTaskMemFree(pcpfd);
return E_OUTOFMEMORY;
}
}
// Got here? Then we win!
*ppcpfd = pcpfd;
return S_OK;
}
bool Provider::SerializedUserNameAvailable()
{
// Did we get any creds?
if(!m_setSerialization)
{
pDEBUG(L"SerializedUserNameAvailable: No serialized creds set");
return false;
}
// Did we get a username?
if(m_setSerialization->Logon.UserName.Length && m_setSerialization->Logon.UserName.Buffer)
return true;
pDEBUG(L"SerializedUserNameAvailable: couldn't work out username");
return false;
}
bool Provider::SerializedPasswordAvailable()
{
// Did we get any creds?
if(!m_setSerialization)
{
pDEBUG(L"SerializedPasswordAvailable: No serialized creds set");
return false;
}
// Did we get a password?
if(m_setSerialization->Logon.Password.Length && m_setSerialization->Logon.Password.Buffer)
return true;
pDEBUG(L"SerializedPasswordAvailable: couldn't work out password");
return false;
}
bool Provider::SerializedDomainNameAvailable()
{
// Did we get any creds?
if(!m_setSerialization)
{
pDEBUG(L"SerializedDomainNameAvailable: No serialized creds set");
return false;
}
// Did we get a domain name?
if(m_setSerialization->Logon.LogonDomainName.Length && m_setSerialization->Logon.LogonDomainName.Buffer)
return true;
pDEBUG(L"SerializedDomainNameAvailable: couldn't work out domain name");
return false;
}
void Provider::GetSerializedCredentials(PWSTR *username, PWSTR *password, PWSTR *domain)
{
if (username)
{
if (SerializedUserNameAvailable())
{
if (SerializedDomainNameAvailable())
{
*username = (PWSTR) LocalAlloc(LMEM_ZEROINIT, m_setSerialization->Logon.UserName.Length + sizeof(wchar_t) + m_setSerialization->Logon.LogonDomainName.Length + sizeof(wchar_t));
HLOCAL u = LocalAlloc(LMEM_ZEROINIT, m_setSerialization->Logon.UserName.Length + sizeof(wchar_t));
CopyMemory(u, m_setSerialization->Logon.UserName.Buffer, m_setSerialization->Logon.UserName.Length);
HLOCAL d = LocalAlloc(LMEM_ZEROINIT, m_setSerialization->Logon.LogonDomainName.Length + sizeof(wchar_t));
CopyMemory(d, m_setSerialization->Logon.LogonDomainName.Buffer, m_setSerialization->Logon.LogonDomainName.Length);
std::wstring t = (PWSTR)u + std::wstring(L"@") + (PWSTR)d;
CopyMemory(*username, t.c_str(), m_setSerialization->Logon.UserName.Length + sizeof(wchar_t) + m_setSerialization->Logon.LogonDomainName.Length);
LocalFree(u);
LocalFree(d);
}
else
{
*username = (PWSTR) LocalAlloc(LMEM_ZEROINIT, m_setSerialization->Logon.UserName.Length + sizeof(wchar_t));
CopyMemory(*username, m_setSerialization->Logon.UserName.Buffer, m_setSerialization->Logon.UserName.Length);
}
}
else
*username = NULL;
}
if (password)
{
if (SerializedPasswordAvailable())
{
*password = (PWSTR) LocalAlloc(LMEM_ZEROINIT, m_setSerialization->Logon.Password.Length + sizeof(wchar_t));
CopyMemory(*password, m_setSerialization->Logon.Password.Buffer, m_setSerialization->Logon.Password.Length);
}
else
*password = <PASSWORD>;
}
if (domain)
{
if (SerializedDomainNameAvailable())
{
*domain = (PWSTR) LocalAlloc(LMEM_ZEROINIT, m_setSerialization->Logon.LogonDomainName.Length + sizeof(wchar_t));
CopyMemory(*domain, m_setSerialization->Logon.LogonDomainName.Buffer, m_setSerialization->Logon.LogonDomainName.Length);
}
else
*domain = NULL;
}
}
void Provider::ServiceStateChanged(bool newState)
{
if(m_logonUiCallbackEvents)
{
m_logonUiCallbackEvents->CredentialsChanged(m_logonUiCallbackContext);
}
}
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using pGina.Shared.Settings;
namespace pGina.Plugin.LocalMachine
{
public class Settings
{
private static dynamic m_settings = new pGinaDynamicSettings(PluginImpl.PluginUuid);
static Settings()
{
// Authentication step settings:
m_settings.SetDefault("AlwaysAuthenticate", false); // Auth regardless of other plugins auth step
// Authorization step settings
m_settings.SetDefault("AuthzLocalAdminsOnly", false); // Prevent non-admins
m_settings.SetDefault("AuthzLocalGroupsOnly", false); // Require group membership in following list
m_settings.SetDefault("AuthzLocalGroups", new string[] { }); // Only users in these groups (in their UserInformation, not in SAM!) can be authorized
m_settings.SetDefault("AuthzApplyToAllUsers", true); // Authorize *all* users according to above rules, if false - non-admin/group checks are only done for users *we* authenticated
m_settings.SetDefault("MirrorGroupsForAuthdUsers", false); // Load users groups from local SAM into userInfo
// Gateway step settings
m_settings.SetDefault("GroupCreateFailIsFail", true); // Do we fail gateway if group create/add fails?
m_settings.SetDefault("MandatoryGroups", new string[] { }); // *All* users are added to these groups (by name)
m_settings.SetDefault("RemoveProfiles", false); // Do we remove accounts/profiles after logout?
m_settings.SetDefault("ScramblePasswords", false); // Do we scramble users passwords after logout?
m_settings.SetDefault("ScramblePasswordsWhenLMAuthFails", true); // Only scramble when LM fails or doesnt execute
m_settings.SetDefault("ScramblePasswordsExceptions", new string[] { });
// Cleanup thread settings (not user configurable)
m_settings.SetDefault("CleanupUsers", new string[] { }); // List of principal names we must cleanup!
m_settings.SetDefault("BackgroundTimerSeconds", 60); // How often we look to cleanup
}
public static dynamic Store
{
get { return m_settings; }
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace pGina.Plugin.MySQLAuth
{
public partial class Configuration : Form
{
private log4net.ILog m_logger = log4net.LogManager.GetLogger("MySQLAuth Configuration");
public Configuration()
{
InitializeComponent();
InitUI();
}
private void InitUI()
{
this.hostTB.Text = Settings.Store.Host;
int port = Settings.Store.Port;
this.portTB.Text = Convert.ToString(port);
this.userTB.Text = Settings.Store.User;
this.passwordTB.Text = Settings.Store.GetEncryptedSetting("Password");
this.dbTB.Text = Settings.Store.Database;
bool useSsl = Settings.Store.UseSsl;
this.useSslCB.Checked = useSsl;
// User table schema settings
this.userTableTB.Text = Settings.Store.Table;
this.unameColTB.Text = Settings.Store.UsernameColumn;
this.hashMethodColTB.Text = Settings.Store.HashMethodColumn;
this.passwdColTB.Text = Settings.Store.PasswordColumn;
this.userPrimaryKeyColTB.Text = Settings.Store.UserTablePrimaryKeyColumn;
int encodingInt = Settings.Store.HashEncoding;
Settings.HashEncoding encoding = (Settings.HashEncoding)encodingInt;
if (encoding == Settings.HashEncoding.HEX)
this.encHexRB.Checked = true;
else
this.encBase64RB.Checked = true;
// Group table schema settings
this.groupTableNameTB.Text = Settings.Store.GroupTableName;
this.groupNameColTB.Text = Settings.Store.GroupNameColumn;
this.groupTablePrimaryKeyColTB.Text = Settings.Store.GroupTablePrimaryKeyColumn;
// User-Group table settings
this.userGroupTableNameTB.Text = Settings.Store.UserGroupTableName;
this.userGroupUserFKColTB.Text = Settings.Store.UserForeignKeyColumn;
this.userGroupGroupFKColTB.Text = Settings.Store.GroupForeignKeyColumn;
/////////////// Authorization tab /////////////////
this.cbAuthzMySqlGroupMemberOrNot.SelectedIndex = 0;
this.cbAuthzGroupRuleAllowOrDeny.SelectedIndex = 0;
this.ckDenyWhenMySqlAuthFails.Checked = Settings.Store.AuthzRequireMySqlAuth;
List<GroupAuthzRule> lst = GroupRuleLoader.GetAuthzRules();
// The last one should be the default rule
if (lst.Count > 0 &&
lst[lst.Count - 1].RuleCondition == GroupRule.Condition.ALWAYS)
{
GroupAuthzRule rule = lst[lst.Count - 1];
if (rule.AllowOnMatch)
this.rbDefaultAllow.Checked = true;
else
this.rbDefaultDeny.Checked = true;
lst.RemoveAt(lst.Count - 1);
}
else
{
// The list is empty or the last rule is not a default rule.
throw new Exception("Default rule not found in rule list.");
}
// The rest of the rules
foreach (GroupAuthzRule rule in lst)
this.listBoxAuthzRules.Items.Add(rule);
///////////////// Gateway tab ///////////////
List<GroupGatewayRule> gwLst = GroupRuleLoader.GetGatewayRules();
foreach (GroupGatewayRule rule in gwLst)
this.gtwRulesListBox.Items.Add(rule);
this.gtwRuleConditionCB.SelectedIndex = 0;
this.m_preventLogonWhenServerUnreachableCb.Checked = Settings.Store.PreventLogonOnServerError;
}
private void cancelButton_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
private void saveButton_Click(object sender, EventArgs e)
{
if (Save())
{
this.DialogResult = DialogResult.OK;
this.Close();
}
}
private bool Save()
{
int port = 0;
try
{
port = Convert.ToInt32(this.portTB.Text);
}
catch (Exception)
{
MessageBox.Show("The port must be a positive integer.");
return false;
}
Settings.Store.Host = this.hostTB.Text.Trim();
Settings.Store.Port = port;
Settings.Store.User = this.userTB.Text.Trim();
Settings.Store.SetEncryptedSetting("Password", this.passwordTB.Text);
Settings.Store.Database = this.dbTB.Text.Trim();
Settings.Store.UseSsl = this.useSslCB.Checked;
// User table settings
Settings.Store.Table = this.userTableTB.Text.Trim();
Settings.Store.UsernameColumn = this.unameColTB.Text.Trim();
Settings.Store.HashMethodColumn = this.hashMethodColTB.Text.Trim();
Settings.Store.PasswordColumn = this.passwdColTB.Text.Trim();
Settings.Store.UserTablePrimaryKeyColumn = this.userPrimaryKeyColTB.Text.Trim();
if (encHexRB.Checked)
Settings.Store.HashEncoding = (int)Settings.HashEncoding.HEX;
else
Settings.Store.HashEncoding = (int)Settings.HashEncoding.BASE_64;
// Group table schema settings
Settings.Store.GroupTableName = this.groupTableNameTB.Text.Trim();
Settings.Store.GroupNameColumn = this.groupNameColTB.Text.Trim();
Settings.Store.GroupTablePrimaryKeyColumn = this.groupTablePrimaryKeyColTB.Text.Trim();
// User-Group table settings
Settings.Store.UserGroupTableName = this.userGroupTableNameTB.Text.Trim();
Settings.Store.UserForeignKeyColumn = this.userGroupUserFKColTB.Text.Trim();
Settings.Store.GroupForeignKeyColumn = this.userGroupGroupFKColTB.Text.Trim();
////////// Authorization Tab ////////////
Settings.Store.AuthzRequireMySqlAuth = this.ckDenyWhenMySqlAuthFails.Checked;
List<GroupAuthzRule> lst = new List<GroupAuthzRule>();
foreach (Object item in this.listBoxAuthzRules.Items)
{
lst.Add(item as GroupAuthzRule);
m_logger.DebugFormat("Saving rule: {0}", item);
}
// Add the default as the last rule in the list
lst.Add(new GroupAuthzRule(this.rbDefaultAllow.Checked));
GroupRuleLoader.SaveAuthzRules(lst);
// Gateway rules
List<GroupGatewayRule> gwList = new List<GroupGatewayRule>();
foreach (Object item in this.gtwRulesListBox.Items)
{
gwList.Add(item as GroupGatewayRule);
}
GroupRuleLoader.SaveGatewayRules(gwList);
Settings.Store.PreventLogonOnServerError = m_preventLogonWhenServerUnreachableCb.Checked;
return true;
}
private void passwdCB_CheckedChanged(object sender, EventArgs e)
{
this.passwordTB.UseSystemPasswordChar = !this.passwdCB.Checked;
}
private void testBtn_Click(object sender, EventArgs e)
{
TextBoxInfoDialog infoDlg = new TextBoxInfoDialog();
infoDlg.Show();
infoDlg.AppendLine("Beginning test of MySQL database..." + Environment.NewLine);
MySqlConnection conn = null;
string tableName = this.userTableTB.Text.Trim();
try
{
string connStr = this.BuildConnectionString();
if (connStr == null) return;
infoDlg.AppendLine("Connection Status");
infoDlg.AppendLine("-------------------------------------");
conn = new MySqlConnection(connStr);
conn.Open();
infoDlg.AppendLine(string.Format("Connection to {0} successful.", this.hostTB.Text.Trim()));
// Variables to be used repeatedly below
MySqlCommand cmd = null;
MySqlDataReader rdr = null;
string query = "";
// Check SSL status
if (useSslCB.Checked)
{
string cipher = "";
query = "SHOW STATUS LIKE 'Ssl_cipher'";
cmd = new MySqlCommand(query, conn);
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
rdr.Read();
cipher = rdr[1].ToString();
}
rdr.Close();
if (string.IsNullOrEmpty(cipher))
{
infoDlg.AppendLine( "Not using SSL." );
}
else
{
infoDlg.AppendLine("SSL enabled, using cipher: " + cipher);
}
}
else
{
infoDlg.AppendLine( "Not using SSL." );
}
infoDlg.AppendLine( Environment.NewLine + "User Table" );
infoDlg.AppendLine( "-------------------------------");
CheckTable(tableName,
new string[] { this.unameColTB.Text.Trim(), this.passwdColTB.Text.Trim(), this.hashMethodColTB.Text.Trim(), this.userPrimaryKeyColTB.Text.Trim() },
infoDlg, conn);
infoDlg.AppendLine(Environment.NewLine + "Group Table");
infoDlg.AppendLine("-------------------------------");
CheckTable(this.groupTableNameTB.Text.Trim(),
new string[] { this.groupNameColTB.Text.Trim(), this.groupTablePrimaryKeyColTB.Text.Trim() },
infoDlg, conn);
infoDlg.AppendLine(Environment.NewLine + "User-Group Table");
infoDlg.AppendLine("-------------------------------");
CheckTable(this.userGroupTableNameTB.Text.Trim(),
new string[] { this.userGroupUserFKColTB.Text.Trim(), this.userGroupGroupFKColTB.Text.Trim() },
infoDlg, conn);
}
catch (Exception ex)
{
if (ex is MySqlException)
{
MySqlException mysqlEx = ex as MySqlException;
infoDlg.AppendLine("MySQL ERROR: " + mysqlEx.Message);
}
else
{
infoDlg.AppendLine(string.Format("ERROR: A fatal error occured: {0}", ex));
}
}
finally
{
infoDlg.AppendLine(Environment.NewLine + "Closing connection.");
if (conn != null)
conn.Close();
infoDlg.AppendLine("Test complete.");
}
}
private void CheckTable(string tableName, string[] columnNames, TextBoxInfoDialog infoDlg, MySqlConnection conn)
{
// Check for existence of the table
bool tableExists = this.TableExists(tableName, conn);
if (tableExists)
{
m_logger.DebugFormat("Table \"{0}\" found.", tableName);
infoDlg.AppendLine(string.Format("Table \"{0}\" found.", tableName));
}
else
{
m_logger.DebugFormat("Table {0} not found.", tableName);
infoDlg.AppendLine(string.Format("ERROR: Table \"{0}\" not found.", tableName));
return;
}
if (tableExists)
{
// Get column names from DB
List<string> columnNamesFromDB = new List<string>();
string query = string.Format("DESCRIBE {0}", tableName);
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string colName = rdr[0].ToString();
columnNamesFromDB.Add(colName);
}
rdr.Close();
// Check for appropriate columns.
bool ok = true;
foreach (string c in columnNames)
{
if (columnNamesFromDB.Contains(c, StringComparer.CurrentCultureIgnoreCase))
infoDlg.AppendLine(string.Format("Found column \"{0}\"", c));
else
{
ok = false;
infoDlg.AppendLine(string.Format("ERROR: Column \"{0}\" not found!", c));
}
}
if (!ok)
infoDlg.AppendLine(string.Format("ERROR: Table \"{0}\" schema looks incorrect.", tableName));
}
}
private void createTableBtn_Click(object sender, EventArgs e)
{
string connStr = this.BuildConnectionString();
if (connStr == null) return;
TextBoxInfoDialog infoDlg = new TextBoxInfoDialog();
infoDlg.ClearText();
infoDlg.Show();
try
{
using (MySqlConnection conn = new MySqlConnection(connStr))
{
infoDlg.AppendLine("Connecting...");
conn.Open();
// User table
string tableName = this.userTableTB.Text.Trim();
infoDlg.AppendLine(Environment.NewLine +
string.Format("Creating table \"{0}\"", tableName));
if (!this.TableExists(tableName, conn))
{
// Column names
string pk = this.userPrimaryKeyColTB.Text.Trim();
string unameCol = this.unameColTB.Text.Trim();
string hashMethodCol = this.hashMethodColTB.Text.Trim();
string passwdCol = this.passwdColTB.Text.Trim();
// Is the primary key the same as the username?
bool pkIsUserName =
unameCol.Equals(pk, StringComparison.CurrentCultureIgnoreCase);
StringBuilder sql = new StringBuilder();
sql.AppendFormat("CREATE TABLE {0} ( \r\n", tableName);
if (!pkIsUserName)
sql.AppendFormat(" {0} BIGINT auto_increment PRIMARY KEY, \r\n", pk);
sql.AppendFormat(" {0} VARCHAR(128) {1}, \r\n", unameCol, pkIsUserName ? "PRIMARY KEY" : "NOT NULL UNIQUE");
sql.AppendFormat(" {0} TEXT NOT NULL, \r\n", hashMethodCol);
sql.AppendFormat(" {0} TEXT \r\n", passwdCol);
sql.Append(")"); // End create table.
infoDlg.AppendLine("Executing SQL:");
infoDlg.AppendLine(sql.ToString());
using (MySqlCommand cmd = new MySqlCommand(sql.ToString(), conn))
{
cmd.ExecuteNonQuery();
infoDlg.AppendLine(string.Format("Table \"{0}\" created.", tableName));
}
}
else
{
infoDlg.AppendLine(
string.Format("WARNING: Table \"{0}\"already exists, skipping.", tableName));
}
// Group table
tableName = this.groupTableNameTB.Text.Trim();
infoDlg.AppendLine(Environment.NewLine +
string.Format("Creating table \"{0}\"", tableName));
if (!this.TableExists(tableName, conn))
{
// Column names
string pk = this.groupTablePrimaryKeyColTB.Text.Trim();
string groupNameCol = this.groupNameColTB.Text.Trim();
// Is the primary key the same as the group name?
bool pkIsGroupName =
groupNameCol.Equals(pk, StringComparison.CurrentCultureIgnoreCase);
StringBuilder sql = new StringBuilder();
sql.AppendFormat("CREATE TABLE {0} ( \r\n", tableName);
if (!pkIsGroupName)
sql.AppendFormat(" {0} BIGINT AUTO_INCREMENT PRIMARY KEY, \r\n", pk);
sql.AppendFormat(" {0} VARCHAR(128) {1} \r\n", groupNameCol, pkIsGroupName ? "PRIMARY KEY" : "NOT NULL UNIQUE");
sql.Append(")"); // End create table.
infoDlg.AppendLine("Executing SQL:");
infoDlg.AppendLine(sql.ToString());
using (MySqlCommand cmd = new MySqlCommand(sql.ToString(), conn))
{
cmd.ExecuteNonQuery();
infoDlg.AppendLine(string.Format("Table \"{0}\" created.", tableName));
}
}
else
{
infoDlg.AppendLine(
string.Format("WARNING: Table \"{0}\"already exists, skipping.", tableName));
}
// user-Group table
tableName = this.userGroupTableNameTB.Text.Trim();
infoDlg.AppendLine(Environment.NewLine +
string.Format("Creating table \"{0}\"", tableName));
if (!this.TableExists(tableName, conn))
{
// Column names
string userFK = this.userGroupUserFKColTB.Text.Trim();
string userPK = this.userPrimaryKeyColTB.Text.Trim();
string groupFK = this.userGroupGroupFKColTB.Text.Trim();
string groupPK = this.groupTablePrimaryKeyColTB.Text.Trim();
string groupNameCol = this.groupNameColTB.Text.Trim();
string unameCol = this.unameColTB.Text.Trim();
// Is the primary key the same as the group name?
bool pkIsGroupName =
groupNameCol.Equals(groupPK, StringComparison.CurrentCultureIgnoreCase);
bool pkIsUserName =
unameCol.Equals(userPK, StringComparison.CurrentCultureIgnoreCase);
StringBuilder sql = new StringBuilder();
sql.AppendFormat("CREATE TABLE {0} ( \r\n", tableName);
sql.AppendFormat(" {0} {1}, \r\n", groupFK, pkIsGroupName ? "VARCHAR(128)" : "BIGINT");
sql.AppendFormat(" {0} {1}, \r\n", userFK, pkIsUserName ? "VARCHAR(128)" : "BIGINT");
sql.AppendFormat(" PRIMARY KEY ({0}, {1}) \r\n", userFK, groupFK);
sql.Append(")"); // End create table.
infoDlg.AppendLine("Executing SQL:");
infoDlg.AppendLine(sql.ToString());
MySqlCommand cmd = new MySqlCommand(sql.ToString(), conn);
cmd.ExecuteNonQuery();
infoDlg.AppendLine(string.Format("Table \"{0}\" created.", tableName));
}
else
{
infoDlg.AppendLine(
string.Format("WARNING: Table \"{0}\"already exists, skipping.", tableName));
}
}
}
catch (MySqlException ex)
{
infoDlg.AppendLine(String.Format("ERROR: {0}", ex.Message));
}
finally
{
infoDlg.AppendLine(Environment.NewLine + "Finished.");
}
}
private bool TableExists(string tableName, MySqlConnection conn)
{
string query = "SHOW TABLES LIKE @table";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@table", tableName);
MySqlDataReader rdr = cmd.ExecuteReader();
bool tableExists = rdr.HasRows;
rdr.Close();
return tableExists;
}
private string BuildConnectionString()
{
uint port = 0;
try
{
port = Convert.ToUInt32(this.portTB.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid port number.");
return null;
}
MySqlConnectionStringBuilder bldr = new MySqlConnectionStringBuilder();
bldr.Server = this.hostTB.Text.Trim();
bldr.Port = port;
bldr.UserID = this.userTB.Text.Trim();
bldr.Database = this.dbTB.Text.Trim();
bldr.Password = <PASSWORD>.passwordTB.Text;
if (this.useSslCB.Checked)
{
bldr.SslMode = MySqlSslMode.Required;
}
return bldr.GetConnectionString(true);
}
private void encHexRB_CheckedChanged(object sender, EventArgs e)
{
}
private void groupBox3_Enter(object sender, EventArgs e)
{
}
private void gtwRuleAddBtn_Click(object sender, EventArgs e)
{
string localGrp = this.gtwRuleLocalGroupTB.Text.Trim();
if (string.IsNullOrEmpty(localGrp))
{
MessageBox.Show("Please enter a local group name");
return;
}
int idx = this.gtwRuleConditionCB.SelectedIndex;
GroupRule.Condition c;
if (idx == 0) c = GroupRule.Condition.MEMBER_OF;
else if (idx == 1) c = GroupRule.Condition.NOT_MEMBER_OF;
else
throw new Exception("Unrecognized option in gtwRuleAddBtn_Click");
if (c == GroupRule.Condition.ALWAYS)
{
this.gtwRulesListBox.Items.Add(new GroupGatewayRule(localGrp));
}
else
{
string remoteGroup = this.gtwRuleMysqlGroupTB.Text.Trim();
if (string.IsNullOrEmpty(remoteGroup))
{
MessageBox.Show("Please enter a remote group name");
return;
}
this.gtwRulesListBox.Items.Add(new GroupGatewayRule(remoteGroup, c, localGrp));
}
}
private void gtwRuleConditionCB_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void gtwRuleDeleteBtn_Click(object sender, EventArgs e)
{
int idx = this.gtwRulesListBox.SelectedIndex;
if (idx >= 0 && idx < this.gtwRulesListBox.Items.Count)
this.gtwRulesListBox.Items.RemoveAt(idx);
}
private void btnAuthzGroupRuleAdd_Click(object sender, EventArgs e)
{
string grp = this.tbAuthzRuleGroup.Text.Trim();
if (string.IsNullOrEmpty(grp))
{
MessageBox.Show("Please enter a group name.");
return;
}
int idx = this.cbAuthzMySqlGroupMemberOrNot.SelectedIndex;
GroupRule.Condition c;
if (idx == 0) c = GroupRule.Condition.MEMBER_OF;
else if (idx == 1) c = GroupRule.Condition.NOT_MEMBER_OF;
else
throw new Exception("Unrecognized option in authzRuleAddButton_Click");
idx = this.cbAuthzGroupRuleAllowOrDeny.SelectedIndex;
bool allow;
if (idx == 0) allow = true; // allow
else if (idx == 1) allow = false; // deny
else
throw new Exception("Unrecognized action option in authzRuleAddButton_Click");
GroupAuthzRule rule = new GroupAuthzRule(grp, c, allow);
this.listBoxAuthzRules.Items.Add(rule);
}
private void btnAuthzGroupRuleUp_Click(object sender, EventArgs e)
{
int idx = this.listBoxAuthzRules.SelectedIndex;
if (idx > 0 && idx < this.listBoxAuthzRules.Items.Count)
{
object item = this.listBoxAuthzRules.Items[idx];
this.listBoxAuthzRules.Items.RemoveAt(idx);
this.listBoxAuthzRules.Items.Insert(idx - 1, item);
this.listBoxAuthzRules.SelectedIndex = idx - 1;
}
}
private void btnAuthzGroupRuleDelete_Click(object sender, EventArgs e)
{
int idx = this.listBoxAuthzRules.SelectedIndex;
if (idx >= 0 && idx < this.listBoxAuthzRules.Items.Count)
this.listBoxAuthzRules.Items.RemoveAt(idx);
}
private void btnAuthzGroupRuleDown_Click(object sender, EventArgs e)
{
int idx = this.listBoxAuthzRules.SelectedIndex;
if (idx >= 0 && idx < this.listBoxAuthzRules.Items.Count - 1)
{
object item = this.listBoxAuthzRules.Items[idx];
this.listBoxAuthzRules.Items.RemoveAt(idx);
this.listBoxAuthzRules.Items.Insert(idx + 1, item);
this.listBoxAuthzRules.SelectedIndex = idx + 1;
}
}
private void btnhelp(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/mysql_auth.html");
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.ServiceProcess;
using System.Collections.Generic;
namespace pGina.Shared.Interfaces
{
/// <summary>
/// All plugins must implement this interface
/// </summary>
public interface IPluginBase
{
string Name { get; }
string Description { get; }
string Version { get; }
Guid Uuid { get; }
/// <summary>
/// Called when pGina service starts. Intended for 'startup' time processing. This is
/// not called during simulation so plugins should not do anything here that would
/// be necessary for logon processing.
/// </summary>
void Starting();
/// <summary>
/// Called when the pGina service is shutting down, for 'stopping' time processing. This
/// is not called during simulation. Plugins should not depend on this to clean up
/// post logon.
/// </summary>
void Stopping();
}
/// <summary>
/// Plugins which wish to integrate with the pGina configuration/Plugin
/// management UI must implement this interface
/// </summary>
public interface IPluginConfiguration : IPluginBase
{
void Configure();
}
/// <summary>
/// Plugins that want to be available for use in authentication must
/// implement this interface. At least one plugin
/// must succeed for the login process to continue.
/// </summary>
public interface IPluginAuthentication : IPluginBase
{
Types.BooleanResult AuthenticateUser(Types.SessionProperties properties);
}
/// <summary>
/// Plugins that want to validate a users access (not identity per-se) must
/// implement this interface. All plugins which implement this interface
/// must succeed for the login process to continue.
/// </summary>
public interface IPluginAuthorization : IPluginBase
{
Types.BooleanResult AuthorizeUser(Types.SessionProperties properties);
}
/// <summary>
/// Plugins that want to be involved in account management (post-auth*)
/// must implement this interface. All plugins which implement this interface
/// must succeed for the login process to continue.
/// </summary>
public interface IPluginAuthenticationGateway : IPluginBase
{
/// <summary>
/// User has been authenticated and authorized - now
/// is your chance to do other accounting/management before the user's login is successful.
/// </summary>
/// <param name="properties">Info about the session</param>
/// <returns>Whether or not the plugin was successful.</returns>
Types.BooleanResult AuthenticatedUserGateway(Types.SessionProperties properties);
}
/// <summary>
/// Plugins that want notification of events as they occur must implement
/// this interface. Note that these are notifications only - these are
/// called from the core service in the context of the service and it's
/// session (i.e. not in users session, as user, etc). Plugins which want
/// to perform processing which requires specific context should see the
/// IPlugin[User|System]SessionHelper interfaces.
/// </summary>
public interface IPluginEventNotifications : IPluginBase
{
/// <summary>
/// Default System session notification (as provided to pGina service
/// via http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.onsessionchange.aspx)
/// </summary>
/// <param name="changeDescription">See MSDN, includes session id and change reason (login, logout etc)</param>
/// <param name="properties">
/// If the session is a pGina session, this is the properties instance used by the plugins at auth time.
/// This value is null if the session is not a pGina session.
/// </param>
void SessionChange(int sessionID, SessionChangeReason evnt, Types.SessionProperties properties);
}
/// <summary>
/// Plugins that want notification of shutdown events as they occur must implement this.
/// </summary>
public interface IPluginLogoffRequestAddTime : IPluginBase
{
/// <summary>
/// Called during a shutdown, after the GPO shutdown scripts
/// it requires a bool true to wait a while longer
/// </summary>
/// <param name="props"></param>
Boolean LogoffRequestAddTime();
/// <summary>
/// Called prior to authentication for every login.
/// to check if the user that tries to login is still logged out
/// bool false means the user can login
/// </summary>
/// <param name="username"></param>
Boolean LoginUserRequest(string username);
}
/// <summary>
/// Plugins that want to have some persistent state between stages can implement this
/// interface. BeginChain will be called at the beginning of a login process and
/// EndChain will be called when the login process completes (regardless of which stage
/// causes the login to fail). Plugins can store any state associated with the login in
/// the SessionProperties object provided as a parameter.
/// </summary>
public interface IStatefulPlugin : IPluginBase
{
/// <summary>
/// Called prior to authentication for every login.
/// </summary>
/// <param name="props"></param>
void BeginChain(Types.SessionProperties props);
/// <summary>
/// Called at the end of a login process regardless of success or failure,
/// and regardless of what stage caused the login to fail.
/// </summary>
/// <param name="props"></param>
void EndChain(Types.SessionProperties props);
}
/// <summary>
/// Plugins that want to support the change password scenario should
/// implement this interface.
/// </summary>
public interface IPluginChangePassword : IPluginBase
{
/// <summary>
/// Attempt to change the password.
/// </summary>
/// <param name="properties">Info about the session</param>
/// <returns>Success/failure of the change password operation.</returns>
Types.BooleanResult ChangePassword(Types.SessionProperties props, Types.ChangePasswordPluginActivityInfo pluginInfo);
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include "DialogBase.h"
#include "Dll.h"
namespace pGina
{
namespace GINA
{
DialogBase::DialogBase(WinlogonInterface * iface, int dialogId) :
m_winlogon(iface), m_dialogId(dialogId), m_instance(GetMyInstance()), m_hwnd(0), m_nextTimer(1)
{
}
int DialogBase::ShowDialog()
{
return m_winlogon->WlxDialogBoxParam(m_instance, MAKEINTRESOURCE(m_dialogId), 0, DialogProcInternal, (LPARAM)this);
}
/*static*/
INT_PTR CALLBACK DialogBase::DialogProcInternal(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
// When we get an init, we can count on lparam being the value we specified
if(msg == WM_INITDIALOG)
{
// lparam is us!
DialogBase * dialog = (DialogBase *)lparam;
dialog->Hwnd(hwnd);
dialog->CenterWindow();
// Now set a ptr to us in user data that will always be available
SetWindowLongPtr(hwnd, GWLP_USERDATA, lparam);
// Inherited init
dialog->DialogInit();
return TRUE;
}
else
{
// Try and get a ptr to us out of user data, if not available, just do nothing
DialogBase * dialog = (DialogBase *) GetWindowLongPtr(hwnd, GWLP_USERDATA);
if(!dialog)
return FALSE;
// We call different verbs on subs based on message
switch(msg)
{
case WM_COMMAND:
if(dialog->Command(LOWORD(wparam)))
return true;
break;
case WM_TIMER:
if(dialog->Timer(LOWORD(wparam)))
return true;
break;
case WM_DESTROY:
dialog->InternalDestroy();
break;
}
return dialog->DialogProcImpl(msg, wparam, lparam);
}
}
void DialogBase::InternalDestroy()
{
if(m_nextTimer > 1)
{
for(int x = 1; x < m_nextTimer; x++)
{
StopTimer(x);
}
}
Destroy();
}
void DialogBase::CenterWindow()
{
RECT rect = {0, 0, 0, 0};
GetWindowRect(m_hwnd, &rect);
LONG Style = GetWindowLong(m_hwnd, GWL_STYLE);
LONG dx = rect.right - rect.left;
LONG dy = rect.bottom - rect.top;
LONG dxParent, dyParent;
if ((Style & WS_CHILD) == 0)
{
// No parent, center on screen
dxParent = GetSystemMetrics(SM_CXSCREEN);
dyParent = GetSystemMetrics(SM_CYSCREEN);
}
else
{
// Center on parent
HWND hwndParent = GetParent(m_hwnd);
if (hwndParent == NULL)
{
// No parent? Use desktop...
hwndParent = GetDesktopWindow();
}
RECT rectParent;
GetWindowRect(hwndParent, &rectParent);
dxParent = rectParent.right - rectParent.left;
dyParent = rectParent.bottom - rectParent.top;
}
rect.left = (dxParent - dx) / 2;
rect.top = (dyParent - dy) / 3;
SetWindowPos(m_hwnd, HWND_TOPMOST, rect.left, rect.top, 0, 0, SWP_NOSIZE);
SetForegroundWindow(m_hwnd);
}
HWND DialogBase::GetItem(int itemId)
{
return GetDlgItem(m_hwnd, itemId);
}
void DialogBase::SetCaption(const wchar_t *caption)
{
SetWindowText(m_hwnd, caption);
}
void DialogBase::SetItemText(int itemId, const wchar_t *text)
{
SetDlgItemText(m_hwnd, itemId, text);
}
void DialogBase::EnableItem(int itemId)
{
EnableWindow(GetItem(itemId), TRUE);
}
void DialogBase::DisableItem(int itemId)
{
EnableWindow(GetItem(itemId), FALSE);
}
void DialogBase::HideItem(int itemId)
{
ShowWindow(GetItem(itemId), FALSE);
}
void DialogBase::ShowItem(int itemId)
{
ShowWindow(GetItem(itemId), TRUE);
}
void DialogBase::CheckState(int itemId, bool checkstate)
{
SendMessage(GetItem(itemId), BM_SETCHECK, checkstate, 0);
}
bool DialogBase::CheckState(int itemId)
{
return IsDlgButtonChecked(m_hwnd, itemId) == BST_CHECKED;
}
std::wstring DialogBase::GetItemText(int itemId)
{
wchar_t buffer[1024 * 64]; // 64k buffer
memset(buffer, 0, sizeof(buffer));
GetDlgItemText(m_hwnd, itemId, buffer, 1024 * 64);
return buffer;
}
void DialogBase::SetFocusItem(int itemid)
{
SetFocus(GetItem(itemid));
}
void DialogBase::SetItemBitmap(int itemid, HBITMAP bitmap)
{
SendDlgItemMessage(m_hwnd, itemid, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)bitmap);
}
int DialogBase::StartTimer(unsigned int period)
{
int timerId = m_nextTimer;
m_nextTimer++;
UINT_PTR result = SetTimer(m_hwnd, (UINT_PTR) timerId, period, NULL);
return timerId;
}
void DialogBase::StopTimer(int timerId)
{
KillTimer(m_hwnd, (UINT_PTR) timerId);
}
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.DirectoryServices.Protocols;
using log4net;
using pGina.Shared.Interfaces;
using pGina.Shared.Types;
namespace pGina.Plugin.Ldap
{
public class LdapPlugin : IStatefulPlugin, IPluginAuthentication, IPluginAuthorization, IPluginAuthenticationGateway, IPluginConfiguration, IPluginChangePassword
{
public static readonly Guid LdapUuid = new Guid("{0F52390B-C781-43AE-BD62-553C77FA4CF7}");
private ILog m_logger = LogManager.GetLogger("LdapPlugin");
public LdapPlugin()
{
using(Process me = Process.GetCurrentProcess())
{
m_logger.DebugFormat("LDAP Plugin initialized on {0} in PID: {1} Session: {2}", Environment.MachineName, me.Id, me.SessionId);
}
}
public string Name
{
get { return "LDAP"; }
}
public string Description
{
get { return "Uses a LDAP server as a data source for authentication and/or group authorization."; }
}
public string Version
{
get
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public Guid Uuid
{
get { return LdapUuid; }
}
public BooleanResult AuthenticateUser(Shared.Types.SessionProperties properties)
{
// Get the LdapServer object from the session properties (created in BeginChain)
LdapServer server = properties.GetTrackedSingle<LdapServer>();
if (server == null)
return new BooleanResult() { Success = false, Message = "Internal error: LdapServer object not available" };
try
{
m_logger.DebugFormat("AuthenticateUser({0})", properties.Id.ToString());
Shared.Types.UserInformation userInfo = properties.GetTrackedSingle<Shared.Types.UserInformation>();
m_logger.DebugFormat("Received username: {0}", userInfo.Username);
// Authenticate the login
m_logger.DebugFormat("Attempting authentication for {0}", userInfo.Username);
return server.Authenticate(userInfo.Username, userInfo.Password, properties);
}
catch (Exception e)
{
if (e is LdapException)
{
LdapException ldapEx = (e as LdapException);
if (ldapEx.ErrorCode == 81)
{
// Server can't be contacted, set server object to null
m_logger.ErrorFormat("Server unavailable: {0}, {1}", ldapEx.ServerErrorMessage, e.Message);
server.Close();
properties.AddTrackedSingle<LdapServer>(null);
return new BooleanResult { Success = false, Message = "Failed to contact LDAP server." };
}
}
// This is an unexpected error, so set LdapServer object to null, because
// subsequent stages shouldn't use it, and this indicates to later stages
// that this stage failed unexpectedly.
server.Close();
properties.AddTrackedSingle<LdapServer>(null);
m_logger.ErrorFormat("Exception in LDAP authentication: {0}", e);
throw; // Allow pGina service to catch and handle exception
}
}
public void Configure()
{
Configuration conf = new Configuration();
conf.ShowDialog();
}
public void Starting() { }
public void Stopping() { }
public void BeginChain(SessionProperties props)
{
m_logger.Debug("BeginChain");
try
{
LdapServer serv = new LdapServer();
props.AddTrackedSingle<LdapServer>(serv);
}
catch (Exception e)
{
m_logger.ErrorFormat("Failed to create LdapServer: {0}", e);
props.AddTrackedSingle<LdapServer>(null);
}
}
public void EndChain(SessionProperties props)
{
m_logger.Debug("EndChain");
LdapServer serv = props.GetTrackedSingle<LdapServer>();
if (serv != null) serv.Close();
}
public BooleanResult AuthorizeUser(SessionProperties properties)
{
m_logger.Debug("LDAP Plugin Authorization");
bool requireAuth = Settings.Store.AuthzRequireAuth;
// Get the authz rules from registry
List<GroupAuthzRule> rules = GroupRuleLoader.GetAuthzRules();
// Get the LDAP server object
LdapServer serv = properties.GetTrackedSingle<LdapServer>();
// If LDAP server object is not found, then something went wrong in authentication.
// We allow or deny based on setting
if (serv == null)
{
m_logger.ErrorFormat("AuthorizeUser: Internal error, LdapServer object not available.");
// LdapServer is not available, allow or deny based on settings.
return new BooleanResult()
{
Success = Settings.Store.AuthzAllowOnError,
Message = "LDAP server unavailable."
};
}
// If we require authentication, and we failed to auth this user, then we
// fail authorization. Note that we do this AFTER checking the LDAP server object
// because we may want to succeed if the authentication failed due to server
// being unavailable.
PluginActivityInformation actInfo = properties.GetTrackedSingle<PluginActivityInformation>();
if (requireAuth && !WeAuthedThisUser(actInfo) )
{
m_logger.InfoFormat("Deny because LDAP auth failed, and configured to require LDAP auth.");
return new BooleanResult()
{
Success = false,
Message = "Deny because LDAP authentication failed, or did not execute."
};
}
// Apply the authorization rules
try
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
// Bind for searching if we have rules to process. If there's only one, it's the
// default rule which doesn't require searching the LDAP tree.
if (rules.Count > 0)
{
this.BindForAuthzOrGatewaySearch(serv);
}
foreach (GroupAuthzRule rule in rules)
{
bool inGroup = false;
string path = rule.path.Replace("%u", userInfo.Username);
string filter = rule.filter.Replace("%u", userInfo.Username);
inGroup = serv.GetUserAttribValue(path, filter, rule.SearchScope, new string[] { "dn" }).Count > 0;
m_logger.DebugFormat("User {0} {1} {2} {3}", userInfo.Username, inGroup ? "is" : "is not", filter, path);
if (rule.RuleMatch(inGroup))
{
if (rule.AllowOnMatch)
return new BooleanResult()
{
Success = true,
Message = string.Format("Allow via rule: \"{0}\"", rule.ToString())
};
else
return new BooleanResult()
{
Success = false,
Message = string.Format("Deny via rule: \"{0}\"", rule.ToString())
};
}
}
// If there is no matching rule use default. allow or deny
if ((bool)Settings.Store.AuthzDefault)
return new BooleanResult() { Success = true, Message = "" };
else
return new BooleanResult() { Success = false, Message = String.Format("You are not allowed to login! No matching rule found! Default rule:{0}", (bool)Settings.Store.AuthzDefault ? "Allow" : "Deny") };
}
catch (Exception e)
{
if (e is LdapException)
{
LdapException ldapEx = (e as LdapException);
if (ldapEx.ErrorCode == 81)
{
// Server can't be contacted, set server object to null
m_logger.ErrorFormat("Server unavailable: {0}, {1}", ldapEx.ServerErrorMessage, e.Message);
serv.Close();
properties.AddTrackedSingle<LdapServer>(null);
return new BooleanResult
{
Success = Settings.Store.AuthzAllowOnError,
Message = "Failed to contact LDAP server."
};
}
else if (ldapEx.ErrorCode == 49)
{
// This is invalid credentials, return false, but server object should remain connected
m_logger.ErrorFormat("LDAP bind failed: invalid credentials.");
return new BooleanResult
{
Success = false,
Message = "Authorization via LDAP failed. Invalid credentials."
};
}
}
// Unexpected error, let the PluginDriver catch
m_logger.ErrorFormat("Error during authorization: {0}", e);
throw;
}
}
public BooleanResult AuthenticatedUserGateway(SessionProperties properties)
{
m_logger.Debug("LDAP Plugin Gateway");
List<string> addedGroups = new List<string>();
LdapServer serv = properties.GetTrackedSingle<LdapServer>();
// If the server is unavailable, we go ahead and succeed anyway.
if (serv == null)
{
m_logger.ErrorFormat("AuthenticatedUserGateway: Internal error, LdapServer object not available.");
return new BooleanResult()
{
Success = true,
Message = "LDAP server not available"
};
}
try
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
List<GroupGatewayRule> rules = GroupRuleLoader.GetGatewayRules();
bool boundToServ = false;
foreach (GroupGatewayRule rule in rules)
{
bool inGroup = false;
// If we haven't bound to server yet, do so.
if (!boundToServ)
{
this.BindForAuthzOrGatewaySearch(serv);
boundToServ = true;
}
string path = rule.path.Replace("%u", userInfo.Username);
string filter = rule.filter.Replace("%u", userInfo.Username);
//inGroup = serv.MemberOfGroup(user, rule.Group);
inGroup = serv.GetUserAttribValue(path, filter, rule.SearchScope, new string[] { "dn" }).Count > 0;
m_logger.DebugFormat("User {0} {1} {2} {3}", userInfo.Username, filter, inGroup ? "is" : "is not", path);
if (rule.RuleMatch(inGroup))
{
m_logger.InfoFormat("Adding user {0} to local group {1}, due to rule \"{2}\"", userInfo.Username, rule.LocalGroup, rule.ToString());
addedGroups.Add(rule.LocalGroup);
userInfo.AddGroup( new GroupInformation() { Name = rule.LocalGroup } );
}
}
}
catch (Exception e)
{
m_logger.ErrorFormat("Error during gateway: {0}", e);
// Error does not cause failure
return new BooleanResult() { Success = true, Message = e.Message };
}
string message = "";
if (addedGroups.Count > 0)
message = string.Format("Added to groups: {0}", string.Join(", ", addedGroups));
else
message = "No groups added.";
return new BooleanResult() { Success = true, Message = message };
}
public BooleanResult ChangePassword(SessionProperties properties, ChangePasswordPluginActivityInfo pluginInfo)
{
m_logger.Debug("ChangePassword()");
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
using (LdapServer serv = new LdapServer())
{
try
{
string[] hosts = Settings.Store.LdapHost;
// Authenticate using old password
BooleanResult result = serv.Authenticate(userInfo.Username, userInfo.oldPassword, properties);
if (!result.Success)
{
return new BooleanResult { Success = false, Message = "Password change failed: Invalid LDAP username or password." };
}
// Set the password attributes
List<AttributeEntry> attribs = CPAttributeSettings.Load();
foreach (AttributeEntry entry in attribs)
{
if (entry.Method.HasFlag(Methods.ADPWD))
{
bool ADpwd = false;
string pwdmessage = "";
foreach (string server in hosts)
{
pwdmessage = Abstractions.WindowsApi.pInvokes.UserChangePassword(server, userInfo.Username, userInfo.oldPassword, userInfo.Password);
if (pwdmessage == "")
{
ADpwd = true;
break;
}
}
if (!ADpwd)
{
return new BooleanResult { Success = false, Message = "Failed to change password.\n" + pwdmessage };
}
continue;
}
if (entry.Method.HasFlag(Methods.Timestamps) || entry.Method.HasFlag(Methods.Timestampd) || entry.Method.HasFlag(Methods.Timestampt))
{
TimeMethod time = TimeMethod.methods[entry.Method];
m_logger.DebugFormat("Setting attribute {0} using method {1}", entry.Name, time.Name);
if (!serv.SetUserAttribute(userInfo.Username, entry.Name, time.time()))
return new BooleanResult { Success = false, Message = "LDAPplugin failed by setting an attribute\nFor more details please consult the log!" };
}
else
{
AttribMethod hasher = AttribMethod.methods[entry.Method];
m_logger.DebugFormat("Setting attribute {0} using method {1}", entry.Name, hasher.Name);
if (!serv.SetUserAttribute(userInfo.Username, entry.Name, hasher.hash(userInfo.Password)))
return new BooleanResult { Success = false, Message = "LDAPplugin failed by setting an attribute\nFor more details please consult the log!" };
}
}
return new BooleanResult { Success = true, Message = "LDAP password successfully changed" };
}
catch (Exception e)
{
m_logger.ErrorFormat("Exception in ChangePassword: {0}", e);
return new BooleanResult() { Success = false, Message = "Error in LDAP plugin." };
}
}
}
private bool WeAuthedThisUser( PluginActivityInformation actInfo )
{
try
{
BooleanResult ldapResult = actInfo.GetAuthenticationResult(this.Uuid);
return ldapResult.Success;
}
catch (KeyNotFoundException)
{
// The plugin is not enabled for authentication
return false;
}
}
private void BindForAuthzOrGatewaySearch(LdapServer serv)
{
// If we're configured to use authorization credentials for searching, then
// we don't need to bind to the server (it's already been done if auth was
// successful).
bool useAuthBindForSearch = Settings.Store.UseAuthBindForAuthzAndGateway;
if (!useAuthBindForSearch)
{
serv.BindForSearch();
}
else
{
m_logger.DebugFormat("Using authentication credentials for LDAP search.");
}
}
}
}
<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <Windows.h>
#include <pGinaNativeLib.h>
#include "DialogBase.h"
#include "resource.h"
namespace pGina
{
namespace GINA
{
class DialogLoggedOutSAS : public DialogBase
{
public:
typedef enum DialogResult
{
SAS_ACTION_LOGON = WLX_SAS_ACTION_LOGON,
SAS_ACTION_NONE = WLX_SAS_ACTION_NONE,
SAS_ACTION_LOCK_WKSTA = WLX_SAS_ACTION_LOCK_WKSTA,
SAS_ACTION_LOGOFF = WLX_SAS_ACTION_LOGOFF,
SAS_ACTION_SHUTDOWN = WLX_SAS_ACTION_SHUTDOWN,
SAS_ACTION_PWD_CHANGED = WLX_SAS_ACTION_PWD_CHANGED,
SAS_ACTION_TASKLIST = WLX_SAS_ACTION_TASKLIST,
SAS_ACTION_UNLOCK_WKSTA = WLX_SAS_ACTION_UNLOCK_WKSTA,
SAS_ACTION_FORCE_LOGOFF = WLX_SAS_ACTION_FORCE_LOGOFF,
SAS_ACTION_SHUTDOWN_POWER_OFF = WLX_SAS_ACTION_SHUTDOWN_POWER_OFF,
SAS_ACTION_SHUTDOWN_REBOOT = WLX_SAS_ACTION_SHUTDOWN_REBOOT,
SAS_ACTION_SHUTDOWN_SLEEP = WLX_SAS_ACTION_SHUTDOWN_SLEEP,
SAS_ACTION_SHUTDOWN_SLEEP2 = WLX_SAS_ACTION_SHUTDOWN_SLEEP2,
SAS_ACTION_SHUTDOWN_HIBERNATE = WLX_SAS_ACTION_SHUTDOWN_HIBERNATE,
SAS_ACTION_RECONNECTED = WLX_SAS_ACTION_RECONNECTED,
SAS_ACTION_DELAYED_FORCE_LOGOFF = WLX_SAS_ACTION_DELAYED_FORCE_LOGOFF,
SAS_ACTION_SWITCH_CONSOLE = WLX_SAS_ACTION_SWITCH_CONSOLE,
SAS_ACTION_MIN = SAS_ACTION_LOGON,
SAS_ACTION_MAX = SAS_ACTION_SWITCH_CONSOLE
};
public:
DialogLoggedOutSAS(WinlogonInterface *iface) :
DialogBase(iface, IDD_LOGGEDOUT_SAS),
m_bitmap(NULL), m_statusTimerId(0)
{
}
virtual void DialogInit();
virtual bool Command(int itemId);
virtual bool Timer(int timerId);
virtual INT_PTR DialogProcImpl(UINT msg, WPARAM wparam, LPARAM lparam);
std::wstring Username() { return m_username; }
void Username(std::wstring const& v) { m_username = v; }
std::wstring Password() { return m_password; }
void Password(std::wstring const& v) { m_password = v; }
private:
void ApplyLogoImage();
void SetServiceStatus();
private:
std::wstring m_username;
std::wstring m_password;
HBITMAP m_bitmap;
int m_statusTimerId;
};
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using pGina.Shared.Settings;
namespace pGina.Plugin.Email
{
public partial class Configuration : Form
{
dynamic m_settings = new pGinaDynamicSettings(EmailAuthPlugin.SimpleUuid);
private static string popSslPort = "995";
private static string popPort = "110";
private static string imapPort = "143";
private static string imapSslPort = "993";
public Configuration()
{
InitializeComponent();
LoadSettings();
}
private void LoadSettings()
{
serverTextBox.Text = Settings.Store.Server;
sslCheckBox.Checked = Settings.Store.UseSsl;
if ((String)Settings.Store.Protocol == "POP3")
popButton.Checked = true;
else if ((String)Settings.Store.Protocol == "IMAP")
imapButton.Checked = true;
portTextBox.Text = Settings.Store.Port;
domainAppendCheckBox.Checked = Settings.Store.AppendDomain;
domainTextBox.Text = Settings.Store.Domain;
int timeout = Settings.Store.NetworkTimeout;
tbTimeout.Text = timeout.ToString();
updateSettings();
}
private void StoreSettings()
{
Settings.Store.Server = serverTextBox.Text.Trim();
Settings.Store.UseSsl = sslCheckBox.Checked;
Settings.Store.Protocol = (popButton.Checked) ? "POP3" : "IMAP";
Settings.Store.Port = portTextBox.Text.Trim();
Settings.Store.AppendDomain = domainAppendCheckBox.Checked;
Settings.Store.Domain = domainTextBox.Text.Replace('@', ' ').Trim();
try
{
int timeout = Convert.ToInt32(tbTimeout.Text);
Settings.Store.NetworkTimeout = timeout;
}
catch (FormatException) { }
}
private bool ValidateInput()
{
if (serverTextBox.Text.Trim().Length == 0)
{
MessageBox.Show("Server address can not be blank.");
return false;
}
if (!popButton.Checked && !imapButton.Checked)
{
MessageBox.Show("A protocol must be selected.");
return false;
}
try
{
int port = Convert.ToInt32(portTextBox.Text);
if (port < 0) throw new FormatException();
}
catch (FormatException)
{
MessageBox.Show("Port must be an integer greater than 0.");
return false;
}
if (domainAppendCheckBox.Checked && domainTextBox.Text.Trim().Length == 0)
{
MessageBox.Show("A domain must be entered if \"Append domain to username\" is checked.");
return false;
}
return true;
}
private void btnOk_Click(object sender, EventArgs e)
{
if (ValidateInput())
{
StoreSettings();
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
private void settingsChanged(object sender, EventArgs e)
{
updateSettings();
}
private void updateSettings()
{
domainLabel.Enabled = domainAppendCheckBox.Checked;
domainTextBox.Enabled = domainAppendCheckBox.Checked;
}
//Changes the default port value if the protocol or SSL status is changed
private void changedProtocol(Object sender, EventArgs e)
{
if(popButton.Checked)
portTextBox.Text = (sslCheckBox.Checked ? popSslPort : popPort);
else
portTextBox.Text = (sslCheckBox.Checked ? imapSslPort : imapPort);
}
private void Btn_help(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/email_auth.html");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using pGina.Shared.Types;
using pGina.Plugin.HttpAuth;
namespace TestingExe
{
class Program
{
static void Main(string[] args)
{
SessionProperties properties = new SessionProperties(new Guid("12345678-1234-1234-1234-123412341234"));
UserInformation userInfo = new UserInformation();
userInfo.Username = "gandalf";
userInfo.Email = "<EMAIL>";
userInfo.Fullname = "<NAME>";
userInfo.LoginScript = "net use x: \\lserver\bakasracky";
userInfo.Password = "<PASSWORD>";
properties.AddTrackedSingle<UserInformation>(userInfo);
PluginImpl plugin = new PluginImpl();
var authResult = plugin.AuthenticateUser(properties);
Debug.Assert(authResult.Success == true, "auth should succeed!");
var gatewayResult = plugin.AuthenticatedUserGateway(properties);
Debug.Assert(authResult.Success == true, "gateway should succeed!");
System.Console.Write("DONE");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
namespace pGina.Service.Impl
{
public class ServiceThread
{
private pGina.Service.Impl.Service m_service = null;
public ServiceThread() { }
public void Start()
{
m_service = new pGina.Service.Impl.Service();
m_service.Start();
}
public void Stop()
{
m_service.Stop();
}
public Boolean OnCustomCommand()
{
return m_service.OnCustomCommand();
}
public void SessionChange(int sessionID, SessionChangeReason evnt)
{
m_service.SessionChange(sessionID, evnt);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace pGina.Plugin.MySqlLogger
{
interface ILoggerMode
{
//Logs the specified event/properties
bool Log(int SessionId, System.ServiceProcess.SessionChangeReason Reason, pGina.Shared.Types.SessionProperties properties);
//Tests to make sure the table exists, and contains the right columns, returns a string indicating the table status.
string TestTable();
//Attempts to create the neccesary table for the logging mode, and returns a string indicating it's success/failure
string CreateTable();
//Sets the connection to the MySql server, so that multiple loggers can share one stream
void SetConnection(MySqlConnection m_conn);
}
class LoggerModeFactory
{
static private MySqlConnection m_conn = null;
private LoggerModeFactory() { }
public static ILoggerMode getLoggerMode(LoggerMode mode)
{
//Create a new MySqlConnection if no viable one is available
if (m_conn == null || m_conn.State != System.Data.ConnectionState.Open)
{
string connStr = BuildConnectionString();
m_conn = new MySqlConnection(connStr);
}
ILoggerMode logger = null;
if (mode == LoggerMode.EVENT)
logger = new EventLoggerMode();
else if (mode == LoggerMode.SESSION)
logger = new SessionLogger();
else
throw new ArgumentException("Invalid LoggerMode");
logger.SetConnection(m_conn);
return logger;
}
public static void closeConnection(){
if(m_conn != null)
m_conn.Close();
m_conn = null;
}
private static string BuildConnectionString()
{
uint port = 0;
try
{
port = Convert.ToUInt32((String)Settings.Store.Port);
}
catch (FormatException e)
{
throw new Exception("Invalid port number.", e);
}
MySqlConnectionStringBuilder bldr = new MySqlConnectionStringBuilder();
bldr.Server = Settings.Store.Host;
bldr.Port = port;
bldr.UserID = Settings.Store.User;
bldr.Database = Settings.Store.Database;
bldr.Password = <PASSWORD>.Store.GetEncryptedSetting("Password");
//m_logger.DebugFormat("Connecting to {0}:{1} as {2}, database: {3}",
// bldr.Server, bldr.Port, bldr.UserID, bldr.Database);
return bldr.GetConnectionString(true);
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using log4net;
using log4net.Config;
namespace pGina.Shared.Logging
{
public static class Logging
{
public static void Init()
{
string curPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string l4nConfig = string.Format("{0}\\{1}", curPath, "log4net.config");
if (!File.Exists(l4nConfig))
{
string curDir = Directory.GetCurrentDirectory();
l4nConfig = string.Format("{0}\\{1}", curDir, "log4net.config");
}
using (Process me = Process.GetCurrentProcess())
{
log4net.GlobalContext.Properties["pid"] = me.Id;
log4net.GlobalContext.Properties["AppName"] = me.ProcessName;
}
XmlConfigurator.ConfigureAndWatch(new FileInfo(l4nConfig));
LogManager.GetLogger("Startup").InfoFormat("Starting up, log4net configured from: {0}", l4nConfig);
}
}
}
<file_sep>/**
* Note that this file is a copy, with the listed edits, of
* helpers.h from the Microsoft Platform SDK sample, original
* copyright notice thereof follows this comment block.
*
* - Remove FieldDescriptor* functions - not used
* - Place all functions in the Microsoft::Sample namespace
*/
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Helper functions for copying parameters and packaging the buffer
// for GetSerialization.
#pragma once
#include <credentialprovider.h>
#include <ntsecapi.h>
#define SECURITY_WIN32
#include <security.h>
#include <intsafe.h>
#include <windows.h>
#include <strsafe.h>
#pragma warning(push)
#pragma warning(disable : 4995)
#include <shlwapi.h>
#pragma warning(pop)
namespace Microsoft
{
namespace Sample
{
//creates a UNICODE_STRING from a NULL-terminated string
HRESULT UnicodeStringInitWithString(
__in PWSTR pwz,
__out UNICODE_STRING* pus
);
//initializes a KERB_INTERACTIVE_UNLOCK_LOGON with weak references to the provided credentials
HRESULT KerbInteractiveUnlockLogonInit(
__in PWSTR pwzDomain,
__in PWSTR pwzUsername,
__in PWSTR pwzPassword,
__in CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus,
__out KERB_INTERACTIVE_UNLOCK_LOGON* pkiul
);
//packages the credentials into the buffer that the system expects
HRESULT KerbInteractiveUnlockLogonPack(
__in const KERB_INTERACTIVE_UNLOCK_LOGON& rkiulIn,
__deref_out_bcount(*pcb) BYTE** prgb,
__out DWORD* pcb
);
// pack the credentials into a buffer for the change password scenario
HRESULT KerbChangePasswordPack(
__in const KERB_CHANGEPASSWORD_REQUEST & kcpReqIn,
__deref_out_bcount(*pcb) BYTE** prgb,
__out DWORD* pcb
);
//get the authentication package that will be used for our logon attempt
HRESULT RetrieveNegotiateAuthPackage(
__out ULONG * pulAuthPackage
);
//encrypt a password (if necessary) and copy it; if not, just copy it
HRESULT ProtectIfNecessaryAndCopyPassword(
__in PCWSTR pwzPassword,
__in CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus,
__deref_out PWSTR* ppwzProtectedPassword
);
HRESULT KerbInteractiveUnlockLogonRepackNative(
__in_bcount(cbWow) BYTE* rgbWow,
__in DWORD cbWow,
__deref_out_bcount(*pcbNative) BYTE** prgbNative,
__out DWORD* pcbNative
);
void KerbInteractiveUnlockLogonUnpackInPlace(
__inout_bcount(cb) KERB_INTERACTIVE_UNLOCK_LOGON* pkiul,
__in DWORD cb
);
HRESULT DomainUsernameStringAlloc(
__in PCWSTR pwszDomain,
__in PCWSTR pwszUsername,
__deref_out PWSTR* ppwszDomainUsername
);
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include <assert.h>
#include "BinaryReader.h"
#if _DEBUG
#define BOUNDS_CHECK(size) if( (m_cursor + size) - m_buffer > m_bufferLength ) assert(0)
#else
#define BOUNDS_CHECK(size)
#endif
namespace pGina
{
namespace Memory
{
int BinaryReader::ReadInt32()
{
BOUNDS_CHECK(sizeof(int));
int value = 0;
memcpy(&value, m_cursor, sizeof(int));
m_cursor += sizeof(int);
return value;
}
unsigned char BinaryReader::ReadByte()
{
BOUNDS_CHECK(1);
unsigned char v = m_cursor[0];
m_cursor++;
return v;
}
std::string BinaryReader::ReadUTF8String()
{
std::string value;
int length = Decode7bitLength();
BOUNDS_CHECK(length);
// We could do some crazy hanky casting to memcpy directly into
// a std::string, but we aren't in dire need of crazy performance,
// so we'll take the hit for a spurious malloc/free
char * buffer = (char *) malloc(length + 1);
memset(buffer, 0, length + 1);
memcpy(buffer, m_cursor, length);
m_cursor += length;
value = buffer;
free(buffer);
return value;
}
std::wstring BinaryReader::ReadUnicodeString()
{
std::wstring value;
int length = Decode7bitLength();
BOUNDS_CHECK(length);
// We could do some crazy hanky casting to memcpy directly into
// a std::string, but we aren't in dire need of crazy performance,
// so we'll take the hit for a spurious malloc/free
wchar_t * buffer = (wchar_t *) malloc(length + 2);
memset(buffer, 0, length + 2);
memcpy(buffer, m_cursor, length);
m_cursor += length;
value = buffer;
free(buffer);
return value;
}
bool BinaryReader::ReadBool()
{
unsigned char v = ReadByte();
return (v != 0x00);
}
int BinaryReader::Decode7bitLength()
{
unsigned char bit = 0;
int num = 0, num2 = 0;
do
{
bit = ReadByte();
num |= (bit & 0x7f) << num2;
num2 += 7;
} while ((bit & 0x80) != 0x00);
return num;
}
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Diagnostics;
using System.Security.AccessControl;
using System.Security.Principal;
using Abstractions.Logging;
namespace Abstractions.Pipes
{
public class PipeClient : Pipe
{
public PipeClient(string name, Func<BinaryReader, BinaryWriter, bool> action)
: base(name, action)
{
}
public PipeClient(string name, Func<IDictionary<string, object>, IDictionary<string, object>> action)
: base(name, action)
{
}
public PipeClient(string name)
: base(name)
{
// user must use Start(action) flavor...
}
public void Start(IDictionary<string, object> initialMessage)
{
Start(initialMessage, Timeout.Infinite);
}
public void Start(IDictionary<string, object> initialMessage, int timeout)
{
if (StreamAction == null)
throw new ArgumentException(string.Format("You cannot use Start() having constructed the client without an action, use Start(<action>) instead."));
Start(StreamAction, initialMessage, timeout);
}
public void Start(Func<IDictionary<string, object>, IDictionary<string, object>> action, IDictionary<string, object> initialMessage, int timeout)
{
Start(
(Func<BinaryReader, BinaryWriter, bool>)((r, w) =>
{
return DefaultMessageHandler(r, w, action);
}),
initialMessage, timeout);
}
public void Start(Func<BinaryReader, BinaryWriter, bool> action, IDictionary<string, object> initialMessage, int timeout)
{
StreamAction = action;
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", Name, PipeDirection.InOut,
PipeOptions.WriteThrough, TokenImpersonationLevel.None, HandleInheritability.None))
{
for (int x = 1; x <= 5; x++)
{
try
{
pipeClient.Connect(timeout);
}
catch (Exception e)
{
if (x == 5)
{
LibraryLogging.Error("Error connecting PipeClient: {0}", e);
return;
}
Thread.Sleep(100);
}
}
// Write the initial message to get the pumps running,
// error handling to prevent a pipe error exception
try
{
using (BinaryReader reader = new BinaryReader(pipeClient, Encoding.Unicode/*, true*/))
{
using (BinaryWriter writer = new BinaryWriter(pipeClient, Encoding.Unicode/*, true*/))
{
HandlePipeConnection(reader, writer, null);
}
}
}
catch (IOException)
{
LibraryLogging.Error("Error broken pipe connection");
Start(action, initialMessage, timeout);
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace pGina.Plugin.SSHAuth
{
public partial class Configuration : Form
{
public Configuration()
{
InitializeComponent();
SettingsToUi();
}
private void SettingsToUi()
{
string Host_str = Settings.Store.Host;
string Port_str = Settings.Store.Port;
this.hostText.Text = Host_str;
this.portText.Text = Port_str;
}
private void UiToSettings()
{
Settings.Store.Host = this.hostText.Text.Trim();
Settings.Store.Port = this.portText.Text.Trim();
}
private void save_Click(object sender, EventArgs e)
{
this.UiToSettings();
this.Close();
}
private void cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void Btn_help(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/sshauth.html");
}
private void description_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label1_Click_1(object sender, EventArgs e)
{
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Security.Principal;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Threading;
using System.IO;
using log4net;
using pGina.Shared.Interfaces;
using pGina.Shared.Types;
using Abstractions;
namespace pGina.Plugin.LocalMachine
{
public class PluginImpl : IPluginAuthentication, IPluginAuthorization, IPluginAuthenticationGateway, IPluginConfiguration, IPluginEventNotifications, IPluginLogoffRequestAddTime, IPluginChangePassword
{
// Per-instance logger
private ILog m_logger = LogManager.GetLogger("LocalMachine");
private Dictionary<string, Boolean> RunningTasks = new Dictionary<string, Boolean>();
private ReaderWriterLockSlim Locker = new ReaderWriterLockSlim();
public static Boolean IsShuttingDown = false;
private object logoff_locker = new object();
#region Init-plugin
public static Guid PluginUuid
{
get { return new Guid("{12FA152D-A2E3-4C8D-9535-5DCD49DFCB6D}"); }
}
public PluginImpl()
{
using(Process me = Process.GetCurrentProcess())
{
m_logger.DebugFormat("Plugin initialized on {0} in PID: {1} Session: {2}", Environment.MachineName, me.Id, me.SessionId);
}
}
public string Name
{
get { return "Local Machine"; }
}
public string Description
{
get { return "Manages local machine accounts for authenticated users, and authenticates against the local SAM"; }
}
public string Version
{
get
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public Guid Uuid
{
get { return PluginUuid; }
}
#endregion
public void Starting() { }
public void Stopping() { }
public Boolean LogoffRequestAddTime()
{
IsShuttingDown = true;
try
{
Locker.TryEnterReadLock(-1);
if (RunningTasks.Values.Contains(true))
return true;
}
catch (Exception ex)
{
m_logger.InfoFormat("LogoffRequestAddTime() error {0}", ex.Message);
}
finally
{
Locker.ExitReadLock();
}
return false;
}
public Boolean LoginUserRequest(string username)
{
try
{
Locker.TryEnterReadLock(-1);
if (RunningTasks.Keys.Contains(username.ToLower()))
{
m_logger.InfoFormat("LoginUserRequest() logoff in process for {0}", username);
return true;
}
else
{
m_logger.InfoFormat("LoginUserRequest() {0} free to login", username);
return false;
}
}
catch (Exception ex)
{
m_logger.InfoFormat("LoginUserRequest() {0} error {1}", username, ex.Message);
}
finally
{
Locker.ExitReadLock();
}
return false;
}
private int FindString(string[] array, string filter)
{
for (int x = 0; x < array.Length; x++)
{
if (array[x].StartsWith(filter))
return x;
}
return -1;
}
public BooleanResult ChangePassword(SessionProperties properties, ChangePasswordPluginActivityInfo pluginInfo)
{
m_logger.Debug("ChangePassword()");
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
// Verify the old password
if (Abstractions.WindowsApi.pInvokes.ValidateUser(userInfo.Username, "", userInfo.oldPassword))
{
m_logger.DebugFormat("Authenticated via old password: {0}", userInfo.Username);
}
else
{
return new BooleanResult { Success = false, Message = "Current password or username is not valid." };
}
using (UserPrincipal user = LocalAccount.GetUserPrincipal(userInfo.Username))
{
if (user != null)
{
m_logger.DebugFormat("Found principal, changing password for {0}", userInfo.Username);
user.SetPassword(<PASSWORD>);
}
else
{
return new BooleanResult { Success = false, Message = "Local machine plugin internal error: directory entry not found." };
}
}
return new BooleanResult { Success = true, Message = "Local password successfully changed." };
}
public BooleanResult AuthenticatedUserGateway(SessionProperties properties)
{
// Our job, if we've been elected to do gateway, is to ensure that an
// authenticated user:
//
// 1. Has a local account
// 2. That account's password is set to the one they used to authenticate
// 3. That account is a member of all groups listed, and not a member of any others
// Is failure at #3 a total fail?
bool failIfGroupSyncFails = Settings.Store.GroupCreateFailIsFail;
// Groups everyone is added to
string[] MandatoryGroups = Settings.Store.MandatoryGroups;
// user info
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
// is this a pgina user?
Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4 userinfo4 = new Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4();
if (Abstractions.WindowsApi.pInvokes.UserGet(userInfo.Username, ref userinfo4)) //true if user exists
{
if (!userinfo4.comment.Contains("pGina created"))
{
m_logger.InfoFormat("User {0} is'nt a pGina created user. I'm not executing Gateway stage", userInfo.Username);
return new BooleanResult() { Success = true };
}
}
// Add user to all mandatory groups
if (MandatoryGroups.Length > 0)
{
foreach (string group in MandatoryGroups)
{
string group_string=group;
m_logger.DebugFormat("Is there a Group with SID/Name:{0}", group);
using (GroupPrincipal groupconf = LocalAccount.GetGroupPrincipal(group))
{
if (groupconf != null)
{
m_logger.DebugFormat("Groupname: \"{0}\"", groupconf.Name);
group_string = groupconf.Name;
}
else
{
m_logger.ErrorFormat("Group: \"{0}\" not found", group);
m_logger.Error("Failsave add user to group Users");
using (GroupPrincipal groupfail = LocalAccount.GetGroupPrincipal(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null).ToString()))
{
if (groupfail != null)
{
group_string = groupfail.Name;
}
else
{
m_logger.Debug("no BuiltinUsers. I'm out of options");
group_string = null;
}
}
}
}
if (group_string != null)
userInfo.AddGroup(new GroupInformation() { Name = group_string });
}
}
try
{
m_logger.DebugFormat("AuthenticatedUserGateway({0}) for user: {1}", properties.Id.ToString(), userInfo.Username);
LocalAccount.SyncUserInfoToLocalUser(userInfo);
using (UserPrincipal user = LocalAccount.GetUserPrincipal(userInfo.Username))
{
userInfo.SID = user.Sid;
userInfo.Description = user.Description;
}
properties.AddTrackedSingle<UserInformation>(userInfo);
}
catch (LocalAccount.GroupSyncException e)
{
if (failIfGroupSyncFails)
return new BooleanResult() { Success = false, Message = string.Format("Unable to sync users local group membership: {0}", e.RootException) };
}
catch(Exception e)
{
if (e.Message.ToLower().Contains("0x800708c5"))
{
return new BooleanResult() { Success = false, Message = string.Format("This Worstation is denying the password of {0}.\nMost likely the password does not meet complexity requirements\n\n{1}", userInfo.Username, e) };
}
return new BooleanResult() { Success = false, Message = string.Format("Unexpected error while syncing user's info: {0}", e) };
}
return new BooleanResult() { Success = true };
}
private bool HasUserAuthenticatedYet(SessionProperties properties)
{
PluginActivityInformation pluginInfo = properties.GetTrackedSingle<PluginActivityInformation>();
foreach (Guid uuid in pluginInfo.GetAuthenticationPlugins())
{
if (pluginInfo.GetAuthenticationResult(uuid).Success)
return true;
}
return false;
}
public BooleanResult AuthenticateUser(SessionProperties properties)
{
try
{
bool alwaysAuth = Settings.Store.AlwaysAuthenticate;
m_logger.DebugFormat("AuthenticateUser({0})", properties.Id.ToString());
// Get user info
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
m_logger.DebugFormat("Found username: {0}", userInfo.Username);
// Should we authenticate? Only if user has not yet authenticated, or we are not in fallback mode
if (alwaysAuth || !HasUserAuthenticatedYet(properties))
{
if (LocalAccount.UserExists(userInfo.Username))
{
// We use a pInvoke here instead of using PrincipalContext.ValidateCredentials
// due to the fact that the latter will throw an exception when the network is disconnected.
if (Abstractions.WindowsApi.pInvokes.ValidateUser(userInfo.Username, Environment.MachineName, userInfo.Password))
{
if (!Abstractions.WindowsApi.pInvokes.ValidateCredentials(userInfo.Username, userInfo.Password))
{
userInfo.PasswordEXP = true;
properties.AddTrackedSingle<UserInformation>(userInfo);
// windows itself will put on an error "pwd expired"
}
m_logger.InfoFormat("Authenticated user: {0}", userInfo.Username);
userInfo.Domain = Environment.MachineName;
m_logger.Debug("AuthenticateUser: Mirroring group membership from SAM");
LocalAccount.SyncLocalGroupsToUserInfo(userInfo);
// Return success
return new BooleanResult() { Success = true };
}
}
else
{
m_logger.InfoFormat("User {0} does not exist on this machine.", userInfo.Username);
}
}
m_logger.ErrorFormat("Failed to authenticate user: {0}", userInfo.Username);
// Note that we don't include a message. We are a last chance auth, and want previous/failed plugins
// to have the honor of explaining why.
return new BooleanResult() { Success = false, Message = null };
}
catch (Exception e)
{
m_logger.ErrorFormat("AuthenticateUser exception: {0}", e);
throw; // Allow pGina service to catch and handle exception
}
}
public BooleanResult AuthorizeUser(SessionProperties properties)
{
// Some things we always do,
bool mirrorGroups = Settings.Store.MirrorGroupsForAuthdUsers; // Should we load users groups from SAM? We always do if we auth'd only
if (mirrorGroups && !DidWeAuthThisUser(properties, false))
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
if (LocalAccount.UserExists(userInfo.Username))
{
m_logger.DebugFormat("AuthorizeUser: Mirroring users group membership from SAM");
LocalAccount.SyncLocalGroupsToUserInfo(userInfo);
}
}
// Do we need to do authorization?
if (DoesAuthzApply(properties))
{
bool limitToLocalAdmins = Settings.Store.AuthzLocalAdminsOnly;
bool limitToLocalGroups = Settings.Store.AuthzLocalGroupsOnly;
string[] limitToGroupList = Settings.Store.AuthzLocalGroups;
bool restrictionsApply = limitToLocalAdmins || limitToLocalGroups;
PluginActivityInformation pluginInfo = properties.GetTrackedSingle<PluginActivityInformation>();
if (!restrictionsApply)
{
return new BooleanResult() { Success = true };
}
else if (!pluginInfo.LoadedAuthenticationGatewayPlugins.Contains(this))
{
return new BooleanResult()
{
Success = false,
Message = string.Format("Plugin configured to authorize users based on group membership, but not in the gateway list to ensure membership is enforced, denying access")
};
}
// The user must have the local administrator group in his group list, and
// we must be in the Gateway list of plugins (as we'll be the ones ensuring
// this group membership is enforced).
if (limitToLocalAdmins)
{
SecurityIdentifier adminSid = Abstractions.Windows.Security.GetWellknownSID(WellKnownSidType.BuiltinAdministratorsSid);
string adminName = Abstractions.Windows.Security.GetNameFromSID(adminSid);
if(!ListedInGroup(adminName, adminSid, properties))
{
return new BooleanResult()
{
Success = false,
Message = string.Format("Users group list does not include the admin group ({0}), denying access", adminName)
};
}
}
// The user must have one of the groups listed (by name) in their group list
// and we must be in the Gateway list of plugins (as we'll be the ones ensuring
// this group membership is enforced).
if (limitToLocalGroups)
{
if (limitToGroupList.Length > 0)
{
foreach (string group in limitToGroupList)
{
SecurityIdentifier sid = null;
try { sid = new SecurityIdentifier(group); }
catch { }
if (ListedInGroup(group, sid, properties))
{
return new BooleanResult() { Success = true };
}
}
}
return new BooleanResult()
{
Success = false,
Message = "User is not a member of one of the required groups, denying access"
};
}
return new BooleanResult() { Success = true };
}
else
{
// We elect to not do any authorization, let the user pass for us
return new BooleanResult() { Success = true };
}
}
public void Configure()
{
Configuration dialog = new Configuration();
dialog.ShowDialog();
}
private bool ListedInGroup(string name, SecurityIdentifier sid, SessionProperties properties)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
foreach (GroupInformation group in userInfo.Groups)
{
if (group.Name == name || (sid != null && group.SID == sid))
return true;
}
return false;
}
private bool DoesAuthzApply(SessionProperties properties)
{
// Do we authorize all users?
bool authzAllUsers = Settings.Store.AuthzApplyToAllUsers;
if (authzAllUsers) return true;
// Did we auth this user?
return DidWeAuthThisUser(properties, false);
}
private bool DidWeAuthThisUser(SessionProperties properties, bool exclusiveOnly)
{
PluginActivityInformation pluginInfo = properties.GetTrackedSingle<PluginActivityInformation>();
if (!exclusiveOnly)
{
if (pluginInfo.GetAuthenticationPlugins().Contains(PluginUuid))
{
return pluginInfo.GetAuthenticationResult(PluginUuid).Success;
}
}
else
{
if (!pluginInfo.GetAuthenticationPlugins().Contains(PluginUuid))
return false;
// We must be the only one
foreach (Guid pluginId in pluginInfo.GetAuthenticationPlugins())
{
if (pluginId != PluginUuid && pluginInfo.GetAuthenticationResult(pluginId).Success) return false;
}
return true;
}
return false;
}
public void SessionChange(int SessionId, System.ServiceProcess.SessionChangeReason Reason, SessionProperties properties)
{
if (properties == null)
return;
if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogoff)
{
UserInformation uInfo = properties.GetTrackedSingle<UserInformation>();
m_logger.DebugFormat("{1} SessionChange SessionLogoff for ID:{0}", SessionId, uInfo.Username);
m_logger.InfoFormat("{3} {0} {1} {2}", uInfo.Description.Contains("pGina created"), uInfo.HasSID, properties.CREDUI, uInfo.Username);
if (uInfo.Description.Contains("pGina created") && uInfo.HasSID && !properties.CREDUI)
{
try
{
Locker.TryEnterWriteLock(-1);
RunningTasks.Add(uInfo.Username.ToLower(), true);
}
finally
{
Locker.ExitWriteLock();
}
// add this plugin into PluginActivityInformation
m_logger.DebugFormat("{1} properties.id:{0}", properties.Id, uInfo.Username);
PluginActivityInformation notification = properties.GetTrackedSingle<PluginActivityInformation>();
foreach (Guid gui in notification.GetNotificationPlugins())
{
m_logger.DebugFormat("{1} PluginActivityInformation Guid:{0}", gui, uInfo.Username);
}
m_logger.DebugFormat("{1} PluginActivityInformation add guid:{0}", PluginUuid, uInfo.Username);
notification.AddNotificationResult(PluginUuid, new BooleanResult { Message = "", Success = false });
properties.AddTrackedSingle<PluginActivityInformation>(notification);
foreach (Guid gui in notification.GetNotificationPlugins())
{
m_logger.DebugFormat("{1} PluginActivityInformation Guid:{0}", gui, uInfo.Username);
}
Thread rem_local = new Thread(() => cleanup(uInfo, SessionId, properties));
rem_local.Start();
}
else
{
m_logger.InfoFormat("{0} {1}. I'm not executing Notification stage", uInfo.Username, (properties.CREDUI) ? "has a program running in his context" : "is'nt a pGina created user");
}
}
if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogon)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
if (!userInfo.HasSID)
{
m_logger.InfoFormat("{1} SessionLogon Event denied for ID:{0}", SessionId, userInfo.Username);
return;
}
m_logger.DebugFormat("{1} SessionChange SessionLogon for ID:{0}", SessionId, userInfo.Username);
if (userInfo.Description.Contains("pGina created"))
{
if (!userInfo.Description.Contains("pgSMB"))
{
if (!String.IsNullOrEmpty(userInfo.LoginScript))
{
if (!Abstractions.WindowsApi.pInvokes.StartUserProcessInSession(SessionId, userInfo.LoginScript))
{
m_logger.ErrorFormat("Can't run application {0}", userInfo.LoginScript);
Abstractions.WindowsApi.pInvokes.SendMessageToUser(SessionId, "Can't run application", String.Format("I'm unable to run your LoginScript\n{0}", userInfo.LoginScript));
}
}
if (!Abstractions.Windows.User.QueryQuota(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation.HKEY_USERS, userInfo.SID.ToString()) && Convert.ToUInt32(userInfo.usri4_max_storage) > 0)
{
m_logger.InfoFormat("{1} no quota GPO settings for user {0}", userInfo.SID.ToString(), userInfo.Username);
if (!Abstractions.Windows.User.SetQuota(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation.HKEY_USERS, userInfo.SID.ToString(), Convert.ToUInt32(userInfo.usri4_max_storage)))
{
m_logger.InfoFormat("{1} failed to set quota GPO for user {0}", userInfo.SID.ToString(), userInfo.Username);
}
else
{
m_logger.InfoFormat("{1} done quota GPO settings for user {0}", userInfo.SID.ToString(), userInfo.Username);
try
{
Abstractions.WindowsApi.pInvokes.StartUserProcessInSession(SessionId, "proquota.exe");
}
catch (Exception ex)
{
m_logger.ErrorFormat("{2} Can't run application {0} because {1}", "proquota.exe", ex.ToString(), userInfo.Username);
}
}
}
IntPtr hToken = Abstractions.WindowsApi.pInvokes.GetUserToken(userInfo.Username, null, userInfo.Password);
if (hToken != IntPtr.Zero)
{
string uprofile = Abstractions.WindowsApi.pInvokes.GetUserProfilePath(hToken);
if (String.IsNullOrEmpty(uprofile))
{
uprofile = Abstractions.WindowsApi.pInvokes.GetUserProfileDir(hToken);
}
Abstractions.WindowsApi.pInvokes.CloseHandle(hToken);
m_logger.InfoFormat("add LocalProfilePath:[{0}]", uprofile);
// the profile realy exists there, instead of assuming it will be created or changed during a login (temp profile[win error reading profile])
userInfo.LocalProfilePath = uprofile;
properties.AddTrackedSingle<UserInformation>(userInfo);
if ((uprofile.Contains(@"\TEMP") && !userInfo.Username.StartsWith("temp", StringComparison.CurrentCultureIgnoreCase)) || Abstractions.Windows.User.IsProfileTemp(userInfo.SID.ToString()) == true)
{
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), userInfo.Username, userInfo.Password, String.Format("pGina: Windows tmp Login {0} from {1}", userInfo.Username, Environment.MachineName), "Windows was unable to load the profile");
}
}
}
if (userInfo.PasswordEXPcntr.Ticks > 0)
{
Abstractions.WindowsApi.pInvokes.SendMessageToUser(SessionId, "Password expiration warning", String.Format("Your password will expire in {0} days {1} hours {2} minutes", userInfo.PasswordEXPcntr.Days, userInfo.PasswordEXPcntr.Hours, userInfo.PasswordEXPcntr.Minutes));
}
}
else
{
m_logger.InfoFormat("{0} {1}. I'm not executing Notification stage", userInfo.Username, (userInfo.Description.Contains("pgSMB")) ? "was created by pgSMB" : "is'nt a pGina created user");
}
}
}
private void cleanup(UserInformation userInfo, int sessionID, SessionProperties properties)
{
bool scramble = Settings.Store.ScramblePasswords;
bool remove = Settings.Store.RemoveProfiles;
while (true)
{
// logoff detection is quite a problem under NT6
// a disconnectEvent is only triggered during a logoff
// but not during a shutdown/reboot
// and the SessionLogoffEvent is only saying that the user is logging of
// So, there is no event that is fired during a user-logoff/reboot/shutdown
// that indicates that the user has logged of
if (Abstractions.WindowsApi.pInvokes.IsSessionLoggedOFF(sessionID) || IsShuttingDown)
{
break;
}
else
{
Thread.Sleep(1000);
}
}
while (true)
{
// if no other notification plugin is working on this user
// if the first entry from GetNotificationPlugins is equal to this plugin UID
IEnumerable<Guid> guids = properties.GetTrackedSingle<PluginActivityInformation>().GetNotificationPlugins();
/*foreach(Guid gui in guids)
{
m_logger.DebugFormat("{1} PluginActivityInformation guid:{0}", gui, userInfo.Username);
}*/
if (guids.DefaultIfEmpty(Guid.Empty).FirstOrDefault().Equals(PluginUuid) || guids.ToList().Count == 0)
{
break;
}
Thread.Sleep(1000);
}
m_logger.DebugFormat("{0} start cleanup with Description \"{1}\"", userInfo.Username, userInfo.Description);
if (LocalAccount.UserExists(userInfo.Username))
{
lock (logoff_locker)
{
LocalAccount lo = new LocalAccount(userInfo);
if (remove)
{
m_logger.DebugFormat("{0} remove profile", userInfo.Username);
lo.RemoveUserAndProfile(userInfo.Username, sessionID);
}
else
{
m_logger.DebugFormat("{0} not removing profile", userInfo.Username);
}
if (scramble && !remove)
{
m_logger.DebugFormat("{0} scramble password", userInfo.Username);
lo.ScrambleUsersPassword(userInfo.Username);
}
else
{
m_logger.DebugFormat("{0} not scramble password", userInfo.Username);
}
m_logger.DebugFormat("{0} cleanup done", userInfo.Username);
}
}
else
{
m_logger.DebugFormat("{0} doesnt exist", userInfo.Username);
}
try
{
Locker.TryEnterWriteLock(-1);
RunningTasks.Remove(userInfo.Username.ToLower());
PluginActivityInformation notification = properties.GetTrackedSingle<PluginActivityInformation>();
notification.DelNotificationResult(PluginUuid);
m_logger.InfoFormat("{1} PluginActivityInformation del Guid:{0}", PluginUuid, userInfo.Username);
properties.AddTrackedSingle<PluginActivityInformation>(notification);
foreach (Guid guid in properties.GetTrackedSingle<PluginActivityInformation>().GetNotificationPlugins())
{
m_logger.InfoFormat("{1} PluginActivityInformation Guid:{0}", guid, userInfo.Username);
}
}
finally
{
Locker.ExitWriteLock();
}
}
}
}
<file_sep>#include "authfuncs.h"
extern "C"{
__declspec(dllexport) int auth_user(wchar_t* Username, wchar_t* Password, wchar_t* Domain, wchar_t* Ticket)
{
/*
Creates a new SEC_WINNT_AUTH_IDENTITY structure using the given user name, password, and domain. These fields are supplied by pGina, and the configuration
tool for the krb5 plugin.
*/
SEC_WINNT_AUTH_IDENTITY auth;
ZeroMemory( &auth, sizeof(auth) );
auth.Domain = reinterpret_cast<unsigned short*>( Domain );
auth.DomainLength = (unsigned long)wcslen( Domain );
auth.User = reinterpret_cast<unsigned short*>( Username );
auth.UserLength = (unsigned long)wcslen( Username );
auth.Password = reinterpret_cast<unsigned short*>( Password );
auth.PasswordLength = (unsigned long)wcslen( Password );
auth.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
char clientOutBufferData[8192];
SecBuffer clientOutBuffer;
SecBufferDesc clientOutBufferDesc;
///////////////////////////////////////////
// Get the client and server credentials //
///////////////////////////////////////////
CredHandle clientCredentials;
SECURITY_STATUS status;
/*
Acquires a HANDLE to the credentials for the given user
*/
status = ::AcquireCredentialsHandle( NULL,
L"Kerberos",
SECPKG_CRED_OUTBOUND,
NULL,
&auth,
NULL,
NULL,
&clientCredentials,
NULL );
if(status != SEC_E_OK)
return status;
//////////////////////////////////////
// Initialize the security contexts //
//////////////////////////////////////
CtxtHandle clientContext = {};
unsigned long clientContextAttr = 0;
/////////////////////////////
// Clear the client buffer //
/////////////////////////////
clientOutBuffer.BufferType = SECBUFFER_TOKEN;
clientOutBuffer.cbBuffer = sizeof clientOutBufferData;
clientOutBuffer.pvBuffer = clientOutBufferData;
clientOutBufferDesc.cBuffers = 1;
clientOutBufferDesc.pBuffers = &clientOutBuffer;
clientOutBufferDesc.ulVersion = SECBUFFER_VERSION;
///////////////////////////////////
// Initialize the client context //
///////////////////////////////////
status = InitializeSecurityContext( &clientCredentials,
NULL,
Ticket,// the (service/domain) spn target that will authenticate this user "krbtgt/ad.utah.edu",
0,
0,
SECURITY_NATIVE_DREP,
NULL,
0,
&clientContext,
&clientOutBufferDesc,
&clientContextAttr,
NULL );
return status;
}
}<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <Windows.h>
#include <string>
#include <vector>
#include "Winlogon.h"
namespace pGina
{
namespace GINA
{
// Simple base class that 'ui' dialogs can inherit from, thanks to <NAME> and his
// excellent GINA series for this idea - basically we just proxy all DialogProcs through
// a static proc with a class ptr as user data. This lets each dialog have its own
// class and handler, without the added work of individual WlxDialogBox() calls all over
// the place. Instead, just YourDialogBox->ShowDialog().
class DialogBase
{
public:
DialogBase(WinlogonInterface * iface, int dialogId);
int ShowDialog();
protected:
virtual void DialogInit() = 0; // WM_INITDIALOG
virtual bool Command(int itemId) = 0; // WM_COMMAND
virtual bool Timer(int timerId) = 0; // WM_TIMER
virtual void Destroy() {} // WM_DESTROY
virtual INT_PTR DialogProcImpl(UINT msg, WPARAM wparam, LPARAM lparam) = 0;
// Helpers that subclasses can use to center, get/set data etc
void CenterWindow();
HWND GetItem(int itemId);
void SetCaption(const wchar_t *caption);
void SetItemText(int itemId, const wchar_t *text);
void SetItemText(int itemId, std::wstring const& text) { SetItemText(itemId, text.c_str()); }
std::wstring GetItemText(int itemId);
void EnableItem(int itemId);
void DisableItem(int itemId);
void HideItem(int itemId);
void ShowItem(int itemId);
void CheckState(int itemId, bool checked);
bool CheckState(int itemId);
void SetFocusItem(int itemId);
void SetItemBitmap(int itemId, HBITMAP bitmap);
void FinishWithResult(INT_PTR result) { EndDialog(m_hwnd, result); }
int StartTimer(unsigned int period);
void StopTimer(int timerId);
private:
static INT_PTR CALLBACK DialogProcInternal(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);
void Hwnd(HWND v) { m_hwnd = v; }
void InternalDestroy();
protected:
WinlogonInterface * m_winlogon;
int m_dialogId;
HINSTANCE m_instance;
HWND m_hwnd;
int m_nextTimer;
};
}
}<file_sep>#define SECURITY_WIN32 1
#include <Windows.h>
#include <Sspi.h>
<file_sep>/*
Copyright (c) 2018, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
using System.Net;
using System.Net.Security;
using System.Security.Principal;
using System.ComponentModel;
using Microsoft.Win32;
using System.Security.AccessControl;
using Abstractions.Logging;
namespace Abstractions.WindowsApi
{
public static class pInvokes
{
internal class SafeNativeMethods
{
#region Structs/Enums
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct CREDUI_INFO
{
public int cbSize;
public IntPtr hwndParent;
public string pszMessageText;
public string pszCaptionText;
public IntPtr hbmBanner;
}
public enum PromptForWindowsCredentialsFlags
{
/// <summary>
/// The caller is requesting that the credential provider return the user name and password in plain text.
/// This value cannot be combined with SECURE_PROMPT.
/// </summary>
CREDUIWIN_GENERIC = 0x1,
/// <summary>
/// The Save check box is displayed in the dialog box.
/// </summary>
CREDUIWIN_CHECKBOX = 0x2,
/// <summary>
/// Only credential providers that support the authentication package specified by the authPackage parameter should be enumerated.
/// This value cannot be combined with CREDUIWIN_IN_CRED_ONLY.
/// </summary>
CREDUIWIN_AUTHPACKAGE_ONLY = 0x10,
/// <summary>
/// Only the credentials specified by the InAuthBuffer parameter for the authentication package specified by the authPackage parameter should be enumerated.
/// If this flag is set, and the InAuthBuffer parameter is NULL, the function fails.
/// This value cannot be combined with CREDUIWIN_AUTHPACKAGE_ONLY.
/// </summary>
CREDUIWIN_IN_CRED_ONLY = 0x20,
/// <summary>
/// Credential providers should enumerate only administrators. This value is intended for User Account Control (UAC) purposes only. We recommend that external callers not set this flag.
/// </summary>
CREDUIWIN_ENUMERATE_ADMINS = 0x100,
/// <summary>
/// Only the incoming credentials for the authentication package specified by the authPackage parameter should be enumerated.
/// </summary>
CREDUIWIN_ENUMERATE_CURRENT_USER = 0x200,
/// <summary>
/// The credential dialog box should be displayed on the secure desktop. This value cannot be combined with CREDUIWIN_GENERIC.
/// Windows Vista: This value is not supported until Windows Vista with SP1.
/// </summary>
CREDUIWIN_SECURE_PROMPT = 0x1000,
/// <summary>
/// The credential provider should align the credential BLOB pointed to by the refOutAuthBuffer parameter to a 32-bit boundary, even if the provider is running on a 64-bit system.
/// </summary>
CREDUIWIN_PACK_32_WOW = 0x10000000,
}
public enum ResourceScope
{
RESOURCE_CONNECTED = 1,
RESOURCE_GLOBALNET,
RESOURCE_REMEMBERED,
RESOURCE_RECENT,
RESOURCE_CONTEXT
}
public enum ResourceType
{
RESOURCETYPE_ANY,
RESOURCETYPE_DISK,
RESOURCETYPE_PRINT,
RESOURCETYPE_RESERVED
}
public enum ResourceUsage
{
RESOURCEUSAGE_CONNECTABLE = 0x00000001,
RESOURCEUSAGE_CONTAINER = 0x00000002,
RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004,
RESOURCEUSAGE_SIBLING = 0x00000008,
RESOURCEUSAGE_ATTACHED = 0x00000010,
RESOURCEUSAGE_ALL = (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED),
}
public enum ResourceDisplayType
{
RESOURCEDISPLAYTYPE_GENERIC,
RESOURCEDISPLAYTYPE_DOMAIN,
RESOURCEDISPLAYTYPE_SERVER,
RESOURCEDISPLAYTYPE_SHARE,
RESOURCEDISPLAYTYPE_FILE,
RESOURCEDISPLAYTYPE_GROUP,
RESOURCEDISPLAYTYPE_NETWORK,
RESOURCEDISPLAYTYPE_ROOT,
RESOURCEDISPLAYTYPE_SHAREADMIN,
RESOURCEDISPLAYTYPE_DIRECTORY,
RESOURCEDISPLAYTYPE_TREE,
RESOURCEDISPLAYTYPE_NDSCONTAINER
}
[StructLayout(LayoutKind.Sequential)]
internal class NETRESOURCE
{
public ResourceScope dwScope = 0; // Ignored by WNetAddConnection2
public ResourceType dwType = ResourceType.RESOURCETYPE_DISK;
public ResourceDisplayType dwDisplayType = 0; // Ignored by WNetAddConnection2
public ResourceUsage dwUsage = 0; // Ignored by WNetAddConnection2
public string lpLocalName = null;
public string lpRemoteName = null;
public string lpComment = ""; // Ignored by WNetAddConnection2
public string lpProvider = null;
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
public enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
[Flags]
public enum ACCESS_MASK : uint
{
DELETE = 0x00010000,
READ_CONTROL = 0x00020000,
WRITE_DAC = 0x00040000,
WRITE_OWNER = 0x00080000,
SYNCHRONIZE = 0x00100000,
STANDARD_RIGHTS_REQUIRED = 0x000f0000,
STANDARD_RIGHTS_READ = 0x00020000,
STANDARD_RIGHTS_WRITE = 0x00020000,
STANDARD_RIGHTS_EXECUTE = 0x00020000,
STANDARD_RIGHTS_ALL = 0x001f0000,
SPECIFIC_RIGHTS_ALL = 0x0000ffff,
ACCESS_SYSTEM_SECURITY = 0x01000000,
MAXIMUM_ALLOWED = 0x02000000,
GENERIC_READ = 0x80000000,
GENERIC_WRITE = 0x40000000,
GENERIC_EXECUTE = 0x20000000,
GENERIC_ALL = 0x10000000,
DESKTOP_READOBJECTS = 0x00000001,
DESKTOP_CREATEWINDOW = 0x00000002,
DESKTOP_CREATEMENU = 0x00000004,
DESKTOP_HOOKCONTROL = 0x00000008,
DESKTOP_JOURNALRECORD = 0x00000010,
DESKTOP_JOURNALPLAYBACK = 0x00000020,
DESKTOP_ENUMERATE = 0x00000040,
DESKTOP_WRITEOBJECTS = 0x00000080,
DESKTOP_SWITCHDESKTOP = 0x00000100,
WINSTA_ENUMDESKTOPS = 0x00000001,
WINSTA_READATTRIBUTES = 0x00000002,
WINSTA_ACCESSCLIPBOARD = 0x00000004,
WINSTA_CREATEDESKTOP = 0x00000008,
WINSTA_WRITEATTRIBUTES = 0x00000010,
WINSTA_ACCESSGLOBALATOMS = 0x00000020,
WINSTA_EXITWINDOWS = 0x00000040,
WINSTA_ENUMERATE = 0x00000100,
WINSTA_READSCREEN = 0x00000200,
WINSTA_ALL_ACCESS = 0x0000037f
}
public enum TOKEN_TYPE
{
TokenPrimary = 1,
TokenImpersonation
}
public enum LogonFlags
{
LOGON_WITH_PROFILE = 1,
LOGON_NETCREDENTIALS_ONLY = 2,
}
public enum TOKEN_INFORMATION_CLASS : int
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
MaxTokenInfoClass
};
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public Int32 cb;
public String lpReserved;
public String lpDesktop;
public String lpTitle;
public UInt32 dwX;
public UInt32 dwY;
public UInt32 dwXSize;
public UInt32 dwYSize;
public UInt32 dwXCountChars;
public UInt32 dwYCountChars;
public UInt32 dwFillAttribute;
public UInt32 dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
};
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public UInt32 dwProcessId;
public UInt32 dwThreadId;
};
[StructLayout(LayoutKind.Sequential)]
public struct WTS_SESSION_INFO
{
public Int32 SessionID;
[MarshalAs(UnmanagedType.LPStr)]
public String pWinStationName;
public WTS_CONNECTSTATE_CLASS State;
}
public enum WTS_INFO_CLASS
{
WTSInitialProgram,
WTSApplicationName,
WTSWorkingDirectory,
WTSOEMId,
WTSSessionId,
WTSUserName,
WTSWinStationName,
WTSDomainName,
WTSConnectState,
WTSClientBuildNumber,
WTSClientName,
WTSClientDirectory,
WTSClientProductId,
WTSClientHardwareId,
WTSClientAddress,
WTSClientDisplay,
WTSClientProtocolType
}
public enum WTS_CONNECTSTATE_CLASS
{
WTSActive,
WTSConnected,
WTSConnectQuery,
WTSShadow,
WTSDisconnected,
WTSIdle,
WTSListen,
WTSReset,
WTSDown,
WTSInit
}
public static IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;
/// <summary>
/// Used with LogonUser
/// </summary>
public enum LogonType
{
/// <summary>
/// This logon type is intended for users who will be interactively using the computer, such as a user being logged on
/// by a terminal server, remote shell, or similar process.
/// This logon type has the additional expense of caching logon information for disconnected operations;
/// therefore, it is inappropriate for some client/server applications,
/// such as a mail server.
/// </summary>
LOGON32_LOGON_INTERACTIVE = 2,
/// <summary>
/// This logon type is intended for high performance servers to authenticate plaintext passwords.
/// The LogonUser function does not cache credentials for this logon type.
/// </summary>
LOGON32_LOGON_NETWORK = 3,
/// <summary>
/// This logon type is intended for batch servers, where processes may be executing on behalf of a user without
/// their direct intervention. This type is also for higher performance servers that process many plaintext
/// authentication attempts at a time, such as mail or Web servers.
/// The LogonUser function does not cache credentials for this logon type.
/// </summary>
LOGON32_LOGON_BATCH = 4,
/// <summary>
/// Indicates a service-type logon. The account provided must have the service privilege enabled.
/// </summary>
LOGON32_LOGON_SERVICE = 5,
/// <summary>
/// This logon type is for GINA DLLs that log on users who will be interactively using the computer.
/// This logon type can generate a unique audit record that shows when the workstation was unlocked.
/// </summary>
LOGON32_LOGON_UNLOCK = 7,
/// <summary>
/// This logon type preserves the name and password in the authentication package, which allows the server to make
/// connections to other network servers while impersonating the client. A server can accept plaintext credentials
/// from a client, call LogonUser, verify that the user can access the system across the network, and still
/// communicate with other servers.
/// NOTE: Windows NT: This value is not supported.
/// </summary>
LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
/// <summary>
/// This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
/// The new logon session has the same local identifier but uses different credentials for other network connections.
/// NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
/// NOTE: Windows NT: This value is not supported.
/// </summary>
LOGON32_LOGON_NEW_CREDENTIALS = 9,
}
/// <summary>
/// Used with LogonUser
/// </summary>
public enum LogonProvider
{
/// <summary>
/// Use the standard logon provider for the system.
/// The default security provider is negotiate, unless you pass NULL for the domain name and the user name
/// is not in UPN format. In this case, the default provider is NTLM.
/// NOTE: Windows 2000/NT: The default security provider is NTLM.
/// </summary>
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_PROVIDER_WINNT35 = 1,
LOGON32_PROVIDER_WINNT40 = 2,
LOGON32_PROVIDER_WINNT50 = 3,
LOGON32_PROVIDER_VIRTUAL = 4
}
#endregion
#region credui.dll
[DllImport("credui.dll", CharSet = CharSet.Auto)]
public static extern int CredUIPromptForWindowsCredentials(ref CREDUI_INFO uiInfo, int authError, ref uint authPackage,
IntPtr InAuthBuffer, uint InAuthBufferSize,
out IntPtr refOutAuthBuffer, out uint refOutAuthBufferSize,
ref bool fSave, PromptForWindowsCredentialsFlags flags);
[DllImport("credui.dll", CharSet = CharSet.Auto)]
public static extern bool CredUnPackAuthenticationBuffer(int dwFlags, IntPtr pAuthBuffer, uint cbAuthBuffer,
StringBuilder pszUserName, ref int pcchMaxUserName,
StringBuilder pszDomainName, ref int pcchMaxDomainname,
StringBuilder pszPassword, ref int pcchMaxPassword);
#endregion
#region ole32.dll
[DllImport("ole32.dll")]
public static extern void CoTaskMemFree(IntPtr ptr);
#endregion
#region mpr.dll
[DllImport("mpr.dll")]
public static extern int WNetAddConnection2(NETRESOURCE netResource,
string password, string username, int flags);
[DllImport("mpr.dll")]
public static extern int WNetCancelConnection2(string name, int flags,
bool force);
#endregion
#region wtsapi32.dll
[DllImport("wtsapi32.dll", SetLastError = true)]
public static extern bool WTSQueryUserToken(int sessionId, out IntPtr Token);
[DllImport("wtsapi32.dll")]
public static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] String pServerName);
[DllImport("wtsapi32.dll")]
public static extern void WTSCloseServer(IntPtr hServer);
[DllImport("wtsapi32.dll")]
public static extern int WTSEnumerateSessions(IntPtr hServer,
[MarshalAs(UnmanagedType.U4)] int Reserved,
[MarshalAs(UnmanagedType.U4)] int Version,
ref IntPtr ppSessionInfo,
[MarshalAs(UnmanagedType.U4)] ref int pCount);
[DllImport("wtsapi32.dll")]
public static extern void WTSFreeMemory(IntPtr pMemory);
[DllImport("Wtsapi32.dll")]
public static extern bool WTSQuerySessionInformation(System.IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out System.IntPtr ppBuffer, out uint pBytesReturned);
[DllImport("wtsapi32.dll")]
public static extern bool WTSLogoffSession(IntPtr hServer, int sessionId, bool bWait);
#endregion
#region userenv.dll
[DllImport("userenv.dll")]
public static extern bool DeleteProfile(string sidString, string path, string machine);
#endregion
#region kernel32.dll
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.U4)]
public static extern int WTSGetActiveConsoleSessionId();
#endregion
#region advapi32.dll
[DllImport("advapi32.dll", SetLastError = true)]
public extern static bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess, IntPtr tokenAttr,
SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType, out IntPtr phNewToken);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool OpenProcessToken(IntPtr ProcessHandle,
UInt32 DesiredAccess, out IntPtr TokenHandle);
// TokenInformation is really an IntPtr, but we only ever call this with SessionId, so we ref the int directly
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool SetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass,
ref int TokenInformation, int TokenInformationLength);
[DllImport("userenv.dll", SetLastError = true)]
public static extern Boolean CreateEnvironmentBlock(ref IntPtr lpEnvironment, IntPtr hToken, Boolean bInherit);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool CreateProcessAsUser(IntPtr hToken, string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, CreationFlags dwCreationFlags, IntPtr lpEnvironment,
string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
string lpszUsername, string domain, string password,
int dwLogonType, int dwLogonProvider,
out IntPtr phToken);
#endregion
#region ntdll.dll
[DllImport("ntdll.dll", SetLastError = true)]
internal static extern int RtlGetVersion(ref structenums.OSVERSIONINFOW version);
#endregion
#region Netapi32.dll
[DllImport("Netapi32.dll", SetLastError = true)]
internal static extern int NetUserAdd([MarshalAs(UnmanagedType.LPWStr)]string servername, UInt32 level, ref SafeNativeMethods.USER_INFO_1 buf, out Int32 parm_err);
[DllImport("Netapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
internal extern static int NetUserGetInfo([MarshalAs(UnmanagedType.LPWStr)] string ServerName, [MarshalAs(UnmanagedType.LPWStr)] string UserName, int level, out IntPtr BufPtr);
[DllImport("netapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern int NetUserSetInfo([MarshalAs(UnmanagedType.LPWStr)] string servername, string username, int level, ref structenums.USER_INFO_4 buf, out Int32 parm_err);
[DllImport("Netapi32.dll", SetLastError = true)]
internal static extern int NetApiBufferFree(IntPtr Buffer);
[DllImport("Netapi32.dll", SetLastError = true)]
internal static extern int NetUserDel([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string username);
[DllImport("Netapi32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
internal static extern int NetUserChangePassword([MarshalAs(UnmanagedType.LPWStr)] string domainname, [MarshalAs(UnmanagedType.LPWStr)] string username, [MarshalAs(UnmanagedType.LPWStr)] string oldpassword, [MarshalAs(UnmanagedType.LPWStr)] string newpassword);
[DllImport("Netapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern int DsGetDcName([MarshalAs(UnmanagedType.LPTStr)] string ComputerName, [MarshalAs(UnmanagedType.LPTStr)] string DomainName, [In] int DomainGuid, [MarshalAs(UnmanagedType.LPTStr)] string SiteName, [MarshalAs(UnmanagedType.U4)] DSGETDCNAME_FLAGS flags, out IntPtr pDOMAIN_CONTROLLER_INFO);
[DllImport("netapi32.dll", SetLastError = true)]
internal static extern int NetWkstaGetInfo(string servername, int level, out IntPtr bufptr);
#endregion
#region wtsapi32.dll
[DllImport("wtsapi32.dll", SetLastError = true)]
internal static extern bool WTSSendMessage(IntPtr hServer, [MarshalAs(UnmanagedType.I4)] int SessionId, String pTitle, [MarshalAs(UnmanagedType.U4)] int TitleLength, String pMessage, [MarshalAs(UnmanagedType.U4)] int MessageLength, [MarshalAs(UnmanagedType.U4)] int Style, [MarshalAs(UnmanagedType.U4)] int Timeout, [MarshalAs(UnmanagedType.U4)] out int pResponse, bool bWait);
#endregion
[DllImport("Mpr.dll", SetLastError = true)]
internal static extern int WNetUseConnection(IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID, int dwFlags, string lpAccessName, string lpBufferSize, string lpResult);
#region kernel32.dll
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes);
#endregion
#region kernel32.dll
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetCurrentProcess();
#endregion
#region advapi32.dll
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disableAllPrivileges, ref TokPriv1Luid newState, int len, IntPtr prev, IntPtr relen);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern int RegLoadKey(UInt32 hKey, String lpSubKey, String lpFile);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern int RegUnLoadKey(UInt32 hKey, string lpSubKey);
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
internal static extern uint CreateProfile([MarshalAs(UnmanagedType.LPWStr)] String pszUserSid, [MarshalAs(UnmanagedType.LPWStr)] String pszUserName, [Out, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pszProfilePath, uint cchProfilePath);
[DllImport("userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool GetUserProfileDirectory(IntPtr hToken, StringBuilder lpProfileDir, [MarshalAs(UnmanagedType.U4)] ref uint lpcchSize);
[DllImport("shell32.dll", SetLastError = true)]
internal static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, uint dwFlags, [Out] StringBuilder pszPath);
[DllImport("Advapi32.dll", SetLastError = true)]
internal static extern int RegCopyTree(UIntPtr hsKey, string lpSubKey, UIntPtr hdKey);
[DllImport("Advapi32.dll", SetLastError = true)]
internal static extern int RegCloseKey(UIntPtr hKey);
[DllImport("Advapi32.dll", SetLastError = true)]
internal static extern int RegCreateKey(structenums.baseKey hKey, [MarshalAs(UnmanagedType.LPStr)]string subKey, ref UIntPtr phkResult);
[DllImport("Advapi32.dll", SetLastError = true)]
internal static extern int RegOpenKey(structenums.baseKey hKey, [MarshalAs(UnmanagedType.LPStr)]string subKey, ref UIntPtr phkResult);
[DllImport("Advapi32.dll", SetLastError = true)]
internal static extern int RegDeleteTree(structenums.baseKey hKey, [MarshalAs(UnmanagedType.LPStr)]string subKey);
#endregion
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern bool GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, int TokenInformationLength, out int ReturnLength);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool LookupAccountSid(string lpSystemName, IntPtr Sid, StringBuilder lpName, ref uint cchName, StringBuilder ReferencedDomainName, ref uint cchReferencedDomainName, out SID_NAME_USE peUse);
[DllImport("wtsapi32.dll", SetLastError = true)]
internal static extern bool WTSRegisterSessionNotification(IntPtr hWnd, [MarshalAs(UnmanagedType.U4)] int dwFlags);
[DllImport("WtsApi32.dll", SetLastError = true)]
internal static extern bool WTSUnRegisterSessionNotification(IntPtr hWnd);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern bool SetServiceStatus(IntPtr hServiceStatus, ref structenums.SERVICE_STATUS lpServiceStatus);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ChangeServiceConfig2(SafeHandle hService, int dwInfoLevel, IntPtr lpInfo);
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool LoadUserProfile(IntPtr hToken, ref PROFILEINFO lpProfileInfo);
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool UnloadUserProfile(IntPtr hToken, IntPtr hProfile);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern Int32 WaitForSingleObject(IntPtr Handle, Int32 Wait);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct USER_INFO_1052
{
internal IntPtr profile;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct USER_INFO_1
{
internal string usri1_name;
internal string usri1_password;
internal int usri1_password_age;
internal pInvokes.structenums.UserPrivileges usri1_priv;
internal string usri1_home_dir;
internal string comment;
internal int usri1_flags;
internal string usri1_script_path;
}
internal struct Connect
{
internal const int CONNECT_INTERACTIVE = 0x00000008;
internal const int CONNECT_PROMPT = 0x00000010;
internal const int CONNECT_REDIRECT = 0x00000080;
internal const int CONNECT_UPDATE_PROFILE = 0x00000001;
internal const int CONNECT_COMMANDLINE = 0x00000800;
internal const int CONNECT_CMD_SAVECRED = 0x00001000;
internal const int CONNECT_LOCALDRIVE = 0x00000100;
}
internal struct TokenAccessRights
{
internal const string SE_RESTORE_NAME = "SeRestorePrivilege";
internal const string SE_BACKUP_NAME = "SeBackupPrivilege";
internal const UInt32 SE_PRIVILEGE_ENABLED = 0x00000002;
internal const UInt32 STANDARD_RIGHTS_REQUIRED = 0x000F0000;
internal const UInt32 STANDARD_RIGHTS_READ = 0x00020000;
internal const UInt32 TOKEN_ASSIGN_PRIMARY = 0x0001;
internal const UInt32 TOKEN_DUPLICATE = 0x0002;
internal const UInt32 TOKEN_IMPERSONATE = 0x0004;
internal const UInt32 TOKEN_QUERY = 0x0008;
internal const UInt32 TOKEN_QUERY_SOURCE = 0x0010;
internal const UInt32 TOKEN_ADJUST_PRIVILEGES = 0x0020;
internal const UInt32 TOKEN_ADJUST_GROUPS = 0x0040;
internal const UInt32 TOKEN_ADJUST_DEFAULT = 0x0080;
internal const UInt32 TOKEN_ADJUST_SESSIONID = 0x0100;
internal const UInt32 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);
internal const UInt32 TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID);
}
[StructLayout(LayoutKind.Sequential)]
internal struct LUID
{
internal uint LowPart;
internal int HighPart;
}
[StructLayout(LayoutKind.Sequential)]
internal struct LUID_AND_ATTRIBUTES
{
internal LUID pLuid;
internal UInt32 Attributes;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid
{
internal int Count;
internal LUID Luid;
internal UInt32 Attr;
}
internal struct TOKEN_USER
{
#pragma warning disable 0649
internal SID_AND_ATTRIBUTES User;
#pragma warning restore 0649
}
[StructLayout(LayoutKind.Sequential)]
internal struct SID_AND_ATTRIBUTES
{
internal IntPtr Sid;
internal int Attributes;
}
internal enum SID_NAME_USE
{
SidTypeUser = 1,
SidTypeGroup,
SidTypeDomain,
SidTypeAlias,
SidTypeWellKnownGroup,
SidTypeDeletedAccount,
SidTypeInvalid,
SidTypeUnknown,
SidTypeComputer
}
internal enum State
{
SERVICE_STOPPED = 0x00000001,
SERVICE_START_PENDING = 0x00000002,
SERVICE_STOP_PENDING = 0x00000003,
SERVICE_RUNNING = 0x00000004,
SERVICE_CONTINUE_PENDING = 0x00000005,
SERVICE_PAUSE_PENDING = 0x00000006,
SERVICE_PAUSED = 0x00000007,
}
internal enum INFO_LEVEL : uint
{
SERVICE_CONFIG_DESCRIPTION = 0x00000001,
SERVICE_CONFIG_FAILURE_ACTIONS = 0x00000002,
SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 0x00000003,
SERVICE_CONFIG_FAILURE_ACTIONS_FLAG = 0x00000004,
SERVICE_CONFIG_SERVICE_SID_INFO = 0x00000005,
SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO = 0x00000006,
SERVICE_CONFIG_PRESHUTDOWN_INFO = 0x00000007,
SERVICE_CONFIG_TRIGGER_INFO = 0x00000008,
SERVICE_CONFIG_PREFERRED_NODE = 0x00000009
}
[StructLayout(LayoutKind.Sequential)]
internal struct SERVICE_PRESHUTDOWN_INFO
{
internal UInt32 dwPreshutdownTimeout;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct DOMAIN_CONTROLLER_INFO
{
[MarshalAs(UnmanagedType.LPTStr)]
public string DomainControllerName;
[MarshalAs(UnmanagedType.LPTStr)]
public string DomainControllerAddress;
public uint DomainControllerAddressType;
public Guid DomainGuid;
[MarshalAs(UnmanagedType.LPTStr)]
public string DomainName;
[MarshalAs(UnmanagedType.LPTStr)]
public string DnsForestName;
public uint Flags;
[MarshalAs(UnmanagedType.LPTStr)]
public string DcSiteName;
[MarshalAs(UnmanagedType.LPTStr)]
public string ClientSiteName;
}
[Flags]
internal enum DSGETDCNAME_FLAGS : uint
{
DS_FORCE_REDISCOVERY = 0x00000001,
DS_DIRECTORY_SERVICE_REQUIRED = 0x00000010,
DS_DIRECTORY_SERVICE_PREFERRED = 0x00000020,
DS_GC_SERVER_REQUIRED = 0x00000040,
DS_PDC_REQUIRED = 0x00000080,
DS_BACKGROUND_ONLY = 0x00000100,
DS_IP_REQUIRED = 0x00000200,
DS_KDC_REQUIRED = 0x00000400,
DS_TIMESERV_REQUIRED = 0x00000800,
DS_WRITABLE_REQUIRED = 0x00001000,
DS_GOOD_TIMESERV_PREFERRED = 0x00002000,
DS_AVOID_SELF = 0x00004000,
DS_ONLY_LDAP_NEEDED = 0x00008000,
DS_IS_FLAT_NAME = 0x00010000,
DS_IS_DNS_NAME = 0x00020000,
DS_RETURN_DNS_NAME = 0x40000000,
DS_RETURN_FLAT_NAME = 0x80000000
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct WKSTA_INFO_100
{
public int platform_id;
public string computer_name;
public string lan_group;
public int ver_major;
public int ver_minor;
}
[Flags]
internal enum CreationFlags
{
CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
CREATE_DEFAULT_ERROR_MODE = 0x04000000,
CREATE_NEW_CONSOLE = 0x00000010,
CREATE_NEW_PROCESS_GROUP = 0x00000200,
CREATE_NO_WINDOW = 0x08000000,
CREATE_PROTECTED_PROCESS = 0x00040000,
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
CREATE_SEPARATE_WOW_VDM = 0x00000800,
CREATE_SHARED_WOW_VDM = 0x00001000,
CREATE_SUSPENDED = 0x00000004,
CREATE_UNICODE_ENVIRONMENT = 0x00000400,
DEBUG_ONLY_THIS_PROCESS = 0x00000002,
DEBUG_PROCESS = 0x00000001,
DETACHED_PROCESS = 0x00000008,
EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
INHERIT_PARENT_AFFINITY = 0x00010000,
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct STARTUPINFOEX
{
public STARTUPINFO StartupInfo;
public IntPtr lpAttributeList;
}
[StructLayout(LayoutKind.Sequential)]
internal struct PROFILEINFO
{
internal int dwSize;
internal int dwFlags;
[MarshalAs(UnmanagedType.LPTStr)]
internal String lpUserName;
[MarshalAs(UnmanagedType.LPTStr)]
internal String lpProfilePath;
[MarshalAs(UnmanagedType.LPTStr)]
internal String lpDefaultPath;
[MarshalAs(UnmanagedType.LPTStr)]
internal String lpServerName;
[MarshalAs(UnmanagedType.LPTStr)]
internal String lpPolicyPath;
internal IntPtr hProfile;
}
internal static Boolean RegistryLoadPrivilegeSet = false;
}
public class structenums
{
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
public struct OSVERSIONINFOW
{
[MarshalAs(UnmanagedType.U4)]
internal int dwOSVersionInfoSize;
[MarshalAs(UnmanagedType.U4)]
public int dwMajorVersion;
[MarshalAs(UnmanagedType.U4)]
public int dwMinorVersion;
[MarshalAs(UnmanagedType.U4)]
public int dwBuildNumber;
[MarshalAs(UnmanagedType.U4)]
public int dwPlatformId;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
public char[] szCSDVersion;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct USER_INFO_4
{
public string name;
public string password;
public int password_age;
public UserPrivileges priv;
public string home_dir;
public string comment;
public UserFlags flags;
public string script_path;
public AuthFlags auth_flags;
public string full_name;
public string usr_comment;
public string parms;
public string workstations;
public int last_logon;
public int last_logoff;
public int acct_expires;
public int max_storage;
public int units_per_week;
public IntPtr logon_hours; // This is a PBYTE
public int bad_pw_count;
public int num_logons;
public string logon_server;
public int country_code;
public int code_page;
public IntPtr user_sid; // This is a PSID
public int primary_group_id;
public string profile;
public string home_dir_drive;
public int password_expired;
}
public enum UserPrivileges
{
USER_PRIV_GUEST = 0x0,
USER_PRIV_USER = 0x1,
USER_PRIV_ADMIN = 0x2,
}
public enum UserFlags
{
UF_SCRIPT = 0x0001,
UF_ACCOUNTDISABLE = 0x0002,
UF_HOMEDIR_REQUIRED = 0x0008,
UF_LOCKOUT = 0x0010,
UF_PASSWD_NOTREQD = 0x0020,
UF_PASSWD_CANT_CHANGE = 0x0040,
UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0x0080,
UF_TEMP_DUPLICATE_ACCOUNT = 0x0100,
UF_NORMAL_ACCOUNT = 0x0200,
UF_INTERDOMAIN_TRUST_ACCOUNT = 0x0800,
UF_WORKSTATION_TRUST_ACCOUNT = 0x1000,
UF_SERVER_TRUST_ACCOUNT = 0x2000,
UF_DONT_EXPIRE_PASSWD = 0x10000,
UF_MNS_LOGON_ACCOUNT = 0x20000,
UF_SMARTCARD_REQUIRED = 0x40000,
UF_TRUSTED_FOR_DELEGATION = 0x80000,
UF_NOT_DELEGATED = 0x100000,
UF_USE_DES_KEY_ONLY = 0x200000,
UF_DONT_REQUIRE_PREAUTH = 0x400000,
UF_PASSWORD_EXPIRED = 0x800000,
UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0x1000000,
UF_PARTIAL_SECRETS_ACCOUNT = 0x04000000,
}
public enum AuthFlags
{
AF_OP_PRINT = 0x1,
AF_OP_COMM = 0x2,
AF_OP_SERVER = 0x4,
AF_OP_ACCOUNTS = 0x8,
}
public enum RegistryLocation
{
HKEY_CLASSES_ROOT,
HKEY_CURRENT_USER,
HKEY_LOCAL_MACHINE,
HKEY_USERS,
HKEY_CURRENT_CONFIG
}
public enum baseKey : uint
{
HKEY_CLASSES_ROOT = 0x80000000,
HKEY_CURRENT_USER = 0x80000001,
HKEY_LOCAL_MACHINE = 0x80000002,
HKEY_USERS = 0x80000003,
HKEY_CURRENT_CONFIG = 0x80000005
}
public enum PBT
{
// Vista++ && XP++
APMPOWERSTATUSCHANGE = 0xA, //Power status has changed.
APMRESUMEAUTOMATIC = 0x12, //Operation is resuming automatically from a low-power state. This message is sent every time the system resumes.
APMRESUMESUSPEND = 0x7, //Operation is resuming from a low-power state. This message is sent after PBT_APMRESUMEAUTOMATIC if the resume is triggered by user input, such as pressing a key.
APMSUSPEND = 0x4, //System is suspending operation.
POWERSETTINGCHANGE = 0x8013, //A power setting change event has been received.
// XP++ only
APMBATTERYLOW = 0x9, //Battery power is low. In Windows Server 2008 and Windows Vista, use PBT_APMPOWERSTATUSCHANGE instead.
APMOEMEVENT = 0xB, //OEM-defined event occurred. In Windows Server 2008 and Windows Vista, this event is not available because these operating systems support only ACPI; APM BIOS events are not supported.
APMQUERYSUSPEND = 0x0, //Request for permission to suspend. In Windows Server 2008 and Windows Vista, use the SetThreadExecutionState function instead.
APMQUERYSUSPENDFAILED = 0x2, //Suspension request denied. In Windows Server 2008 and Windows Vista, use SetThreadExecutionState instead.
APMRESUMECRITICAL = 0x6, //Operation resuming after critical suspension. In Windows Server 2008 and Windows Vista, use PBT_APMRESUMEAUTOMATIC instead.
}
public enum WTS
{
CONSOLE_CONNECT = 0x1, //The session identified by lParam was connected to the console terminal or RemoteFX session.
CONSOLE_DISCONNECT = 0x2, //The session identified by lParam was disconnected from the console terminal or RemoteFX session.
REMOTE_CONNECT = 0x3, //The session identified by lParam was connected to the remote terminal.
REMOTE_DISCONNECT = 0x4, //The session identified by lParam was disconnected from the remote terminal.
SESSION_LOGON = 0x5, //A user has logged on to the session identified by lParam.
SESSION_LOGOFF = 0x6, //A user has logged off the session identified by lParam.
SESSION_LOCK = 0x7, //The session identified by lParam has been locked.
SESSION_UNLOCK = 0x8, //The session identified by lParam has been unlocked.
SESSION_REMOTE_CONTROL = 0x9, //The session identified by lParam has changed its remote controlled status. To determine the status, call GetSystemMetrics and check the SM_REMOTECONTROL metric.
SESSION_CREATE = 0xA, //Reserved for future use.
SESSION_TERMINATE = 0xB, //Reserved for future use.
}
public enum DBT
{
CONFIGCHANGECANCELED = 0x0019, //A request to change the current configuration (dock or undock) has been canceled.
CONFIGCHANGED = 0x0018, //The current configuration has changed, due to a dock or undock.
CUSTOMEVENT = 0x8006, //A custom event has occurred.
DEVICEARRIVAL = 0x8000, //A device or piece of media has been inserted and is now available.
DEVICEQUERYREMOVE = 0x8001, //Permission is requested to remove a device or piece of media. Any application can deny this request and cancel the removal.
DEVICEQUERYREMOVEFAILED = 0x8002, //A request to remove a device or piece of media has been canceled.
DEVICEREMOVECOMPLETE = 0x8004, //A device or piece of media has been removed.
DEVICEREMOVEPENDING = 0x8003, //A device or piece of media is about to be removed. Cannot be denied.
DEVICETYPESPECIFIC = 0x8005, //A device-specific event has occurred.
DEVNODES_CHANGED = 0x0007, //A device has been added to or removed from the system.
QUERYCHANGECONFIG = 0x0017, //Permission is requested to change the current configuration (dock or undock).
USERDEFINED = 0xFFFF, //The meaning of this message is user-defined.
}
public enum WM
{
POWERBROADCAST = 0x0218, //PBT enums
WTSSESSION_CHANGE = 0x02B1, //WTS enums
DEVICECHANGE = 0x0219, //DBT enums
}
[StructLayout(LayoutKind.Sequential)]
public struct SERVICE_STATUS
{
public int serviceType;
public int currentState;
public int controlsAccepted;
public int win32ExitCode;
public int serviceSpecificExitCode;
public int checkPoint;
public int waitHint;
}
public enum ServiceControl
{
SERVICE_CONTROL_DEVICEEVENT = 0x0000000B,
SERVICE_CONTROL_HARDWAREPROFILECHANGE = 0x0000000C,
SERVICE_CONTROL_POWEREVENT = 0x0000000D,
SERVICE_CONTROL_SESSIONCHANGE = 0x0000000E,
SERVICE_CONTROL_TIMECHANGE = 0x00000010,
SERVICE_CONTROL_TRIGGEREVENT = 0x00000020,
SERVICE_CONTROL_USERMODEREBOOT = 0x00000040,
SERVICE_CONTROL_CONTINUE = 0x00000003,
SERVICE_CONTROL_INTERROGATE = 0x00000004,
SERVICE_CONTROL_NETBINDADD = 0x00000007,
SERVICE_CONTROL_NETBINDDISABLE = 0x0000000A,
SERVICE_CONTROL_NETBINDENABLE = 0x00000009,
SERVICE_CONTROL_NETBINDREMOVE = 0x00000008,
SERVICE_CONTROL_PARAMCHANGE = 0x00000006,
SERVICE_CONTROL_PAUSE = 0x00000002,
SERVICE_CONTROL_PRESHUTDOWN = 0x0000000F,
SERVICE_CONTROL_SHUTDOWN = 0x00000005,
SERVICE_CONTROL_STOP = 0x00000001,
}
public enum ServiceAccept
{
SERVICE_ACCEPT_NETBINDCHANGE = 0x00000010,
SERVICE_ACCEPT_PARAMCHANGE = 0x00000008,
SERVICE_ACCEPT_PAUSE_CONTINUE = 0x00000002,
SERVICE_ACCEPT_PRESHUTDOWN = 0x00000100,
SERVICE_ACCEPT_SHUTDOWN = 0x00000004,
SERVICE_ACCEPT_STOP = 0x00000001,
SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 0x00000020,
SERVICE_ACCEPT_POWEREVENT = 0x00000040,
SERVICE_ACCEPT_SESSIONCHANGE = 0x00000080,
SERVICE_ACCEPT_TIMECHANGE = 0x00000200,
SERVICE_ACCEPT_TRIGGEREVENT = 0x00000400,
SERVICE_ACCEPT_USERMODEREBOOT = 0x00000800, //windows 8
}
}
public static bool SetPreshutdownTimeout(SafeHandle handle, ref structenums.SERVICE_STATUS myServiceStatus)
{
SafeNativeMethods.SERVICE_PRESHUTDOWN_INFO spi = new SafeNativeMethods.SERVICE_PRESHUTDOWN_INFO();
spi.dwPreshutdownTimeout = 3600 * 1000;
IntPtr lpInfo = Marshal.AllocHGlobal(Marshal.SizeOf(spi));
if (lpInfo == IntPtr.Zero)
{
string errorMessage = LastError();
LibraryLogging.Error("Unable to allocate memory for service action, error: {0}", errorMessage);
EventLog.WriteEntry("pGina", String.Format("Unable to allocate memory for service action\nerror:{0}", errorMessage), EventLogEntryType.Warning);
return false;
}
else
{
Marshal.StructureToPtr(spi, lpInfo, false);
if (!SafeNativeMethods.ChangeServiceConfig2(handle, (int)SafeNativeMethods.INFO_LEVEL.SERVICE_CONFIG_PRESHUTDOWN_INFO, lpInfo))
{
string errorMessage = LastError();
LibraryLogging.Error("ChangeServiceConfig2 error: {0}", errorMessage);
EventLog.WriteEntry("pGina", String.Format("ChangeServiceConfig2\nThe service will be forced to stop during a shutdown within 3 minutes\nerror:{0}", errorMessage), EventLogEntryType.Warning);
return false;
}
Marshal.FreeHGlobal(lpInfo);
}
return true;
}
public static bool ShutdownPending(IntPtr handle, ref structenums.SERVICE_STATUS myServiceStatus, TimeSpan wait)
{
myServiceStatus.checkPoint++;
myServiceStatus.currentState = (int)SafeNativeMethods.State.SERVICE_STOP_PENDING;
myServiceStatus.waitHint = wait.Milliseconds;
if (!SafeNativeMethods.SetServiceStatus(handle, ref myServiceStatus))
{
LibraryLogging.Error("SetServiceStatus error:{0}", LastError());
return false;
}
return true;
}
public static bool SetServiceStopped(IntPtr handle, ref structenums.SERVICE_STATUS myServiceStatus)
{
myServiceStatus.checkPoint++;
myServiceStatus.currentState = (int)SafeNativeMethods.State.SERVICE_STOPPED;
myServiceStatus.waitHint = 0;
if (!SafeNativeMethods.SetServiceStatus(handle, ref myServiceStatus))
{
LibraryLogging.Error("SetServiceStatus error:{0}", LastError());
return false;
}
return true;
}
public static int GetSessionId()
{
int ret=0;
try
{
ret = SafeNativeMethods.WTSGetActiveConsoleSessionId();
}
catch
{
LibraryLogging.Error("GetSessionId() WTSGetActiveConsoleSessionId Error:{0}", LastError());
}
return ret;
}
public static IntPtr WTSQueryUserToken(int sessionId)
{
IntPtr result = IntPtr.Zero;
if (SafeNativeMethods.WTSQueryUserToken(sessionId, out result))
return result;
return IntPtr.Zero;
}
public static bool DeleteProfile(SecurityIdentifier sid)
{
return SafeNativeMethods.DeleteProfile(sid.ToString(), null, null);
}
public static List<string> GetInteractiveUserList()
{
List<string> result = new List<string>();
IntPtr sessionInfoList = IntPtr.Zero;
int sessionCount = 0;
int retVal = SafeNativeMethods.WTSEnumerateSessions(SafeNativeMethods.WTS_CURRENT_SERVER_HANDLE, 0, 1, ref sessionInfoList, ref sessionCount);
if(retVal != 0)
{
int dataSize = Marshal.SizeOf(typeof(SafeNativeMethods.WTS_SESSION_INFO));
Int64 currentSession = (Int64) sessionInfoList;
for(int x = 0; x < sessionCount; x++)
{
SafeNativeMethods.WTS_SESSION_INFO sessionInfo = (SafeNativeMethods.WTS_SESSION_INFO)Marshal.PtrToStructure((IntPtr)currentSession, typeof(SafeNativeMethods.WTS_SESSION_INFO));
currentSession += dataSize;
uint bytes = 0;
IntPtr userInfo = IntPtr.Zero;
IntPtr domainInfo = IntPtr.Zero;
bool sResult = SafeNativeMethods.WTSQuerySessionInformation(SafeNativeMethods.WTS_CURRENT_SERVER_HANDLE, sessionInfo.SessionID, SafeNativeMethods.WTS_INFO_CLASS.WTSUserName, out userInfo, out bytes);
if (!sResult)
{
LibraryLogging.Error("GetInteractiveUserList() WTSQuerySessionInformation WTSUserName Error:{0}", LastError());
}
string user = Marshal.PtrToStringAnsi(userInfo);
SafeNativeMethods.WTSFreeMemory(userInfo);
/*
sResult = SafeNativeMethods.WTSQuerySessionInformation(SafeNativeMethods.WTS_CURRENT_SERVER_HANDLE, sessionInfo.SessionID, SafeNativeMethods.WTS_INFO_CLASS.WTSDomainName, out domainInfo, out bytes);
if (!sResult)
{
LibraryLogging.Error("GetInteractiveUserList() WTSQuerySessionInformation WTSDomainName Error:{0}", LastError());
}
string domain = Marshal.PtrToStringAnsi(domainInfo);
SafeNativeMethods.WTSFreeMemory(domainInfo);
*/
/*
if (!string.IsNullOrEmpty(domain))
{
result.Add(string.Format("{0}\\{1}", domain, user));
}*/
if (!string.IsNullOrEmpty(user))
{
result.Add(string.Format("{0}\\{1}", sessionInfo.SessionID, user));
}
}
SafeNativeMethods.WTSFreeMemory(sessionInfoList);
}
//LibraryLogging.Info("InteractiveUsers:{0}", String.Join<string>(", ", result));
return result;
}
public static bool IsSessionLoggedOFF(int session)
{
SafeNativeMethods.WTS_SESSION_INFO sessionInfo = new SafeNativeMethods.WTS_SESSION_INFO();
// if WTSQuerySessionInformation returns false than the session is already closed
// WTSQuerySessionInformation returns zero if the session is logged off.
sessionInfo.State = SafeNativeMethods.WTS_CONNECTSTATE_CLASS.WTSReset;
uint bytes = 0;
IntPtr userInfo = IntPtr.Zero;
bool sResult = SafeNativeMethods.WTSQuerySessionInformation(SafeNativeMethods.WTS_CURRENT_SERVER_HANDLE, session, SafeNativeMethods.WTS_INFO_CLASS.WTSConnectState, out userInfo, out bytes);
if (sResult)
{
int lData = Marshal.ReadInt32(userInfo);
sessionInfo.State = (SafeNativeMethods.WTS_CONNECTSTATE_CLASS)Enum.ToObject(typeof(SafeNativeMethods.WTS_CONNECTSTATE_CLASS), lData);
/*
switch (sessionInfo.State)
{
case SafeNativeMethods.WTS_CONNECTSTATE_CLASS.WTSActive:
ret = "WTSActive";
break;
case SafeNativeMethods.WTS_CONNECTSTATE_CLASS.WTSConnected:
ret = "WTSConnected";
break;
case SafeNativeMethods.WTS_CONNECTSTATE_CLASS.WTSConnectQuery:
ret = "WTSConnectQuery";
break;
case SafeNativeMethods.WTS_CONNECTSTATE_CLASS.WTSDisconnected:
ret = "WTSDisconnected";
break;
case SafeNativeMethods.WTS_CONNECTSTATE_CLASS.WTSDown:
ret = "WTSDown";
break;
case SafeNativeMethods.WTS_CONNECTSTATE_CLASS.WTSIdle:
ret = "WTSIdle";
break;
case SafeNativeMethods.WTS_CONNECTSTATE_CLASS.WTSInit:
ret = "WTSInit";
break;
case SafeNativeMethods.WTS_CONNECTSTATE_CLASS.WTSListen:
ret = "WTSListen";
break;
case SafeNativeMethods.WTS_CONNECTSTATE_CLASS.WTSReset:
ret = "WTSReset";
break;
case SafeNativeMethods.WTS_CONNECTSTATE_CLASS.WTSShadow:
ret = "WTSShadow";
break;
}
*/
}
SafeNativeMethods.WTSFreeMemory(userInfo);
return (sessionInfo.State == SafeNativeMethods.WTS_CONNECTSTATE_CLASS.WTSReset) ? true : false;
}
public static string GetUserDomain(int sessionId)
{
uint bytes = 0;
IntPtr userInfo = IntPtr.Zero;
bool result = SafeNativeMethods.WTSQuerySessionInformation(SafeNativeMethods.WTS_CURRENT_SERVER_HANDLE, sessionId, SafeNativeMethods.WTS_INFO_CLASS.WTSDomainName, out userInfo, out bytes);
if (!result)
{
LibraryLogging.Error("GetUserDomain({1}) WTSQuerySessionInformation WTSUserName Error:{0}", LastError(), sessionId);
}
string userName = Marshal.PtrToStringAnsi(userInfo);
SafeNativeMethods.WTSFreeMemory(userInfo);
return userName;
}
public static string GetUserName(int sessionId)
{
uint bytes = 0;
IntPtr userInfo = IntPtr.Zero;
bool result = SafeNativeMethods.WTSQuerySessionInformation(SafeNativeMethods.WTS_CURRENT_SERVER_HANDLE, sessionId, SafeNativeMethods.WTS_INFO_CLASS.WTSUserName, out userInfo, out bytes);
if (!result)
{
LibraryLogging.Error("GetUserName({1}) WTSQuerySessionInformation WTSUserName Error:{0}", LastError(), sessionId);
}
string userName = Marshal.PtrToStringAnsi(userInfo);
SafeNativeMethods.WTSFreeMemory(userInfo);
return userName;
}
public static bool CloseHandle(IntPtr handle)
{
return SafeNativeMethods.CloseHandle(handle);
}
public static System.Diagnostics.Process StartProcessInSession(int sessionId, string cmdLine)
{
IntPtr processToken = IntPtr.Zero;
IntPtr duplicateToken = IntPtr.Zero;
try
{
// Get our current process token
using (System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess())
{
if (!SafeNativeMethods.OpenProcessToken(me.Handle, (uint)TokenAccessLevels.AllAccess, out processToken))
{
LibraryLogging.Error("StartProcessInSession({1}, {2}) OpenProcessToken Error:{0}", LastError(), sessionId, cmdLine);
}
}
// Duplicate it, so we can change it's session id
if (!SafeNativeMethods.DuplicateTokenEx(processToken, (uint)SafeNativeMethods.ACCESS_MASK.MAXIMUM_ALLOWED, IntPtr.Zero, SafeNativeMethods.SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, SafeNativeMethods.TOKEN_TYPE.TokenPrimary, out duplicateToken))
{
LibraryLogging.Error("StartProcessInSession({1}, {2}) DuplicateTokenEx Error:{0}", LastError(), sessionId, cmdLine);
}
// Poke the session id we want into our new token
if (!SafeNativeMethods.SetTokenInformation(duplicateToken, SafeNativeMethods.TOKEN_INFORMATION_CLASS.TokenSessionId, ref sessionId, Marshal.SizeOf(sessionId)))
{
LibraryLogging.Error("StartProcessInSession({1}, {2}) SetTokenInformation Error:{0}", LastError(), sessionId, cmdLine);
}
return StartProcessWithToken(duplicateToken, cmdLine);
}
finally
{
SafeNativeMethods.CloseHandle(processToken);
SafeNativeMethods.CloseHandle(duplicateToken);
}
}
public static bool StartProcessInSessionWait(int sessionId, string cmdLine)
{
try
{
using (Process p = StartProcessInSession(sessionId, cmdLine))
{
p.WaitForExit(); // trow exception if error
}
}
catch
{
return false;
}
return true;
}
public static bool StartUserProcessInSession(int sessionId, string cmdLine)
{
IntPtr userToken = IntPtr.Zero;
try
{
// Get user's token from session id, WTSQueryUserToken already returns a primary token for us
// so all we then have to do is use it to start the process.
if (!SafeNativeMethods.WTSQueryUserToken(sessionId, out userToken))
{
LibraryLogging.Error("StartUserProcessInSession({1}, {2}) WTSQueryUserToken Error:{0}", LastError(), sessionId, cmdLine);
}
using (Process p = StartProcessWithToken(userToken, cmdLine))
{
bool tmp = p.HasExited; // trow exception if error
}
}
catch
{
return false;
}
finally
{
SafeNativeMethods.CloseHandle(userToken);
}
return true;
}
public static bool StartUserProcessInSessionWait(int sessionId, string cmdLine)
{
IntPtr userToken = IntPtr.Zero;
try
{
// Get user's token from session id, WTSQueryUserToken already returns a primary token for us
// so all we then have to do is use it to start the process.
if (!SafeNativeMethods.WTSQueryUserToken(sessionId, out userToken))
{
LibraryLogging.Error("StartUserProcessInSession({1}, {2}) WTSQueryUserToken Error:{0}", LastError(), sessionId, cmdLine);
}
using (Process p = StartProcessWithToken(userToken, cmdLine))
{
p.WaitForExit(); // trow exception if error
}
}
catch
{
return false;
}
finally
{
SafeNativeMethods.CloseHandle(userToken);
}
return true;
}
public static System.Diagnostics.Process StartProcessWithToken(IntPtr token, string cmdLine)
{
IntPtr environmentBlock = IntPtr.Zero;
try
{
// Default nil security attribute
SafeNativeMethods.SECURITY_ATTRIBUTES defSec = new SafeNativeMethods.SECURITY_ATTRIBUTES();
defSec.nLength = Marshal.SizeOf(defSec);
defSec.lpSecurityDescriptor = IntPtr.Zero;
defSec.bInheritHandle = 0;
// Create an environment block
if (!SafeNativeMethods.CreateEnvironmentBlock(ref environmentBlock, token, false))
{
LibraryLogging.Error("StartProcessWithToken(IntPtr, {1}) CreateEnvironmentBlock Error:{0}", LastError(), cmdLine);
}
// Now we can finally get into the business at hand and setup our process info
SafeNativeMethods.STARTUPINFO startInfo = new SafeNativeMethods.STARTUPINFO();
startInfo.cb = Marshal.SizeOf(startInfo);
//startInfo.wShowWindow = 0;
//startInfo.lpDesktop = "Winsta0\\Default"; // TBD: Support other desktops?
SafeNativeMethods.PROCESS_INFORMATION procInfo = new SafeNativeMethods.PROCESS_INFORMATION();
if (!SafeNativeMethods.CreateProcessAsUser(token, null, cmdLine, ref defSec, ref defSec, false, SafeNativeMethods.CreationFlags.CREATE_UNICODE_ENVIRONMENT, environmentBlock, null, ref startInfo, out procInfo))
{
LibraryLogging.Error("StartProcessWithToken(IntPtr, {1}) CreateProcessAsUser Error:{0}", LastError(), cmdLine);
}
// We made it, process is running! Closing our handles to it ensures it doesn't orphan,
// then we just use its pid to return a process object
SafeNativeMethods.CloseHandle(procInfo.hProcess);
SafeNativeMethods.CloseHandle(procInfo.hThread);
return System.Diagnostics.Process.GetProcessById((int)procInfo.dwProcessId);
}
finally
{
SafeNativeMethods.CloseHandle(environmentBlock);
}
}
public static bool StartProcessAsUserWait(string username, string domain, string password, string command)
{
IntPtr hToken = IntPtr.Zero;
if (SafeNativeMethods.LogonUser(username, domain, password, (int)SafeNativeMethods.LogonType.LOGON32_LOGON_INTERACTIVE, (int)SafeNativeMethods.LogonProvider.LOGON32_PROVIDER_DEFAULT, out hToken))
{
SafeNativeMethods.PROFILEINFO pinfo = new SafeNativeMethods.PROFILEINFO();
pinfo.dwSize = Marshal.SizeOf(pinfo);
pinfo.lpUserName = username;
if (SafeNativeMethods.LoadUserProfile(hToken, ref pinfo))
{
using (Process proc = StartProcessWithToken(hToken, command))
{
try
{
proc.WaitForExit();
}
catch
{
if (!SafeNativeMethods.UnloadUserProfile(hToken, pinfo.hProfile))
{
LibraryLogging.Error("StartProcessAsUserWait({0}, {1}, ****, {2}) UnloadUserProfile Error:{3}", username, domain, command, LastError());
}
CloseHandle(hToken);
return false;
}
}
if (!SafeNativeMethods.UnloadUserProfile(hToken, pinfo.hProfile))
{
LibraryLogging.Error("StartProcessAsUserWait({0}, {1}, ****, {2}) UnloadUserProfile Error:{3}", username, domain, command, LastError());
}
}
else
{
LibraryLogging.Error("StartProcessAsUserWait({0}, {1}, ****, {2}) LoadUserProfile Error:{3}", username, domain, command, LastError());
CloseHandle(hToken);
return false;
}
CloseHandle(hToken);
}
else
{
LibraryLogging.Error("StartProcessAsUserWait({0}, {1}, ****, {2}) LogonUser Error:{3}", username, domain, command, LastError());
return false;
}
return true;
}
/// <summary>
/// Run app as system
/// </summary>
/// <param name="Application"></param>
/// <param name="CommandLine"></param>
/// <returns>return code of the app or uint.MaxValue if exception</returns>
public static uint CProcess(string Application, string CommandLine)
{
SafeNativeMethods.PROCESS_INFORMATION pInfo = new SafeNativeMethods.PROCESS_INFORMATION();
SafeNativeMethods.STARTUPINFO sInfo = new SafeNativeMethods.STARTUPINFO();
SafeNativeMethods.SECURITY_ATTRIBUTES pSec = new SafeNativeMethods.SECURITY_ATTRIBUTES();
SafeNativeMethods.SECURITY_ATTRIBUTES tSec = new SafeNativeMethods.SECURITY_ATTRIBUTES();
pSec.nLength = Marshal.SizeOf(pSec);
tSec.nLength = Marshal.SizeOf(tSec);
if (SafeNativeMethods.CreateProcess(Application, CommandLine, ref pSec, ref tSec, false, 0x0020, IntPtr.Zero, null, ref sInfo, out pInfo))
{
if (SafeNativeMethods.WaitForSingleObject(pInfo.hProcess, -1) == 0)
{
uint ExitCode;
if (!SafeNativeMethods.GetExitCodeProcess(pInfo.hProcess, out ExitCode))
{
LibraryLogging.Error(String.Format("CProcess() GetExitCodeProcess Error:{0}", LastError()));
return uint.MaxValue;
}
return ExitCode;
}
else
{
LibraryLogging.Error(String.Format("CProcess() WaitForSingleObject Error:{0}", LastError()));
}
}
else
{
LibraryLogging.Error(String.Format("CreateProcess Error:{0}", LastError()));
}
return uint.MaxValue;
}
public static NetworkCredential GetCredentials(string caption, string message)
{
SafeNativeMethods.CREDUI_INFO uiInfo = new SafeNativeMethods.CREDUI_INFO();
uiInfo.cbSize = Marshal.SizeOf(uiInfo);
uiInfo.pszCaptionText = caption;
uiInfo.pszMessageText = message;
uint authPackage = 0;
IntPtr outCredBuffer = new IntPtr();
uint outCredSize;
bool save = false;
int result = SafeNativeMethods.CredUIPromptForWindowsCredentials(ref uiInfo, 0, ref authPackage,
IntPtr.Zero, 0, out outCredBuffer, out outCredSize, ref save, 0);
var usernameBuf = new StringBuilder(100);
var passwordBuf = new StringBuilder(100);
var domainBuf = new StringBuilder(100);
int maxUserName = 100;
int maxDomain = 100;
int maxPassword = 100;
if (result == 0)
{
if (SafeNativeMethods.CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName,
domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
{
SafeNativeMethods.CoTaskMemFree(outCredBuffer);
return new NetworkCredential()
{
UserName = usernameBuf.ToString(),
Password = <PASSWORD>Buf.ToString(),
Domain = domainBuf.ToString()
};
}
}
return null;
}
/// <summary>
/// Map a network drive.
/// </summary>
/// <param name="unc">The full UNC path.</param>
/// <param name="drive">The drive letter (e.g. "Z:", "X:", etc.)</param>
/// <param name="user">The username, null if you want the current user.</param>
/// <param name="password">The password, null to use the default password.</param>
/// <returns>The error code of the WNetAddConnection2 function.</returns>
public static int MapNetworkDrive(string unc, string drive, string user, string password)
{
SafeNativeMethods.NETRESOURCE myNetResource = new SafeNativeMethods.NETRESOURCE();
myNetResource.lpLocalName = drive;
myNetResource.lpRemoteName = unc;
int result = SafeNativeMethods.WNetAddConnection2(myNetResource, password, user, 0);
return result;
}
public static bool LogoffSession(int sessionId)
{
return SafeNativeMethods.WTSLogoffSession(SafeNativeMethods.WTS_CURRENT_SERVER_HANDLE, sessionId, false);
}
/// <summary>
/// Attempts to validate the user's credentials for a local account using
/// a pInvoke to LogonUser.
/// </summary>
/// <param name="username">The username</param>
/// <param name="password">The password</param>
/// <returns>True if the account credentials are valid</returns>
public static bool ValidateCredentials(string username, string password)
{
return ValidateCredentials(username, "", password);
}
/// <summary>
/// Attempts to validate the user's credentials using
/// a pInvoke to LogonUser.
/// </summary>
/// <param name="username">The username</param>
/// <param name="domain">The domain</param>
/// <param name="password">The password</param>
/// <returns>True if the account credentials are valid</returns>
public static bool ValidateCredentials(string username, string domain, string password)
{
int ret = LogonUser(username, domain, password);
if (ret == 0)
{
return true;
}
return false;
}
/// <summary>
/// Attempts to validate the user's credentials using
/// a pInvoke to LogonUser but ignores password change response.
/// </summary>
/// <param name="username">The username</param>
/// <param name="domain">The domain</param>
/// <param name="password">The <PASSWORD></param>
/// <returns>True if the account credentials are valid</returns>
public static bool ValidateUser(string username, string domain, string password)
{
int ret = LogonUser(username, domain, password);
// ERROR_PASSWORD_EXPIRED <PASSWORD>
// ERROR_PASSWORD_MUST_CHANGE <PASSWORD>
// ERROR_PASSWORD_CHANGE_REQUIRED 1938
if (new int[] { 0, 1330, 1907, 1938 }.Any(a => a == ret))
{
return true;
}
return false;
}
internal static int LogonUser(string username, string domain, string password)
{
int error = 0;
IntPtr hToken = IntPtr.Zero;
bool result = SafeNativeMethods.LogonUser(username, domain, password,
(int)SafeNativeMethods.LogonType.LOGON32_LOGON_NETWORK,
(int)SafeNativeMethods.LogonProvider.LOGON32_PROVIDER_DEFAULT,
out hToken);
if (!result)
{
error = Marshal.GetLastWin32Error();
Abstractions.Logging.LibraryLogging.Debug("LogonUser:{0} {1} {2}", result, error, LastError());
}
if (hToken != IntPtr.Zero) CloseHandle(hToken);
return error;
}
public static bool WTSRegister(IntPtr handle)
{
if (!SafeNativeMethods.WTSRegisterSessionNotification(handle, 1/*NOTIFY_FOR_ALL_SESSIONS*/))
{
LibraryLogging.Error("WTSRegisterSessionNotification error:{0}", LastError());
return false;
}
return true;
}
public static bool WTSUnRegister(IntPtr handle)
{
if (!SafeNativeMethods.WTSUnRegisterSessionNotification(handle))
{
LibraryLogging.Error("WTSUnRegisterSessionNotification error:{0}", LastError());
return false;
}
return true;
}
/// <summary>
/// return username based on context in which a program is running.
/// a program running as administrator will add administrator to the list
/// session ID -1 retuns all sessions instead of a specific one
/// </summary>
/// <param name="sessionID">the seesion ID or -1 for all sessions</param>
/// <returns>is a lower username like administrator</returns>
public static List<string> GetSessionContext(int sessionID)
{
List<string> ret = new List<string>();
Dictionary<int, List<string>> contextALL = GetSessionContext();
foreach (KeyValuePair<int, List<string>> pair in contextALL)
{
if (pair.Key == sessionID || sessionID == -1)
{
foreach (string user in pair.Value)
{
if (!ret.Any(s => s.Equals(user, StringComparison.CurrentCultureIgnoreCase)))
{
ret.Add(user);
}
}
}
}
return ret;
}
/// <summary>
/// return username based on context in which a program is running.
/// a program running as administrator will add administrator to the list
/// session ID -1 retuns all sessions instead of a specific one
/// </summary>
/// <param name="sessionID">the seesion ID or -1 for all sessions</param>
/// <param name="contextALL">a GetSessionContext() Directory</param>
/// <returns>is a lower username like administrator</returns>
public static List<string> GetSessionContextParser(int sessionID, Dictionary<int, List<string>> contextALL)
{
List<string> ret = new List<string>();
foreach (KeyValuePair<int, List<string>> pair in contextALL)
{
if (pair.Key == sessionID || sessionID == -1)
{
foreach (string user in pair.Value)
{
if (!ret.Any(s => s.Equals(user, StringComparison.CurrentCultureIgnoreCase)))
{
ret.Add(user);
}
}
}
}
return ret;
}
/// <summary>
/// returns a Dictionary of SessionID Keys and a List of usernames based on context in which a program is running.
/// a program running as administrator will add administrator to the list
/// </summary>
/// <returns>is a lower username like administrator</returns>
public static Dictionary<int, List<string>> GetSessionContext()
{
Dictionary<int, List<string>> ret = new Dictionary<int, List<string>>();
foreach (Process process in Process.GetProcesses())
{
try { var test = process.Handle; }
catch { continue; }
//Console.WriteLine("process:{0}", process.ProcessName);
IntPtr tokenHandle;
// Get the Process Token
if (!SafeNativeMethods.OpenProcessToken(process.Handle, SafeNativeMethods.TokenAccessRights.TOKEN_READ, out tokenHandle))
{
LibraryLogging.Error("OpenProcessToken error:{0}", LastError());
return ret;
}
int TokenInfLength = 0;
if (!SafeNativeMethods.GetTokenInformation(tokenHandle, SafeNativeMethods.TOKEN_INFORMATION_CLASS.TokenUser, IntPtr.Zero, TokenInfLength, out TokenInfLength))
{
int error = Marshal.GetLastWin32Error();
if (error != 122 /*ERROR_INSUFFICIENT_BUFFER*/)
{
LibraryLogging.Error("GetTokenInformation error:{0} {1}", error, LastError());
}
else
{
IntPtr TokenInformation = Marshal.AllocHGlobal(TokenInfLength);
if (!SafeNativeMethods.GetTokenInformation(tokenHandle, SafeNativeMethods.TOKEN_INFORMATION_CLASS.TokenUser, TokenInformation, TokenInfLength, out TokenInfLength))
{
LibraryLogging.Error("GetTokenInformation error:{0}", LastError());
}
else
{
SafeNativeMethods.TOKEN_USER TokenUser = (SafeNativeMethods.TOKEN_USER)Marshal.PtrToStructure(TokenInformation, typeof(SafeNativeMethods.TOKEN_USER));
StringBuilder name = new StringBuilder();
uint cchName = (uint)name.Capacity;
StringBuilder referencedDomainName = new StringBuilder();
uint cchReferencedDomainName = (uint)referencedDomainName.Capacity;
SafeNativeMethods.SID_NAME_USE sidUse;
bool WinAPI = SafeNativeMethods.LookupAccountSid(null, TokenUser.User.Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse);
if (!WinAPI)
{
error = Marshal.GetLastWin32Error();
if (error == 122 /*ERROR_INSUFFICIENT_BUFFER*/)
{
name.EnsureCapacity((int)cchName);
referencedDomainName.EnsureCapacity((int)cchReferencedDomainName);
WinAPI = SafeNativeMethods.LookupAccountSid(null, TokenUser.User.Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse);
if (!WinAPI)
{
LibraryLogging.Error("LookupAccountSid error:{0}", LastError());
}
}
else
{
LibraryLogging.Error("LookupAccountSid error:{0}", LastError());
}
}
if (WinAPI)
{
//LibraryLogging.Info("Found process:{0} in session:{1} account:{2}", process.ProcessName, process.SessionId, name.ToString());
if (!ret.ContainsKey(process.SessionId))
{
ret.Add(process.SessionId, new List<string>() { name.ToString() });
}
else
{
if (!ret[process.SessionId].Contains(name.ToString()))
{
ret[process.SessionId].Add(name.ToString());
}
}
}
}
Marshal.FreeHGlobal(TokenInformation);
}
}
SafeNativeMethods.CloseHandle(tokenHandle);
}
return ret;
}
/// <summary>
/// Create a handle to the user token
/// make sure to close the handle!!!
/// </summary>
/// <param name="username"></param>
/// <param name="domain"></param>
/// <param name="password"></param>
/// <returns></returns>
public static IntPtr GetUserToken(string username, string domain, string password)
{
IntPtr hToken = IntPtr.Zero;
bool result = SafeNativeMethods.LogonUser(username, domain, password,
(int)SafeNativeMethods.LogonType.LOGON32_LOGON_NETWORK,
(int)SafeNativeMethods.LogonProvider.LOGON32_PROVIDER_DEFAULT,
out hToken);
if (!result)
{
LibraryLogging.Error("LogonUser error:{0}", LastError());
}
return hToken;
}
/// <summary>
/// calls API CreateProfile
/// an empty string on error
/// a null string on already exists
/// a string on success
/// </summary>
/// <param name="hToken"></param>
/// <param name="username"></param>
/// <returns></returns>
public static string CreateUserProfileDir(IntPtr hToken, string username)
{
StringBuilder path = new StringBuilder(260);
uint size = Convert.ToUInt32(path.Capacity);
uint hResult = 0;
using (System.Security.Principal.WindowsIdentity i = new System.Security.Principal.WindowsIdentity(hToken))
{
hResult = SafeNativeMethods.CreateProfile(i.Owner.Value, username, path, size);
}
if (hResult == 2147942583)
{
LibraryLogging.Error("CreateProfile already exists:{0}", LastError());
return null;
}
else if (hResult == 0)
{
return path.ToString();
}
else
{
LibraryLogging.Error("CreateProfile error:{0} {1} {2}", hResult, LastError(), path.ToString());
}
return "";
}
/// <summary>
/// get or create user profile directory
/// only if the ProfileList regkey is not of SID.bak (Abstractions.User.FixProfileList)
/// an empty or null string means error
/// </summary>
/// <param name="username"></param>
/// <param name="domain"></param>
/// <param name="password"></param>
/// <returns></returns>
public static string GetOrSetUserProfileDir(string username, string domain, string password)
{
string ret = "";
StringBuilder path = new StringBuilder(260);
uint path_size = Convert.ToUInt32(path.Capacity);
IntPtr hToken = GetUserToken(username, domain, password);
if (hToken == IntPtr.Zero)
{
LibraryLogging.Error("GetOrSetUserProfileDir can't get userToken");
return "";
}
ret = GetUserProfileDir(hToken);
if (String.IsNullOrEmpty(ret))
{
ret = CreateUserProfileDir(hToken, username);
if (String.IsNullOrEmpty(ret))
{
LibraryLogging.Error("GetOrSetUserProfileDir failed to get and create profile error:{0}", LastError());
}
}
SafeNativeMethods.CloseHandle(hToken);
return ret;
}
/// <summary>
/// returns userprofile based on GetUserProfileDirectory
/// only if the ProfileList regkey is not of SID.bak (Abstractions.User.FixProfileList)
/// empty string means error
/// </summary>
/// <param name="hToken"></param>
/// <returns></returns>
public static string GetUserProfileDir(IntPtr hToken)
{
string ret = "";
StringBuilder path = new StringBuilder(260);
uint path_size = Convert.ToUInt32(path.Capacity);
if (SafeNativeMethods.GetUserProfileDirectory(hToken, path, ref path_size))
{
ret = path.ToString();
}
else
{
LibraryLogging.Error("GetUserProfileDirectory error:{0}", LastError());
}
return ret;
}
/// <summary>
/// returns userprofile based on SHGetFolderPath
/// only if the profile realy exists and the ProfileList regkey is not of SID.bak (Abstractions.User.FixProfileList)
/// empty string means error
/// </summary>
/// <param name="hToken"></param>
/// <returns></returns>
public static string GetUserProfilePath(IntPtr hToken)
{
const int MaxPath = 260;
StringBuilder sb = new StringBuilder(MaxPath);
int hResult = SafeNativeMethods.SHGetFolderPath(IntPtr.Zero, 0x0028/*CSIDL_PROFILE*/, hToken, 0x0000, sb);
if (hResult != 0)
{
LibraryLogging.Error("SHGetFolderPath error:{0}", LastError());
return "";
}
return sb.ToString();
}
/// <summary>
/// get the real windows version
/// http://www.codeproject.com/Articles/678606/Part-Overcoming-Windows-s-deprecation-of-GetVe
/// </summary>
/// <returns></returns>
public static structenums.OSVERSIONINFOW VersionsInfo()
{
structenums.OSVERSIONINFOW ret = new structenums.OSVERSIONINFOW();
ret.dwOSVersionInfoSize = Marshal.SizeOf(ret);
if (SafeNativeMethods.RtlGetVersion(ref ret) != 0)
{
LibraryLogging.Error("VersionsInfo error:{0}", LastError());
}
return ret;
}
/// <summary>
/// return true if a local user exists
/// </summary>
/// <param name="username"></param>
/// <param name="domain"></param>
/// <returns></returns>
public static Boolean UserExists(string username, string domain)
{
structenums.USER_INFO_4 userinfo4 = new structenums.USER_INFO_4();
if (UserGet(username, domain, ref userinfo4))
{
return true;
}
return false;
}
/// <summary>
/// return true if a local user exists
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public static Boolean UserExists(string username)
{
return UserExists(username, null);
}
/// <summary>
/// add user to the local system
/// based on http://social.msdn.microsoft.com/forums/en-us/csharpgeneral/thread/B70B79D9-971F-4D6F-8462-97FC126DE0AD
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="comment"></param>
/// <returns></returns>
public static Boolean UserADD(string username, string password, string comment)
{
SafeNativeMethods.USER_INFO_1 NewUser = new SafeNativeMethods.USER_INFO_1();
NewUser.usri1_name = username; // Allocates the username
NewUser.usri1_password = <PASSWORD>; // allocates the password
NewUser.usri1_priv = structenums.UserPrivileges.USER_PRIV_USER; // Sets the account type to USER_PRIV_USER
NewUser.usri1_home_dir = null; // We didn't supply a Home Directory
NewUser.comment = comment;// "pGina created pgSMB"; // Comment on the User
NewUser.usri1_script_path = null; // We didn't supply a Logon Script Path
Int32 ret;
SafeNativeMethods.NetUserAdd(Environment.MachineName, 1, ref NewUser, out ret);
//2224 The user account already exists. NERR_UserExists
if ((ret != 0) && (ret != 2224)) // If the call fails we get a non-zero value
{
LibraryLogging.Error("NetUserAdd error:{0} {1}", ret, LastError());
return false;
}
return true;
}
/// <summary>
/// modify local user settings based on a USER_INFO_4 struct
/// based on http://social.msdn.microsoft.com/forums/en-us/csharpgeneral/thread/B70B79D9-971F-4D6F-8462-97FC126DE0AD
/// </summary>
/// <param name="username"></param>
/// <param name="userInfo4"></param>
/// <returns></returns>
public static Boolean UserMod(string username, structenums.USER_INFO_4 userInfo4)
{
Int32 ret = 1;
SafeNativeMethods.NetUserSetInfo(null, username, 4, ref userInfo4, out ret);
if (ret != 0) // If the call fails we get a non-zero value
{
LibraryLogging.Error("NetUserSetInfo error:{0} {1}", ret, LastError());
return false;
}
return true;
}
/// <summary>
/// returns local user settings as a ref of an USER_INFO_4 struct
/// based on http://social.msdn.microsoft.com/forums/en-us/csharpgeneral/thread/B70B79D9-971F-4D6F-8462-97FC126DE0AD
/// </summary>
/// <param name="username"></param>
/// <param name="userinfo4">a ref of an USER_INFO_4 struct</param>
/// <returns>bool true 4 success</returns>
public static Boolean UserGet(string username, ref structenums.USER_INFO_4 userinfo4)
{
return UserGet(username, null, ref userinfo4);
}
/// <summary>
/// returns local user settings as a ref of an USER_INFO_4 struct
/// based on http://social.msdn.microsoft.com/forums/en-us/csharpgeneral/thread/B70B79D9-971F-4D6F-8462-97FC126DE0AD
/// </summary>
/// <param name="username"></param>
/// <param name="domain"></param>
/// <param name="userinfo4">a ref of an USER_INFO_4 struct</param>
/// <returns>bool true 4 success</returns>
public static Boolean UserGet(string username, string domain, ref structenums.USER_INFO_4 userinfo4)
{
IntPtr bufPtr;
int lngReturn = SafeNativeMethods.NetUserGetInfo((String.IsNullOrEmpty(domain)) ? null : domain, username, 4, out bufPtr);
if (lngReturn == 0)
{
try
{
userinfo4 = (structenums.USER_INFO_4)Marshal.PtrToStructure(bufPtr, typeof(structenums.USER_INFO_4));
}
catch (Exception ex)
{
LibraryLogging.Error("UserGet Marshal.PtrToStructure error:{0}", ex.ToString());
return false;
}
}
else if (lngReturn == 2221)
{
// user does not exist
}
else
{
string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).ToString();
LibraryLogging.Error("NetUserGetInfo error:{0} {1}", lngReturn, errorMessage);
}
SafeNativeMethods.NetApiBufferFree(bufPtr);
if (lngReturn == 0)
{
return true;
}
return false;
}
/// <summary>
/// delete a local user
/// based on http://social.msdn.microsoft.com/forums/en-us/csharpgeneral/thread/B70B79D9-971F-4D6F-8462-97FC126DE0AD
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public static Boolean UserDel(string username)
{
Int32 ret;
ret = SafeNativeMethods.NetUserDel(null, username);
if ((ret != 0) && (ret != 2221)) // If the call fails we get a non-zero value
{
LibraryLogging.Error("NetUserDel error:{0} {1}", ret, LastError());
return false;
}
return true;
}
public static string UserChangePassword(string domainname, string username, string oldpassword, string newpassword)
{
int result = pInvokes.SafeNativeMethods.NetUserChangePassword((String.IsNullOrEmpty(domainname))? Environment.MachineName : domainname, username, oldpassword, newpassword);
if (result != 0)
{
LibraryLogging.Error("NetUserChangePassword({0}, {1}, {2}, {3}) Error:{4} {5}", (String.IsNullOrEmpty(domainname)) ? Environment.MachineName : domainname, username, "***", "***", result, LastError(result));
return String.Format("Password change failed for user {0} with error {1}\n{2}", username, result, LastError(result));
}
return "";
}
/// <summary>
/// send a messagebox to a session
/// </summary>
/// <param name="sessionID"></param>
/// <param name="title"></param>
/// <param name="message"></param>
/// <returns></returns>
public static Boolean SendMessageToUser(int sessionID, string title, string message)
{
int resp = 0;
bool result = SafeNativeMethods.WTSSendMessage(IntPtr.Zero, sessionID, title, title.Length, message, message.Length, 0, 0, out resp, false);
if (!result)
{
LibraryLogging.Error("WTSSendMessage error:{0} {1}", result, LastError());
return false;
}
return true;
}
/// <summary>
/// connect to a remote computer
/// based on http://social.msdn.microsoft.com/Forums/et-EE/netfxbcl/thread/58159e0e-aa45-4d46-a128-596c3d23ff5c
/// </summary>
/// <param name="remoteUNC"></param>
/// <param name="username">better use the domainname\username format</param>
/// <param name="password"></param>
/// <returns></returns>
public static Boolean MapNetworkDrive(string remoteUNC, string username, string password)
{
return MapNetworkDrive(remoteUNC, username, password, false);
}
/// <summary>
/// connect to a remote computer
/// based on http://social.msdn.microsoft.com/Forums/et-EE/netfxbcl/thread/58159e0e-aa45-4d46-a128-596c3d23ff5c
/// </summary>
/// <param name="remoteUNC"></param>
/// <param name="username">better use the domainname\username format</param>
/// <param name="password"></param>
/// <param name="promptUser">true to for a promt, if needed</param>
/// <returns></returns>
public static Boolean MapNetworkDrive(string remoteUNC, string username, string password, bool promptUser)
{
SafeNativeMethods.NETRESOURCE nr = new SafeNativeMethods.NETRESOURCE();
nr.dwType = SafeNativeMethods.ResourceType.RESOURCETYPE_DISK;
nr.lpRemoteName = remoteUNC;
// nr.lpLocalName = "F:";
int ret;
if (promptUser)
{
ret = SafeNativeMethods.WNetUseConnection(IntPtr.Zero, nr, "", "", SafeNativeMethods.Connect.CONNECT_INTERACTIVE | SafeNativeMethods.Connect.CONNECT_PROMPT, null, null, null);
}
else
{
ret = SafeNativeMethods.WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);
}
if (ret != 0)
{
LibraryLogging.Error("Unable to connect to {0} as {1} Error:{2} {3}", remoteUNC, username, ret, LastError());
return false;
}
return true;
}
/// <summary>
/// disconnecting an UNC share
/// </summary>
/// <param name="remoteUNC"></param>
/// <returns></returns>
public static Boolean DisconnectNetworkDrive(string remoteUNC)
{
int ret = SafeNativeMethods.WNetCancelConnection2(remoteUNC, SafeNativeMethods.Connect.CONNECT_UPDATE_PROFILE, false);
if ((ret != 0) && (ret != 2250/*This network connection does not exist*/))
{
LibraryLogging.Error("Unable to disConnect from {0} Error:{1} {2}", remoteUNC, ret, LastError());
return false;
}
return true;
}
/// <summary>
/// Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, the total amount of free space, and the total amount of free space available to the user that is associated with the calling thread.
/// based on http://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx
/// </summary>
/// <param name="share"></param>
/// <returns>An array[freeBytesForUser,totalBytes,freeBytes]. On error all values are -1</returns>
public static long[] GetFreeShareSpace(string share)
{
long freeBytesForUser = -1, totalBytes = -1, freeBytes = -1;
if (!SafeNativeMethods.GetDiskFreeSpaceEx(share, out freeBytesForUser, out totalBytes, out freeBytes))
{
LibraryLogging.Error("Unable to enumerate free space on {0} Error:{1}", share, LastError());
return new long[] { -1, -1, -1 };
}
return new long[] { freeBytesForUser, totalBytes, freeBytes };
}
/// <summary>
/// get RegistryKey from structenums.RegistryLocation
/// </summary>
/// <param name="location"></param>
/// <returns></returns>
public static RegistryKey GetRegistryLocation(structenums.RegistryLocation location)
{
switch (location)
{
case structenums.RegistryLocation.HKEY_CLASSES_ROOT:
return Registry.ClassesRoot;
case structenums.RegistryLocation.HKEY_CURRENT_USER:
return Registry.CurrentUser;
case structenums.RegistryLocation.HKEY_LOCAL_MACHINE:
return Registry.LocalMachine;
case structenums.RegistryLocation.HKEY_USERS:
return Registry.Users;
case structenums.RegistryLocation.HKEY_CURRENT_CONFIG:
return Registry.CurrentConfig;
default:
return null;
}
}
// based on http://stackoverflow.com/questions/7894909/load-registry-hive-from-c-sharp-fails
internal static Boolean RegistryLoadSetPrivilege()
{
IntPtr _myToken;
SafeNativeMethods.TokPriv1Luid _tokenPrivileges = new SafeNativeMethods.TokPriv1Luid();
SafeNativeMethods.TokPriv1Luid _tokenPrivileges2 = new SafeNativeMethods.TokPriv1Luid();
SafeNativeMethods.LUID _restoreLuid;
SafeNativeMethods.LUID _backupLuid;
if (!SafeNativeMethods.OpenProcessToken(SafeNativeMethods.GetCurrentProcess(), SafeNativeMethods.TokenAccessRights.TOKEN_ADJUST_PRIVILEGES | SafeNativeMethods.TokenAccessRights.TOKEN_QUERY, out _myToken))
{
LibraryLogging.Error("SetPrivilege() OpenProcess Error: {0}", LastError());
return false;
}
if (!SafeNativeMethods.LookupPrivilegeValue(null, SafeNativeMethods.TokenAccessRights.SE_RESTORE_NAME, out _restoreLuid))
{
LibraryLogging.Error("SetPrivilege() LookupPrivilegeValue Error: {0}", LastError());
return false;
}
if (!SafeNativeMethods.LookupPrivilegeValue(null, SafeNativeMethods.TokenAccessRights.SE_BACKUP_NAME, out _backupLuid))
{
LibraryLogging.Error("SetPrivilege() LookupPrivilegeValue Error: {0}", LastError());
return false;
}
_tokenPrivileges.Attr = SafeNativeMethods.TokenAccessRights.SE_PRIVILEGE_ENABLED;
_tokenPrivileges.Luid = _restoreLuid;
_tokenPrivileges.Count = 1;
_tokenPrivileges2.Attr = SafeNativeMethods.TokenAccessRights.SE_PRIVILEGE_ENABLED;
_tokenPrivileges2.Luid = _backupLuid;
_tokenPrivileges2.Count = 1;
if (!SafeNativeMethods.AdjustTokenPrivileges(_myToken, false, ref _tokenPrivileges, 0, IntPtr.Zero, IntPtr.Zero))
{
LibraryLogging.Error("SetPrivilege() AdjustTokenPrivileges Error: {0}", LastError());
return false;
}
if (!SafeNativeMethods.AdjustTokenPrivileges(_myToken, false, ref _tokenPrivileges2, 0, IntPtr.Zero, IntPtr.Zero))
{
LibraryLogging.Error("SetPrivilege() AdjustTokenPrivileges Error: {0}", LastError());
return false;
}
if (!CloseHandle(_myToken))
{
LibraryLogging.Warn("Can't close handle _myToken");
}
SafeNativeMethods.RegistryLoadPrivilegeSet = true;
return true;
}
/// <summary>
/// load a regfile at hklm or hku
/// </summary>
/// <param name="where">hklm or hku</param>
/// <param name="name">The name of the key to be created under hKey. This subkey is where the registration information from the file will be loaded</param>
/// <param name="file"></param>
/// <returns></returns>
public static Boolean RegistryLoad(structenums.RegistryLocation where, string name, string file)
{
if (where != structenums.RegistryLocation.HKEY_LOCAL_MACHINE && where != structenums.RegistryLocation.HKEY_USERS)
{
LibraryLogging.Error("unable to load regfile at {0}", where);
return false;
}
if (!SafeNativeMethods.RegistryLoadPrivilegeSet)
{
if (!RegistryLoadSetPrivilege())
return false;
}
int ret = SafeNativeMethods.RegLoadKey((uint)Enum.Parse(typeof(structenums.baseKey), where.ToString()), name, file);
if (ret != 0)
{
LibraryLogging.Error("Unable to load regfile {0} error:{1} {2}", file, ret, LastError(ret));
return false;
}
return true;
}
/// <summary>
/// unload regfile from regkey
/// </summary>
/// <param name="where">hklm or hku</param>
/// <param name="name"></param>
/// <returns></returns>
public static Boolean RegistryUnLoad(structenums.RegistryLocation where, string name)
{
if (!SafeNativeMethods.RegistryLoadPrivilegeSet)
{
if (!RegistryLoadSetPrivilege())
return false;
}
int ret = SafeNativeMethods.RegUnLoadKey((uint)Enum.Parse(typeof(structenums.baseKey), where.ToString()), name);
if (ret != 0)
{
LibraryLogging.Error("Unable to unload regkey {0} error:{1} {2}", name, ret, LastError(ret));
return false;
}
return true;
}
public static UIntPtr RegistryCreateKey(structenums.baseKey RootKey, string SubKey)
{
UIntPtr hKey = UIntPtr.Zero;
int Result = SafeNativeMethods.RegCreateKey(RootKey, SubKey, ref hKey);
if (Result != 0)
{
Console.WriteLine("RegCreateKey error:{0}", LastError(Result));
}
return hKey;
}
public static UIntPtr RegistryOpenKey(structenums.baseKey RootKey, string SubKey)
{
UIntPtr hKey = UIntPtr.Zero;
int Result = SafeNativeMethods.RegOpenKey(RootKey, SubKey, ref hKey);
if (Result != 0)
{
Console.WriteLine("RegOpenKey error:{0}", LastError(Result));
}
return hKey;
}
public static Boolean RegistryCloseKey(UIntPtr hKey)
{
int Result = SafeNativeMethods.RegCloseKey(hKey);
if (Result != 0)
{
Console.WriteLine("RegCloseKey error:{0}", LastError(Result));
return false;
}
return true;
}
public static Boolean RegistryCopyKey(UIntPtr hKey_src, string SubKey, UIntPtr hKey_dst)
{
int Result = SafeNativeMethods.RegCopyTree(hKey_src, SubKey, hKey_dst);
if (Result != 0)
{
Console.WriteLine("CopyKey error:{0}", LastError(Result));
return false;
}
return true;
}
public static Boolean RegistryDeleteTree(structenums.baseKey RootKey, string SubKey)
{
int Result = SafeNativeMethods.RegDeleteTree(RootKey, SubKey);
if (Result != 0)
{
Console.WriteLine("CopyKey error:{0}", LastError(Result));
return false;
}
return true;
}
/// <summary>
/// query if the domain is part of a domain tree in which the local computer is a member of
/// </summary>
/// <param name="domain"></param>
/// <returns></returns>
public static bool DomainMember(string domain)
{
if (String.IsNullOrEmpty(domain))
return false;
return !String.IsNullOrEmpty(GetDomainInfo(domain).DomainName);
}
internal static pInvokes.SafeNativeMethods.DOMAIN_CONTROLLER_INFO GetDomainInfo(string domain)
{
pInvokes.SafeNativeMethods.DOMAIN_CONTROLLER_INFO domainInfo = new pInvokes.SafeNativeMethods.DOMAIN_CONTROLLER_INFO();
IntPtr pDCI = IntPtr.Zero;
int ret = pInvokes.SafeNativeMethods.DsGetDcName(null, domain, 0, "", 0, out pDCI);
if (ret == 0)
{
domainInfo = (pInvokes.SafeNativeMethods.DOMAIN_CONTROLLER_INFO)Marshal.PtrToStructure(pDCI, typeof(pInvokes.SafeNativeMethods.DOMAIN_CONTROLLER_INFO));
}
else
{
LibraryLogging.Error("GetDomainInfo({0}) Error:{1} {2}", domain, ret, LastError(ret));
}
if (pDCI != IntPtr.Zero)
{
pInvokes.SafeNativeMethods.NetApiBufferFree(pDCI);
}
return domainInfo;
}
/// <summary>
/// get local machine domain membership as DNS name
/// </summary>
/// <returns></returns>
public static string GetMachineDomainMembershipEX()
{
return GetDomainInfo("").DomainName;
}
/// <summary>
/// get local machine domain membership as NETBIOS name
/// </summary>
/// <returns></returns>
public static string GetMachineDomainMembership()
{
IntPtr buffer = IntPtr.Zero;
pInvokes.SafeNativeMethods.WKSTA_INFO_100 wksta_info = new pInvokes.SafeNativeMethods.WKSTA_INFO_100();
int result = pInvokes.SafeNativeMethods.NetWkstaGetInfo(null, 100, out buffer);
if (result == 0)
{
wksta_info = (pInvokes.SafeNativeMethods.WKSTA_INFO_100)Marshal.PtrToStructure(buffer, typeof(pInvokes.SafeNativeMethods.WKSTA_INFO_100));
}
else
{
LibraryLogging.Error("GetMachineDomainMembership() Error:{0} {1}", result, LastError(result));
}
if (buffer != IntPtr.Zero)
{
pInvokes.SafeNativeMethods.NetApiBufferFree(buffer);
}
return wksta_info.lan_group;
}
/// <summary>
/// returns GetLastWin32Error as string
/// </summary>
/// <returns></returns>
public static string LastError(int error)
{
return new Win32Exception(error).Message;
}
/// <summary>
/// returns GetLastWin32Error as string
/// </summary>
/// <returns></returns>
public static string LastError()
{
return new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
}
}
<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <windows.h>
#include <credentialprovider.h>
#include <pGinaNativeLib.h>
#include "ClassFactory.h"
#include "TileUiTypes.h"
namespace pGina
{
namespace CredProv
{
class Provider;
class Credential : public IConnectableCredentialProviderCredential
{
public:
// IUnknown
IFACEMETHODIMP_(ULONG) AddRef();
IFACEMETHODIMP_(ULONG) Release();
IFACEMETHODIMP QueryInterface(__in REFIID riid, __deref_out void** ppv);
// ICredentialProviderCredential
IFACEMETHODIMP Advise(__in ICredentialProviderCredentialEvents* pcpce);
IFACEMETHODIMP UnAdvise();
IFACEMETHODIMP SetSelected(__out BOOL* pbAutoLogon);
IFACEMETHODIMP SetDeselected();
IFACEMETHODIMP GetFieldState(__in DWORD dwFieldID, __out CREDENTIAL_PROVIDER_FIELD_STATE* pcpfs, __out CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE* pcpfis);
IFACEMETHODIMP GetStringValue(__in DWORD dwFieldID, __deref_out PWSTR* ppwsz);
IFACEMETHODIMP GetBitmapValue(__in DWORD dwFieldID, __out HBITMAP* phbmp);
IFACEMETHODIMP GetCheckboxValue(__in DWORD dwFieldID, __out BOOL* pbChecked, __deref_out PWSTR* ppwszLabel);
IFACEMETHODIMP GetComboBoxValueCount(__in DWORD dwFieldID, __out DWORD* pcItems, __out_range(<,*pcItems) DWORD* pdwSelectedItem);
IFACEMETHODIMP GetComboBoxValueAt(__in DWORD dwFieldID, __in DWORD dwItem, __deref_out PWSTR* ppwszItem);
IFACEMETHODIMP GetSubmitButtonValue(__in DWORD dwFieldID, __out DWORD* pdwAdjacentTo);
IFACEMETHODIMP SetStringValue(__in DWORD dwFieldID, __in PCWSTR pwz);
IFACEMETHODIMP SetCheckboxValue(__in DWORD dwFieldID, __in BOOL bChecked);
IFACEMETHODIMP SetComboBoxSelectedValue(__in DWORD dwFieldID, __in DWORD dwSelectedItem);
IFACEMETHODIMP CommandLinkClicked(__in DWORD dwFieldID);
IFACEMETHODIMP GetSerialization(__out CREDENTIAL_PROVIDER_GET_SERIALIZATION_RESPONSE* pcpgsr, __out CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION* pcpcs,
__deref_out_opt PWSTR* ppwszOptionalStatusText, __out CREDENTIAL_PROVIDER_STATUS_ICON* pcpsiOptionalStatusIcon);
IFACEMETHODIMP ReportResult(__in NTSTATUS ntsStatus, __in NTSTATUS ntsSubstatus, __deref_out_opt PWSTR* ppwszOptionalStatusText,
__out CREDENTIAL_PROVIDER_STATUS_ICON* pcpsiOptionalStatusIcon);
IFACEMETHODIMP Connect(IQueryContinueWithStatus *pqcws);
IFACEMETHODIMP Disconnect();
Credential();
virtual ~Credential();
void Initialize(CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus, UI_FIELDS const& fields,
DWORD usageFlags, const wchar_t *username, const wchar_t *password);
virtual void ServiceStateChanged(bool newState);
typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
BOOL ISwin10();
private:
void ClearZeroAndFreeAnyPasswordFields(bool updateUi);
void ClearZeroAndFreeAnyTextFields(bool updateUi);
void ClearZeroAndFreeFields(CREDENTIAL_PROVIDER_FIELD_TYPE type, bool updateUi);
PWSTR FindUsernameValue();
PWSTR FindPasswordValue();
DWORD FindStatusId();
bool IsFieldDynamic(DWORD dwFieldID);
std::wstring GetTextForField(DWORD dwFieldID);
static DWORD WINAPI Thread_dialog(LPVOID lpParameter);
static void Thread_dialog_close(HANDLE thread);
private:
long m_referenceCount;
CREDENTIAL_PROVIDER_USAGE_SCENARIO m_usageScenario;
ICredentialProviderCredentialEvents * m_logonUiCallback;
UI_FIELDS *m_fields;
DWORD m_usageFlags;
pGina::Transactions::User::LoginResult m_loginResult;
HWND hdialog;
HANDLE hThread_dialog;
};
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
using pGina.Shared.Types;
using log4net;
namespace pGina.Plugin.MySQLAuth
{
class GroupRuleLoader
{
private static ILog m_logger = LogManager.GetLogger("MySQL GroupRuleLoader");
public static void SaveAuthzRules(List<GroupAuthzRule> rules)
{
List<string> strList = new List<string>();
foreach (GroupRule rule in rules)
{
strList.Add(rule.ToRegString());
}
Settings.Store.GroupAuthzRules = strList.ToArray();
}
public static void SaveGatewayRules(List<GroupGatewayRule> rules)
{
List<string> strList = new List<string>();
foreach (GroupRule rule in rules)
{
strList.Add(rule.ToRegString());
}
Settings.Store.GroupGatewayRules = strList.ToArray();
}
public static List<GroupAuthzRule> GetAuthzRules()
{
List<GroupAuthzRule> rules = new List<GroupAuthzRule>();
string[] strRules = Settings.Store.GroupAuthzRules;
foreach (string str in strRules)
{
GroupAuthzRule rule = GroupAuthzRule.FromRegString(str);
if (rule != null)
rules.Add(rule);
else
// Log error
m_logger.ErrorFormat("Unrecognized registry entry when loading authorization rule, ignoring: {0}", str);
}
return rules;
}
public static List<GroupGatewayRule> GetGatewayRules()
{
List<GroupGatewayRule> rules = new List<GroupGatewayRule>();
string[] strRules = Settings.Store.GroupGatewayRules;
foreach (string str in strRules)
{
GroupGatewayRule rule = GroupGatewayRule.FromRegString(str);
if( rule != null )
rules.Add(rule);
else
// Log error
m_logger.ErrorFormat("Unrecognized registry entry when loading gateway rule, ignoring: {0}", str);
}
return rules;
}
}
public abstract class GroupRule
{
public string Group { get { return m_group; } }
protected string m_group;
public Condition RuleCondition { get { return m_condition; } }
protected Condition m_condition;
public GroupRule( string grp, Condition c )
{
m_group = grp;
m_condition = c;
}
public bool RuleMatch(bool userIsMember)
{
switch( RuleCondition )
{
case Condition.ALWAYS: return true;
case Condition.MEMBER_OF: return userIsMember;
case Condition.NOT_MEMBER_OF: return !userIsMember;
default: return false;
}
}
public enum Condition { MEMBER_OF, NOT_MEMBER_OF, ALWAYS }
public abstract string ToRegString();
}
public class GroupAuthzRule : GroupRule
{
public bool AllowOnMatch { get { return m_allowOnMatch; } }
private bool m_allowOnMatch;
public GroupAuthzRule(bool allow) : base("", Condition.ALWAYS)
{
m_allowOnMatch = allow;
}
public GroupAuthzRule(string grp, Condition c, bool allow) : base(grp, c)
{
m_allowOnMatch = allow;
}
override public string ToRegString()
{
return string.Format("{0}\n{1}\n{2}", m_group, ((int)RuleCondition),(m_allowOnMatch ? "1" : "0") );
}
public static GroupAuthzRule FromRegString(string str)
{
string[] parts = Regex.Split(str, @"\n");
if (parts.Length == 3)
{
string grp = parts[0];
Condition c = (Condition)(Convert.ToInt32(parts[1]));
bool allow = Convert.ToInt32(parts[2]) != 0;
return new GroupAuthzRule(grp, c, allow);
}
return null;
}
override public string ToString()
{
string str = "";
switch( RuleCondition )
{
case Condition.ALWAYS:
str = "Always";
break;
case Condition.MEMBER_OF:
str = string.Format("If member of MySQL group \"{0}\"", m_group);
break;
case Condition.NOT_MEMBER_OF:
str = string.Format("If not member of MySQL group \"{0}\"", m_group);
break;
}
if (m_allowOnMatch) str += " allow.";
else str += " deny.";
return str;
}
}
public class GroupGatewayRule : GroupRule
{
public string LocalGroup { get { return m_localGroup; } }
private string m_localGroup;
public GroupGatewayRule(string localGroup) : base("", Condition.ALWAYS)
{
m_localGroup = localGroup;
}
public GroupGatewayRule(string grp, Condition c, string addTo) : base(grp,c)
{
m_localGroup = addTo;
}
public static GroupGatewayRule FromRegString(string str)
{
string[] parts = Regex.Split(str, @"\n");
if (parts.Length == 3)
{
string grp = parts[0];
Condition c = (Condition)(Convert.ToInt32(parts[1]));
string addTo = parts[2];
return new GroupGatewayRule(grp, c, addTo);
}
return null;
}
override public string ToRegString()
{
return m_group + "\n" + ((int)RuleCondition) + "\n" + m_localGroup;
}
override public string ToString()
{
string str = "";
switch (RuleCondition)
{
case Condition.ALWAYS:
str = "Always";
break;
case Condition.MEMBER_OF:
str = string.Format("If member of MySQL group \"{0}\"", m_group);
break;
case Condition.NOT_MEMBER_OF:
str = string.Format("If not member of MySQL group \"{0}\"", m_group);
break;
}
str += string.Format(" add to local group \"{0}\"", m_localGroup);
return str;
}
}
}
<file_sep>#include <WinSock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <Windows.h>
#include "libssh2.h"
using namespace std;
extern "C" {
__declspec(dllexport) int ssh_connect_and_pw_auth(const char *host, const char *port, const char *user, const char *password, char *errmsg, const int errlen)
{
int rc = 0;
WSADATA wsa_data;
LIBSSH2_SESSION *ssh_session = NULL;
ADDRINFO *addr_info = NULL;
SOCKET sock;
char *ssh_err_desc;
rc = WSAStartup(WINSOCK_VERSION, &wsa_data);
if (rc != 0) {
_snprintf_s(errmsg, errlen, _TRUNCATE, "WSAStartup failed");
return 1;
}
rc = getaddrinfo(host, port, NULL, &addr_info);
if (rc) {
_snprintf_s(errmsg, errlen, _TRUNCATE, "Host name resolution failure (%d)", rc);
if (addr_info != NULL)
freeaddrinfo(addr_info);
WSACleanup();
return 2;
}
// TODO support iteration over entire list returned by getaddrinfo
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET) {
_snprintf_s(errmsg, errlen, _TRUNCATE, "Failed to open socket");
freeaddrinfo(addr_info);
WSACleanup();
return 3;
}
rc = connect(sock, addr_info->ai_addr, (int)addr_info->ai_addrlen);
if (rc == SOCKET_ERROR) {
_snprintf_s(errmsg, errlen, _TRUNCATE, "Failed to open TCP connection");
closesocket(sock);
freeaddrinfo(addr_info);
WSACleanup();
return 4;
}
rc = libssh2_init(0);
if (rc) {
_snprintf_s(errmsg, errlen, _TRUNCATE, "libssh2 initialization failed (%d)\n", rc);
closesocket(sock);
freeaddrinfo(addr_info);
WSACleanup();
return 5;
}
ssh_session = libssh2_session_init();
if (ssh_session == NULL) {
_snprintf_s(errmsg, errlen, _TRUNCATE, "Failed to allocate SSH session data structure (libssh2_session_init returned %d)", rc);
closesocket(sock);
freeaddrinfo(addr_info);
WSACleanup();
return 6;
}
rc = libssh2_session_handshake(ssh_session, (int)sock);
if (rc) {
libssh2_session_last_error(ssh_session, &ssh_err_desc, NULL, 0);
_snprintf_s(errmsg, errlen, _TRUNCATE, "Failed SSH handshake (%d=%s)", rc, ssh_err_desc);
libssh2_session_free(ssh_session);
closesocket(sock);
freeaddrinfo(addr_info);
WSACleanup();
return 7;
}
rc = libssh2_userauth_password(ssh_session, user, password);
// now rc == 0 iff successful authentication; do cleanup and return this code.
if (rc) {
// retrieve error details (likely, incorrect password)
libssh2_session_last_error(ssh_session, &ssh_err_desc, NULL, 0);
_snprintf_s(errmsg, errlen, _TRUNCATE, "SSH authentication failed for user %s (%d: %s)", user, rc, ssh_err_desc);
}
libssh2_session_disconnect(ssh_session, "Finished");
libssh2_session_free(ssh_session);
closesocket(sock);
freeaddrinfo(addr_info);
WSACleanup();
return rc;
}
};<file_sep>/*
Copyright (c) 2018, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;
using System.DirectoryServices.Protocols;
using pGina.Shared.Settings;
using pGina.Plugin.Ldap;
using log4net;
namespace pGina.Plugin.Ldap
{
public partial class Configuration : Form
{
private ILog m_logger = LogManager.GetLogger("Ldap Configuration");
public Configuration()
{
InitializeComponent();
InitUI();
LoadSettings();
UpdateSslElements();
UpdateAuthenticationElements();
}
private void InitUI()
{
this.passwordAttributesDGV.RowHeadersVisible = true;
this.passwordAttributesDGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.passwordAttributesDGV.MultiSelect = false;
this.passwordAttributesDGV.AllowUserToAddRows = true;
this.passwordAttributesDGV.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = "Attribute Name",
DataPropertyName = "Name",
HeaderText = "Attribute Name",
AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
ReadOnly = false
});
DataGridViewComboBoxColumn combCol = new DataGridViewComboBoxColumn()
{
Name = "Method",
DataPropertyName = "Method",
HeaderText = "Method",
AutoSizeMode = DataGridViewAutoSizeColumnMode.None,
Width = 250,
DisplayMember = "Name",
ValueMember = "Method",
};
this.passwordAttributesDGV.DefaultValuesNeeded += passwordAttributesDGV_DefaultValuesNeeded;
combCol.Items.AddRange(AttribMethod.methods.Values.ToArray());
combCol.Items.AddRange(TimeMethod.methods.Values.ToArray());
this.passwordAttributesDGV.Columns.Add(combCol);
}
void passwordAttributesDGV_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
e.Row.Cells[1].Value = Methods.PLAIN;
}
private void LoadSettings()
{
string[] ldapHosts = Settings.Store.LdapHost;
string hosts = "";
for (int i = 0; i < ldapHosts.Count(); i++)
{
string host = ldapHosts[i];
if (i < ldapHosts.Count() - 1) hosts += host + " ";
else hosts += host;
}
ldapHostTextBox.Text = hosts;
int port = Settings.Store.LdapPort;
ldapPortTextBox.Text = Convert.ToString(port);
int timeout = Settings.Store.LdapTimeout;
timeoutTextBox.Text = Convert.ToString(timeout);
bool useSsl = Settings.Store.UseSsl;
useSslCheckBox.CheckState = useSsl ? CheckState.Checked : CheckState.Unchecked;
bool useTls = Settings.Store.UseTls;
useTlsCheckBox.CheckState = useTls ? CheckState.Checked : CheckState.Unchecked;
bool reqCert = Settings.Store.RequireCert;
validateServerCertCheckBox.CheckState = reqCert ? CheckState.Checked : CheckState.Unchecked;
string serverCertFile = Settings.Store.ServerCertFile;
sslCertFileTextBox.Text = serverCertFile;
string searchDn = Settings.Store.SearchDN;
searchDnTextBox.Text = searchDn;
string searchPw = Settings.Store.GetEncryptedSetting("SearchPW");
searchPassTextBox.Text = searchPw;
// Authentication tab
bool allowEmpty = Settings.Store.AllowEmptyPasswords;
this.allowEmptyPwCB.Checked = allowEmpty;
string dnPattern = Settings.Store.DnPattern;
dnPatternTextBox.Text = dnPattern;
bool doSearch = Settings.Store.DoSearch;
searchForDnCheckBox.CheckState = doSearch ? CheckState.Checked : CheckState.Unchecked;
string filter = Settings.Store.SearchFilter;
searchFilterTextBox.Text = filter;
bool useAuth = Settings.Store.UseAuthBindForAuthzAndGateway;
useAuthBindForAuthzAndGatewayCb.Checked = useAuth;
string[] searchContexts = Settings.Store.SearchContexts;
string ctxs = "";
for (int i = 0; i < searchContexts.Count(); i++)
{
string ctx = searchContexts[i];
if (i < searchContexts.Count() - 1) ctxs += ctx + "\r\n";
else ctxs += ctx;
}
searchContextsTextBox.Text = ctxs;
// AttribConverter Grid
string[] AttribConv = Settings.Store.AttribConv;
Column1.DataSource = AttribConvert.Attribs.ToArray();
dataGridView1.ColumnCount = 2;
for (int x = 0; x < AttribConv.Count(); x++)
{
string[] split = AttribConv[x].Split('\t');
if (split.Count() == 2)
{
split[0] = split[0].Trim();
split[1] = split[1].Trim();
if (!String.IsNullOrEmpty(split[0]) && !String.IsNullOrEmpty(split[1]))
{
if (AttribConvert.Attribs.Contains(split[0]))
//if (Array.Exists(WinValues(), element => element == split[0]))
{
int index = AttribConvert.Attribs.IndexOf(split[0]);
//int index = Array.FindIndex(WinValues(), item => item == split[0]);
DataGridViewRow row = new DataGridViewRow();
DataGridViewComboBoxCell CellSample = new DataGridViewComboBoxCell();
CellSample.DataSource = AttribConvert.Attribs.ToArray(); // list of the string items that I want to insert in ComboBox.
CellSample.Value = AttribConvert.Attribs[index]; // default value for the ComboBox
row.Cells.Add(CellSample);
row.Cells.Add(new DataGridViewTextBoxCell()
{
Value = split[1]
});
dataGridView1.Rows.Add(row);
}
}
}
}
/////////////// Authorization tab /////////////////
this.authzRuleMemberComboBox.SelectedIndex = 0;
this.authzRuleActionComboBox.SelectedIndex = 0;
this.authzRuleScope.SelectedIndex = 0;
this.authzDefaultAllowRB.Checked = Settings.Store.AuthzDefault;
this.authzDefaultDenyRB.Checked = !(bool)Settings.Store.AuthzDefault;
this.authzRequireAuthCB.Checked = Settings.Store.AuthzRequireAuth;
this.authzAllowOnErrorCB.Checked = Settings.Store.AuthzAllowOnError;
List<GroupAuthzRule> lst = GroupRuleLoader.GetAuthzRules();
foreach (GroupAuthzRule rule in lst)
this.authzRulesListBox.Items.Add(rule);
///////////////// Gateway tab /////////////////
this.gatewayRuleGroupMemberCB.SelectedIndex = 0;
this.gatewayRuleScope.SelectedIndex = 0;
List<GroupGatewayRule> gwLst = GroupRuleLoader.GetGatewayRules();
foreach (GroupGatewayRule rule in gwLst)
this.gatewayRulesListBox.Items.Add(rule);
////////////// Change Password tab ///////////////
List<AttributeEntry> attribs = CPAttributeSettings.Load();
foreach (AttributeEntry entry in attribs)
this.passwordAttributesDGV.Rows.Add( entry.Name, entry.Method );
}
private void sslCertFileBrowseButton_Click(object sender, EventArgs e)
{
DialogResult result;
string fileName;
using( OpenFileDialog dlg = new OpenFileDialog() )
{
result = dlg.ShowDialog();
fileName = dlg.FileName;
}
if( result == DialogResult.OK )
{
sslCertFileTextBox.Text = fileName;
}
}
private void useSslCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (this.useSslCheckBox.Checked)
this.useTlsCheckBox.Checked = false;
UpdateSslElements();
}
private void useTlsCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (this.useTlsCheckBox.Checked)
this.useSslCheckBox.Checked = false;
UpdateSslElements();
}
private void UpdateSslElements()
{
if (validateServerCertCheckBox.Checked)
{
sslCertFileTextBox.Enabled = true;
sslCertFileBrowseButton.Enabled = true;
}
else if (validateServerCertCheckBox.CheckState == CheckState.Unchecked)
{
sslCertFileTextBox.Enabled = false;
sslCertFileBrowseButton.Enabled = false;
}
if (!useSslCheckBox.Checked && !useTlsCheckBox.Checked)
{
validateServerCertCheckBox.Enabled = false;
sslCertFileTextBox.Enabled = false;
sslCertFileBrowseButton.Enabled = false;
}
else
{
validateServerCertCheckBox.Enabled = true;
}
}
private void UpdateAuthenticationElements()
{
if (searchForDnCheckBox.Checked)
{
searchFilterTextBox.Enabled = true;
searchContextsTextBox.Enabled = true;
dnPatternTextBox.Enabled = false;
}
else
{
searchFilterTextBox.Enabled = false;
searchContextsTextBox.Enabled = false;
dnPatternTextBox.Enabled = true;
}
}
private void validateServerCertCheckBox_CheckedChanged(object sender, EventArgs e)
{
UpdateSslElements();
}
private void searchForDnCheckBox_CheckedChanged(object sender, EventArgs e)
{
UpdateAuthenticationElements();
}
private void cancelButton_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
private void saveButton_Click(object sender, EventArgs e)
{
if (ValidateInput())
{
StoreSettings();
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
}
private bool ValidateInput()
{
if (ldapHostTextBox.Text.Trim().Length == 0)
{
MessageBox.Show("Please provide at least one LDAP host");
return false;
}
try
{
int port = Convert.ToInt32(ldapPortTextBox.Text.Trim());
if (port <= 0) throw new FormatException();
}
catch (FormatException)
{
MessageBox.Show("The LDAP port number must be a positive integer > 0.");
return false;
}
try
{
int timeout = Convert.ToInt32(timeoutTextBox.Text.Trim());
if (timeout <= 0) throw new FormatException();
}
catch (FormatException)
{
MessageBox.Show("The timout be a positive integer > 0.");
return false;
}
if (validateServerCertCheckBox.CheckState == CheckState.Checked && sslCertFileTextBox.Text.Trim().Equals("MATCH"))
{
return true;
}
if (validateServerCertCheckBox.CheckState == CheckState.Checked && sslCertFileTextBox.Text.Trim().Length > 0 && !File.Exists(sslCertFileTextBox.Text.Trim()))
{
MessageBox.Show("SSL certificate file does not exist."
+ "Please select a valid certificate file.");
return false;
}
// TODO: Make sure that other input is valid.
return true;
}
private void StoreSettings()
{
Settings.Store.LdapHost = Regex.Split(ldapHostTextBox.Text.Trim(), @"\s+");
Settings.Store.LdapPort = Convert.ToInt32(ldapPortTextBox.Text.Trim());
Settings.Store.LdapTimeout = Convert.ToInt32(timeoutTextBox.Text.Trim());
Settings.Store.UseSsl = (useSslCheckBox.CheckState == CheckState.Checked);
Settings.Store.UseTls = (useTlsCheckBox.CheckState == CheckState.Checked);
Settings.Store.RequireCert = (validateServerCertCheckBox.CheckState == CheckState.Checked);
Settings.Store.ServerCertFile = sslCertFileTextBox.Text.Trim();
Settings.Store.UseAuthBindForAuthzAndGateway = (useAuthBindForAuthzAndGatewayCb.CheckState == CheckState.Checked);
Settings.Store.SearchDN = searchDnTextBox.Text.Trim();
Settings.Store.SetEncryptedSetting("SearchPW", searchPassTextBox.Text);
// Authentication
Settings.Store.AllowEmptyPasswords = this.allowEmptyPwCB.Checked;
Settings.Store.DnPattern = dnPatternTextBox.Text.Trim();
Settings.Store.DoSearch = (searchForDnCheckBox.CheckState == CheckState.Checked);
Settings.Store.SearchFilter = searchFilterTextBox.Text.Trim();
Settings.Store.SearchContexts = Regex.Split(searchContextsTextBox.Text.Trim(), @"\s*\r?\n\s*");
Settings.Store.AuthzDefault = this.authzDefaultAllowRB.Checked;
List<string> AttribConv = new List<string>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0].Value != null && row.Cells[1].Value != null)
{
AttribConv.Add(row.Cells[0].Value.ToString() + "\t" + row.Cells[1].Value.ToString().Trim());
}
}
if (AttribConv.Count > 0)
Settings.Store.AttribConv = AttribConv.ToArray();
else
Settings.Store.AttribConv = new string[] { };
// Authorization
Settings.Store.AuthzRequireAuth = this.authzRequireAuthCB.Checked;
Settings.Store.AuthzAllowOnError = this.authzAllowOnErrorCB.Checked;
Settings.Store.AuthzDefault = this.authzDefaultAllowRB.Checked;
List<GroupAuthzRule> lst = new List<GroupAuthzRule>();
foreach (Object item in this.authzRulesListBox.Items)
{
lst.Add(item as GroupAuthzRule);
m_logger.DebugFormat("Saving rule: {0}", item);
}
string SaveAuthzRules_ret = GroupRuleLoader.SaveAuthzRules(lst);
if (!string.IsNullOrEmpty(SaveAuthzRules_ret))
{
MessageBox.Show("There was an error in saving your authorization rules.\n" + SaveAuthzRules_ret);
}
// Gateway
List<GroupGatewayRule> gwList = new List<GroupGatewayRule>();
foreach (Object item in this.gatewayRulesListBox.Items)
{
gwList.Add(item as GroupGatewayRule);
m_logger.DebugFormat("Saving rule: {0}", item);
}
string SaveGatewayRules_ret = GroupRuleLoader.SaveGatewayRules(gwList);
if (!string.IsNullOrEmpty(SaveGatewayRules_ret))
{
MessageBox.Show("There was an error in saving your gateway rules.\n" + SaveGatewayRules_ret);
}
// Change Password
List<AttributeEntry> entries = new List<AttributeEntry>();
foreach (DataGridViewRow row in this.passwordAttributesDGV.Rows)
{
if (row.Cells[0].Value != null && row.Cells[1].Value != null)
{
string attribName = row.Cells[0].Value.ToString();
if (!string.IsNullOrEmpty(attribName))
{
AttributeEntry entry = new AttributeEntry
{
Name = attribName,
Method = (Methods)(row.Cells[1].Value)
};
entries.Add(entry);
}
}
}
CPAttributeSettings.Save(entries);
}
private void showPwCB_CheckedChanged(object sender, EventArgs e)
{
this.searchPassTextBox.UseSystemPasswordChar = !this.showPwCB.Checked;
}
private void authzRuleAddButton_Click(object sender, EventArgs e)
{
string path = this.authzRulePathTB.Text.Trim();
if (string.IsNullOrEmpty(path))
{
MessageBox.Show("Please enter a DN");
return;
}
int idx = this.authzRuleMemberComboBox.SelectedIndex;
GroupRule.Condition c;
if (idx == 0) c = GroupRule.Condition.MEMBER_OF;
else if (idx == 1) c = GroupRule.Condition.NOT_MEMBER_OF;
else
throw new Exception("Unrecognized option in authzRuleAddButton_Click");
idx = this.authzRuleActionComboBox.SelectedIndex;
bool allow;
if (idx == 0) allow = true; // allow
else if (idx == 1) allow = false; // deny
else
throw new Exception("Unrecognized action option in authzRuleAddButton_Click");
string filter = this.authzRuleFilter.Text.Trim();
if (string.IsNullOrEmpty(path))
{
MessageBox.Show("Please enter a search filter");
return;
}
SearchScope search = (SearchScope)this.authzRuleScope.SelectedIndex;
GroupAuthzRule rule = new GroupAuthzRule(path, c, allow, filter, search);
this.authzRulesListBox.Items.Add(rule);
}
private void gatewayRuleAddButton_Click(object sender, EventArgs e)
{
string localGrp = this.gatewayRuleLocalGroupTB.Text.Trim();
if (string.IsNullOrEmpty(localGrp))
{
MessageBox.Show("Please enter a group name");
return;
}
int idx = this.gatewayRuleGroupMemberCB.SelectedIndex;
GroupRule.Condition c;
if (idx == 0) c = GroupRule.Condition.MEMBER_OF;
else if (idx == 1) c = GroupRule.Condition.NOT_MEMBER_OF;
else if (idx == 2) c = GroupRule.Condition.ALWAYS;
else
throw new Exception("Unrecognized option in addGatewayGroupRuleButton_Click");
if (c == GroupRule.Condition.ALWAYS)
{
this.gatewayRulesListBox.Items.Add(new GroupGatewayRule(localGrp));
}
else
{
string path = this.gatwayRulePathTB.Text.Trim();
if (string.IsNullOrEmpty(path))
{
MessageBox.Show("Please enter a DN");
return;
}
string filter = this.gatewayRuleFilter.Text;
if (string.IsNullOrEmpty(filter))
{
MessageBox.Show("Please enter a searh filter");
return;
}
SearchScope scope = (SearchScope)this.gatewayRuleScope.SelectedIndex;
this.gatewayRulesListBox.Items.Add(new GroupGatewayRule(path, c, localGrp, filter, scope));
}
}
private void gatewayRuleGroupMemberCB_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.gatewayRuleGroupMemberCB.SelectedIndex == 2)
{
this.gatwayRulePathTB.Enabled = false;
this.gatwayRulePathTB.Text = "";
this.gatewayRuleFilter.Enabled = false;
this.gatewayRuleFilter.Text = "";
this.gatewayRuleScope.Enabled = false;
this.gatewayRuleScope.SelectedIndex = 0;
}
else
{
this.gatwayRulePathTB.Enabled = true;
this.gatewayRuleFilter.Enabled = true;
this.gatewayRuleScope.Enabled = true;
}
}
private void gatewayRuleDeleteBtn_Click(object sender, EventArgs e)
{
int idx = this.gatewayRulesListBox.SelectedIndex;
if( idx >= 0 && idx < this.gatewayRulesListBox.Items.Count )
this.gatewayRulesListBox.Items.RemoveAt(idx);
}
private void authzRuleDeleteBtn_Click(object sender, EventArgs e)
{
int idx = this.authzRulesListBox.SelectedIndex;
if (idx >= 0 && idx < this.authzRulesListBox.Items.Count)
this.authzRulesListBox.Items.RemoveAt(idx);
}
private void authzRuleUpBtn_Click(object sender, EventArgs e)
{
int idx = this.authzRulesListBox.SelectedIndex;
if (idx > 0 && idx < this.authzRulesListBox.Items.Count)
{
object item = this.authzRulesListBox.Items[idx];
this.authzRulesListBox.Items.RemoveAt(idx);
this.authzRulesListBox.Items.Insert(idx-1,item);
this.authzRulesListBox.SelectedIndex = idx - 1;
}
}
private void authzRuleDownBtn_Click(object sender, EventArgs e)
{
int idx = this.authzRulesListBox.SelectedIndex;
if (idx >= 0 && idx < this.authzRulesListBox.Items.Count - 1)
{
object item = this.authzRulesListBox.Items[idx];
this.authzRulesListBox.Items.RemoveAt(idx);
this.authzRulesListBox.Items.Insert(idx + 1, item);
this.authzRulesListBox.SelectedIndex = idx + 1;
}
}
private void gatewayRulesListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.gatewayRulesListBox.SelectedItems.Count == 0)
{
this.gatewayRuleDeleteBtn.Enabled = false;
}
else
{
this.gatewayRuleDeleteBtn.Enabled = true;
}
}
private void authzRulesListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.authzRulesListBox.SelectedItems.Count == 0)
{
this.authzRuleDeleteBtn.Enabled = false;
}
else
{
this.authzRuleDeleteBtn.Enabled = true;
}
}
private void useAuthBindForAuthzAndGatewayCb_CheckedChanged(object sender, EventArgs e)
{
if (useAuthBindForAuthzAndGatewayCb.Checked)
{
searchDnTextBox.Enabled = false;
searchPassTextBox.Enabled = false;
}
else
{
searchDnTextBox.Enabled = true;
searchPassTextBox.Enabled = true;
}
}
private void Btn_help(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/ldap.html");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace pGina.Plugin.HttpAuth
{
public class UInfo
{
public string whyCannotLogin;
public string uname;
public string fullName;
public string email;
public string[] groups;
public static UInfo parseResponse(string res)
{
UInfo u = new UInfo();
using (StringReader strReader = new StringReader(res))
{
// reason why could not login (empty = can login)
u.whyCannotLogin = strReader.ReadLine();
u.uname = strReader.ReadLine();
if (u.uname == null)
{
throw new Exception("Bad response arrived: " + res);
}
u.fullName = strReader.ReadLine();
u.email = strReader.ReadLine();
u.groups = strReader.ReadLine().Split(';');
if (u.groups.Length == 1 && u.groups[0].Contains(";"))
{
throw new Exception("Bad response arrived (groups wrong): " + res);
}
}
return u;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Abstractions.WindowsApi;
namespace Abstractions.Windows
{
public static class OsInfo
{
public static bool IsVistaOrLater()
{
OperatingSystem sys = System.Environment.OSVersion;
if (sys.Platform == PlatformID.Win32NT &&
sys.Version.Major >= 6)
return true;
return false;
}
public static bool IsWindows()
{
OperatingSystem sys = System.Environment.OSVersion;
if (sys.Platform == PlatformID.Win32NT ||
sys.Platform == PlatformID.Win32S ||
sys.Platform == PlatformID.Win32Windows ||
sys.Platform == PlatformID.WinCE)
return true;
return false;
}
public static bool Is64Bit()
{
// Is this equivalent?: return Environment.Is64BitOperatingSystem;
return IntPtr.Size == 8;
}
public static string OsDescription()
{
pInvokes.structenums.OSVERSIONINFOW ver = pInvokes.VersionsInfo();
return string.Format("OS {0}.{1}.{2} Runtime: {3} Culture: {4}", ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber, System.Environment.Version, CultureInfo.InstalledUICulture.EnglishName);
}
public static bool Is7OrLater()
{
pInvokes.structenums.OSVERSIONINFOW ver = pInvokes.VersionsInfo();
if (ver.dwMajorVersion == 6 && ver.dwMinorVersion >= 1)
{
return true;
}
if (ver.dwMajorVersion > 6)
{
return true;
}
return false;
}
public static bool Is8OrLater()
{
pInvokes.structenums.OSVERSIONINFOW ver = pInvokes.VersionsInfo();
if (ver.dwMajorVersion == 6 && ver.dwMinorVersion >= 2)
{
return true;
}
if (ver.dwMajorVersion > 6)
{
return true;
}
return false;
}
public static bool Is8oneOrLater()
{
pInvokes.structenums.OSVERSIONINFOW ver = pInvokes.VersionsInfo();
if (ver.dwMajorVersion == 6 && ver.dwMinorVersion >= 3)
{
return true;
}
if (ver.dwMajorVersion > 6)
{
return true;
}
return false;
}
public static bool Is10OrLater()
{
pInvokes.structenums.OSVERSIONINFOW ver = pInvokes.VersionsInfo();
if (ver.dwMajorVersion == 6 && ver.dwMinorVersion >= 4)
{
return true;
}
if (ver.dwMajorVersion > 6)
{
return true;
}
return false;
}
}
}
<file_sep>//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Gina.rc
//
#define IDB_BITMAP1 101
#define IDB_PGINA_LOGO 101
#define IDD_LOGGEDOUT_SAS 102
#define IDC_LOGO 1001
#define IDC_MOTD 1002
#define IDC_USERNAME_LBL 1003
#define IDC_PASSWORD_LBL 1004
#define IDC_USERNAME_TXT 1005
#define IDC_PASSWORD_TXT 1006
#define IDC_EMERGENCY_ESCAPE_HATCH 1007
#define IDC_LOGIN_BUTTON 1008
#define IDC_SHUTDOWN 1009
#define IDC_SPECIAL 1010
#define IDC_STATUS 1011
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 103
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1012
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <Windows.h>
#include <WinWlx.h>
#include "Winlogon.h"
namespace pGina
{
namespace GINA
{
// This static class allows for the creation of a WLX_DISPATCH_VERSION_1_4 table
// that routes back to the Winlogon interface of choice. Useful when you have to
// load a GINA and want to re-route some of it's calls into winlogon through you're
// own methods.
class WinlogonRouter
{
public:
static void Interface(WinlogonInterface *pIface) { s_interface = pIface; }
static WinlogonInterface * Interface() { return s_interface; }
static PWLX_DISPATCH_VERSION_1_4 DispatchTable() { return &s_table; }
private:
// No instansiation!
WinlogonRouter() {}
private:
// Static methods for dispatching back into our winlogon interface from the
// table we provide to our chained GINA.
static void WlxUseCtrlAltDel(HANDLE hWlx);
static void WlxSetContextPointer(HANDLE hWlx, void *newContext);
static void WlxSasNotify(HANDLE hWlx, DWORD sas);
static bool WlxSetTimeout(HANDLE hWlx, DWORD newTimeout);
static int WlxAssignShellProtection(HANDLE hWlx, HANDLE token, HANDLE process, HANDLE thread);
static int WlxMessageBox(HANDLE hWlx, HWND owner, LPWSTR text, LPWSTR title, UINT style);
static int WlxDialogBox(HANDLE hWlx, HANDLE hInst, LPWSTR lpszTemplate, HWND hwndOwner, DLGPROC dlgprc);
static int WlxDialogBoxParam(HANDLE hWlx, HANDLE hInst, LPWSTR lpszTemplate, HWND hwndOwner, DLGPROC dlgprc, LPARAM dwInitParam);
static int WlxDialogBoxIndirect(HANDLE hWlx, HANDLE hInst, LPCDLGTEMPLATE hDialogTemplate, HWND hwndOwner, DLGPROC dlgprc);
static int WlxDialogBoxIndirectParam(HANDLE hWlx, HANDLE hInst, LPCDLGTEMPLATE hDialogTemplate, HWND hwndOwner, DLGPROC dlgprc, LPARAM dwInitParam);
static int WlxSwitchDesktopToUser(HANDLE hWlx);
static int WlxSwitchDesktopToWinlogon(HANDLE hWlx);
static int WlxChangePasswordNotify(HANDLE hWlx, PWLX_MPR_NOTIFY_INFO pMprInfo, DWORD dwChangeInfo);
static bool WlxGetSourceDesktop(HANDLE hWlx, PWLX_DESKTOP *ppDesktop);
static bool WlxSetReturnDesktop(HANDLE hWlx, PWLX_DESKTOP pDesktop);
static bool WlxCreateUserDesktop(HANDLE hWlx, HANDLE hToken, DWORD Flags, PWSTR pszDesktopName, PWLX_DESKTOP *ppDesktop);
static int WlxChangePasswordNotifyEx(HANDLE hWlx, PWLX_MPR_NOTIFY_INFO pMprInfo, DWORD dwChangeInfo, PWSTR ProviderName, PVOID Reserved);
static bool WlxCloseUserDesktop(HANDLE hWlx, PWLX_DESKTOP pDesktop, HANDLE hToken);
static bool WlxSetOption(HANDLE hWlx, DWORD Option, ULONG_PTR Value, ULONG_PTR *OldValue);
static bool WlxGetOption(HANDLE hWlx, DWORD Option, ULONG_PTR *Value);
static void WlxWin31Migrate(HANDLE hWlx);
static int WlxQueryTerminalServicesData(HANDLE hWlx, PWLX_TERMINAL_SERVICES_DATA pTSData, WCHAR *UserName, WCHAR *Domain);
// These don't have an hWlx param for getting back to us directly, we have to use our global :/
static bool WlxQueryClientCredentials(PWLX_CLIENT_CREDENTIALS_INFO_V1_0 pCred);
static bool WlxQueryInetConnectorCredentials(PWLX_CLIENT_CREDENTIALS_INFO_V1_0 pCred);
static bool WlxDisconnect();
static int WlxQueryConsoleSwitchCredentials(PWLX_CONSOLESWITCH_CREDENTIALS_INFO_V1_0 pCred);
static bool WlxQueryTsLogonCredentials(PWLX_CLIENT_CREDENTIALS_INFO_V2_0 pCred);
private:
static WinlogonInterface * s_interface;
static WLX_DISPATCH_VERSION_1_4 s_table;
};
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include "WinlogonRouter.h"
namespace pGina
{
namespace GINA
{
WinlogonInterface * WinlogonRouter::s_interface = NULL;
WLX_DISPATCH_VERSION_1_4 WinlogonRouter::s_table =
{
(PWLX_USE_CTRL_ALT_DEL) &WinlogonRouter::WlxUseCtrlAltDel,
(PWLX_SET_CONTEXT_POINTER) &WinlogonRouter::WlxSetContextPointer,
(PWLX_SAS_NOTIFY) &WinlogonRouter::WlxSasNotify,
(PWLX_SET_TIMEOUT) &WinlogonRouter::WlxSetTimeout,
(PWLX_ASSIGN_SHELL_PROTECTION) &WinlogonRouter::WlxAssignShellProtection,
(PWLX_MESSAGE_BOX) &WinlogonRouter::WlxMessageBox,
(PWLX_DIALOG_BOX) &WinlogonRouter::WlxDialogBox,
(PWLX_DIALOG_BOX_PARAM) &WinlogonRouter::WlxDialogBoxParam,
(PWLX_DIALOG_BOX_INDIRECT) &WinlogonRouter::WlxDialogBoxIndirect,
(PWLX_DIALOG_BOX_INDIRECT_PARAM) &WinlogonRouter::WlxDialogBoxIndirectParam,
(PWLX_SWITCH_DESKTOP_TO_USER) &WinlogonRouter::WlxSwitchDesktopToUser,
(PWLX_SWITCH_DESKTOP_TO_WINLOGON) &WinlogonRouter::WlxSwitchDesktopToWinlogon,
(PWLX_CHANGE_PASSWORD_NOTIFY) &WinlogonRouter::WlxChangePasswordNotify,
(PWLX_GET_SOURCE_DESKTOP) &WinlogonRouter::WlxGetSourceDesktop,
(PWLX_SET_RETURN_DESKTOP) &WinlogonRouter::WlxSetReturnDesktop,
(PWLX_CREATE_USER_DESKTOP) &WinlogonRouter::WlxCreateUserDesktop,
(PWLX_CHANGE_PASSWORD_NOTIFY_EX) &WinlogonRouter::WlxChangePasswordNotifyEx,
(PWLX_CLOSE_USER_DESKTOP) &WinlogonRouter::WlxCloseUserDesktop,
(PWLX_SET_OPTION) &WinlogonRouter::WlxSetOption,
(PWLX_GET_OPTION) &WinlogonRouter::WlxGetOption,
(PWLX_WIN31_MIGRATE) &WinlogonRouter::WlxWin31Migrate,
(PWLX_QUERY_CLIENT_CREDENTIALS) &WinlogonRouter::WlxQueryClientCredentials,
(PWLX_QUERY_IC_CREDENTIALS) &WinlogonRouter::WlxQueryInetConnectorCredentials,
(PWLX_DISCONNECT) &WinlogonRouter::WlxDisconnect,
(PWLX_QUERY_TERMINAL_SERVICES_DATA) &WinlogonRouter::WlxQueryTerminalServicesData,
(PWLX_QUERY_CONSOLESWITCH_CREDENTIALS) &WinlogonRouter::WlxQueryConsoleSwitchCredentials,
(PWLX_QUERY_TS_LOGON_CREDENTIALS) &WinlogonRouter::WlxQueryTsLogonCredentials,
};
/*static*/
void WinlogonRouter::WlxUseCtrlAltDel(HANDLE hWlx)
{
// We could require that the user who'se passed our table to someone
// also pass a ptr to s_interface as hWlx. Instead, we ignore hWlx
// and always use s_interface. Simpler that way...
if(s_interface)
s_interface->WlxUseCtrlAltDel();
}
/*static*/
void WinlogonRouter::WlxSetContextPointer(HANDLE hWlx, void *newContext)
{
if(s_interface)
s_interface->WlxSetContextPointer(newContext);
}
/*static*/
void WinlogonRouter::WlxSasNotify(HANDLE hWlx, DWORD sas)
{
if(s_interface)
s_interface->WlxSasNotify(sas);
}
/*static*/
bool WinlogonRouter::WlxSetTimeout(HANDLE hWlx, DWORD newTimeout)
{
if(!s_interface) return false;
return s_interface->WlxSetTimeout(newTimeout);
}
/*static*/
int WinlogonRouter::WlxAssignShellProtection(HANDLE hWlx, HANDLE token, HANDLE process, HANDLE thread)
{
if(!s_interface) return -1;
return s_interface->WlxAssignShellProtection(token, process, thread);
}
/*static*/
int WinlogonRouter::WlxMessageBox(HANDLE hWlx, HWND owner, LPWSTR text, LPWSTR title, UINT style)
{
if(!s_interface) return -1;
return s_interface->WlxMessageBox(owner, text, title, style);
}
/*static*/
int WinlogonRouter::WlxDialogBox(HANDLE hWlx, HANDLE hInst, LPWSTR lpszTemplate, HWND hwndOwner, DLGPROC dlgprc)
{
if(!s_interface) return -1;
return s_interface->WlxDialogBox(hInst, lpszTemplate, hwndOwner, dlgprc);
}
/*static*/
int WinlogonRouter::WlxDialogBoxParam(HANDLE hWlx, HANDLE hInst, LPWSTR lpszTemplate, HWND hwndOwner, DLGPROC dlgprc, LPARAM dwInitParam)
{
if(!s_interface) return -1;
return s_interface->WlxDialogBoxParam(hInst, lpszTemplate, hwndOwner, dlgprc, dwInitParam);
}
/*static*/
int WinlogonRouter::WlxDialogBoxIndirect(HANDLE hWlx, HANDLE hInst, LPCDLGTEMPLATE hDialogTemplate, HWND hwndOwner, DLGPROC dlgprc)
{
if(!s_interface) return -1;
return s_interface->WlxDialogBoxIndirect(hInst, hDialogTemplate, hwndOwner, dlgprc);
}
/*static*/
int WinlogonRouter::WlxDialogBoxIndirectParam(HANDLE hWlx, HANDLE hInst, LPCDLGTEMPLATE hDialogTemplate, HWND hwndOwner, DLGPROC dlgprc, LPARAM dwInitParam)
{
if(!s_interface) return -1;
return s_interface->WlxDialogBoxIndirectParam(hInst, hDialogTemplate, hwndOwner, dlgprc, dwInitParam);
}
/*static*/
int WinlogonRouter::WlxSwitchDesktopToUser(HANDLE hWlx)
{
if(!s_interface) return -1;
return s_interface->WlxSwitchDesktopToUser();
}
/*static*/
int WinlogonRouter::WlxSwitchDesktopToWinlogon(HANDLE hWlx)
{
if(!s_interface) return -1;
return s_interface->WlxSwitchDesktopToWinlogon();
}
/*static*/
int WinlogonRouter::WlxChangePasswordNotify(HANDLE hWlx, PWLX_MPR_NOTIFY_INFO pMprInfo, DWORD dwChangeInfo)
{
if(!s_interface) return -1;
return s_interface->WlxChangePasswordNotify(pMprInfo, dwChangeInfo);
}
/*static*/
bool WinlogonRouter::WlxGetSourceDesktop(HANDLE hWlx, PWLX_DESKTOP *ppDesktop)
{
if(!s_interface) return false;
return s_interface->WlxGetSourceDesktop(ppDesktop);
}
/*static*/
bool WinlogonRouter::WlxSetReturnDesktop(HANDLE hWlx, PWLX_DESKTOP pDesktop)
{
if(!s_interface) return false;
return s_interface->WlxSetReturnDesktop(pDesktop);
}
/*static*/
bool WinlogonRouter::WlxCreateUserDesktop(HANDLE hWlx, HANDLE hToken, DWORD Flags, PWSTR pszDesktopName, PWLX_DESKTOP *ppDesktop)
{
if(!s_interface) return false;
return s_interface->WlxCreateUserDesktop(hToken, Flags, pszDesktopName, ppDesktop);
}
/*static*/
int WinlogonRouter::WlxChangePasswordNotifyEx(HANDLE hWlx, PWLX_MPR_NOTIFY_INFO pMprInfo, DWORD dwChangeInfo, PWSTR ProviderName, PVOID Reserved)
{
if(!s_interface) return -1;
return s_interface->WlxChangePasswordNotifyEx(pMprInfo, dwChangeInfo, ProviderName, Reserved);
}
/*static*/
bool WinlogonRouter::WlxCloseUserDesktop(HANDLE hWlx, PWLX_DESKTOP pDesktop, HANDLE hToken)
{
if(!s_interface) return false;
return s_interface->WlxCloseUserDesktop(pDesktop, hToken);
}
/*static*/
bool WinlogonRouter::WlxSetOption(HANDLE hWlx, DWORD Option, ULONG_PTR Value, ULONG_PTR *OldValue)
{
if(!s_interface) return false;
return s_interface->WlxSetOption(Option, Value, OldValue);
}
/*static*/
bool WinlogonRouter::WlxGetOption(HANDLE hWlx, DWORD Option, ULONG_PTR *Value)
{
if(!s_interface) return false;
return s_interface->WlxGetOption(Option, Value);
}
/*static*/
void WinlogonRouter::WlxWin31Migrate(HANDLE hWlx)
{
s_interface->WlxWin31Migrate();
}
/*static*/
int WinlogonRouter::WlxQueryTerminalServicesData(HANDLE hWlx, PWLX_TERMINAL_SERVICES_DATA pTSData, WCHAR *UserName, WCHAR *Domain)
{
if(!s_interface) return -1;
return s_interface->WlxQueryTerminalServicesData(pTSData, UserName, Domain);
}
// These don't have an hWlx param for getting back to us directly, we have to use a /*static*/ global :/
/*static*/
bool WinlogonRouter::WlxQueryClientCredentials(PWLX_CLIENT_CREDENTIALS_INFO_V1_0 pCred)
{
if(!s_interface) return false;
return s_interface->WlxQueryClientCredentials(pCred);
}
/*static*/
bool WinlogonRouter::WlxQueryInetConnectorCredentials(PWLX_CLIENT_CREDENTIALS_INFO_V1_0 pCred)
{
if(!s_interface) return false;
return s_interface->WlxQueryInetConnectorCredentials(pCred);
}
/*static*/
bool WinlogonRouter::WlxDisconnect()
{
if(!s_interface) return false;
return s_interface->WlxDisconnect();
}
/*static*/
int WinlogonRouter::WlxQueryConsoleSwitchCredentials(PWLX_CONSOLESWITCH_CREDENTIALS_INFO_V1_0 pCred)
{
if(!s_interface) return -1;
return s_interface->WlxQueryConsoleSwitchCredentials(pCred);
}
/*static*/
bool WinlogonRouter::WlxQueryTsLogonCredentials(PWLX_CLIENT_CREDENTIALS_INFO_V2_0 pCred)
{
if(!s_interface) return false;
return s_interface->WlxQueryTsLogonCredentials(pCred);
}
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include "GinaWrapper.h"
namespace pGina
{
namespace GINA
{
GinaWrapper::GinaWrapper(const wchar_t * dll) :
Gina(NULL),
m_ginaContext(0),
m_dll(0),
m_dllVersion(0),
m_negotiated(false),
m_initialized(false),
m_pfWlxNegotiate(0),
m_pfWlxInitialize(0),
m_pfWlxDisplaySASNotice(0),
m_pfWlxLoggedOutSAS(0),
m_pfWlxActivateUserShell(0),
m_pfWlxLoggedOnSAS(0),
m_pfWlxDisplayLockedNotice(0),
m_pfWlxWkstaLockedSAS(0),
m_pfWlxIsLockOk(0),
m_pfWlxIsLogoffOk(0),
m_pfWlxLogoff(0),
m_pfWlxShutdown(0),
m_pfWlxStartApplication(0),
m_pfWlxScreenSaverNotify(0),
m_pfWlxNetworkProviderLoad(0),
m_pfWlxDisplayStatusMessage(0),
m_pfWlxGetStatusMessage(0),
m_pfWlxRemoveStatusMessage(0),
m_pfWlxGetConsoleSwitchCredentials(0),
m_pfWlxReconnectNotify(0),
m_pfWlxDisconnectNotify(0)
{
if(dll) m_dllname = dll;
}
GinaWrapper::~GinaWrapper()
{
Unload();
}
// TBD: Instead of checking function ptrs, we could just use m_dllVersion to infer which
// *must* be available (at which point crashes would be the chained dll's fault. That
// seems overly mean though perhaps...
// Additional GINA exports that we implement (wrapped)
bool GinaWrapper::Negotiate(DWORD dwWinlogonVersion)
{
if(!m_pfWlxNegotiate) return false;
m_negotiated = m_pfWlxNegotiate(dwWinlogonVersion, &m_dllVersion) ? true : false;
return m_negotiated;
}
bool GinaWrapper::Initialize(LPWSTR lpWinsta, HANDLE hWlx, PVOID pvReserved, PVOID pWinlogonFunctions)
{
if(!m_pfWlxInitialize) return false;
m_initialized = m_pfWlxInitialize(lpWinsta, hWlx, pvReserved, pWinlogonFunctions, &m_ginaContext) ? true : false;
return m_initialized;
}
// Standard Gina * interfaces, directly map to GINA exports
bool GinaWrapper::IsLockOk()
{
if(!m_pfWlxIsLockOk || !m_negotiated || !m_initialized) return true;
return (m_pfWlxIsLockOk(m_ginaContext) ? true : false);
}
bool GinaWrapper::IsLogoffOk()
{
if(!m_pfWlxIsLogoffOk || !m_negotiated || !m_initialized) return true;
return (m_pfWlxIsLogoffOk(m_ginaContext) ? true : false);
}
bool GinaWrapper::GetConsoleSwitchCredentials(PVOID pCredInfo)
{
if(!m_pfWlxGetConsoleSwitchCredentials || !m_negotiated || !m_initialized) return false;
return m_pfWlxGetConsoleSwitchCredentials(m_ginaContext, pCredInfo) ? true : false;
}
void GinaWrapper::ReconnectNotify()
{
if(m_pfWlxReconnectNotify && m_negotiated && m_initialized)
m_pfWlxReconnectNotify(m_ginaContext);
}
void GinaWrapper::DisconnectNotify()
{
if(m_pfWlxDisconnectNotify && m_negotiated && m_initialized)
m_pfWlxDisconnectNotify(m_ginaContext);
}
void GinaWrapper::Logoff()
{
if(m_pfWlxLogoff && m_negotiated && m_initialized)
m_pfWlxLogoff(m_ginaContext);
}
bool GinaWrapper::ScreenSaverNotify(BOOL * pSecure)
{
if(!m_pfWlxScreenSaverNotify || !m_negotiated || !m_initialized) return false;
return m_pfWlxScreenSaverNotify(m_ginaContext, pSecure) ? true : false;
}
void GinaWrapper::Shutdown(DWORD ShutdownType)
{
if(m_pfWlxShutdown && m_negotiated && m_initialized)
m_pfWlxShutdown(m_ginaContext, ShutdownType);
}
void GinaWrapper::DisplaySASNotice()
{
if(m_pfWlxDisplaySASNotice && m_negotiated && m_initialized)
m_pfWlxDisplaySASNotice(m_ginaContext);
}
void GinaWrapper::DisplayLockedNotice()
{
if(m_pfWlxDisplayLockedNotice && m_negotiated && m_initialized)
m_pfWlxDisplayLockedNotice(m_ginaContext);
}
bool GinaWrapper::DisplayStatusMessage(HDESK hDesktop, DWORD dwOptions, PWSTR pTitle, PWSTR pMessage)
{
if(!m_pfWlxDisplayStatusMessage || !m_negotiated || !m_initialized) return false;
return m_pfWlxDisplayStatusMessage(m_ginaContext, hDesktop, dwOptions, pTitle, pMessage) ? true : false;
}
bool GinaWrapper::GetStatusMessage(DWORD * pdwOptions, PWSTR pMessage, DWORD dwBufferSize)
{
if(!m_pfWlxGetStatusMessage || !m_negotiated || !m_initialized) return false;
return m_pfWlxGetStatusMessage(m_ginaContext, pdwOptions, pMessage, dwBufferSize) ? true : false;
}
bool GinaWrapper::RemoveStatusMessage()
{
if(!m_pfWlxRemoveStatusMessage || !m_negotiated || !m_initialized) return false;
return m_pfWlxRemoveStatusMessage(m_ginaContext) ? true : false;
}
int GinaWrapper::LoggedOutSAS(DWORD dwSasType, PLUID pAuthenticationId, PSID pLogonSid, PDWORD pdwOptions,
PHANDLE phToken, PWLX_MPR_NOTIFY_INFO pMprNotifyInfo, PVOID *pProfile)
{
if(!m_pfWlxLoggedOutSAS || !m_negotiated || !m_initialized) return 0;
return m_pfWlxLoggedOutSAS(m_ginaContext, dwSasType, pAuthenticationId, pLogonSid, pdwOptions, phToken, pMprNotifyInfo, pProfile);
}
int GinaWrapper::LoggedOnSAS(DWORD dwSasType, PVOID pReserved)
{
if(!m_pfWlxLoggedOnSAS || !m_negotiated || !m_initialized) return 0;
return m_pfWlxLoggedOnSAS(m_ginaContext, dwSasType, pReserved);
}
int GinaWrapper::WkstaLockedSAS(DWORD dwSasType)
{
if(!m_pfWlxWkstaLockedSAS || !m_negotiated || !m_initialized) return 0;
return m_pfWlxWkstaLockedSAS(m_ginaContext, dwSasType);
}
bool GinaWrapper::ActivateUserShell(PWSTR pszDesktopName, PWSTR pszMprLogonScript, PVOID pEnvironment)
{
if(!m_pfWlxActivateUserShell || !m_negotiated || !m_initialized) return false;
return m_pfWlxActivateUserShell(m_ginaContext, pszDesktopName, pszMprLogonScript, pEnvironment) ? true : false;
}
bool GinaWrapper::StartApplication(PWSTR pszDesktopName, PVOID pEnvironment, PWSTR pszCmdLine)
{
if(!m_pfWlxStartApplication || !m_negotiated || !m_initialized) return false;
return m_pfWlxStartApplication(m_ginaContext, pszDesktopName, pEnvironment, pszCmdLine) ? true : false;
}
bool GinaWrapper::NetworkProviderLoad(PWLX_MPR_NOTIFY_INFO pNprNotifyInfo)
{
if(!m_pfWlxNetworkProviderLoad || !m_negotiated || !m_initialized) return false;
return m_pfWlxNetworkProviderLoad(m_ginaContext, pNprNotifyInfo) ? true : false;
}
bool GinaWrapper::Load()
{
if(!(m_dll = LoadLibraryW(m_dllname.c_str())))
return false;
m_pfWlxNegotiate = (PFWLXNEGOTIATE) GetProcAddress(m_dll, "WlxNegotiate");
m_pfWlxInitialize = (PFWLXINITIALIZE) GetProcAddress(m_dll, "WlxInitialize");
m_pfWlxDisplaySASNotice = (PFWLXDISPLAYSASNOTICE) GetProcAddress(m_dll, "WlxDisplaySASNotice");
m_pfWlxLoggedOutSAS = (PFWLXLOGGEDOUTSAS) GetProcAddress(m_dll, "WlxLoggedOutSAS");
m_pfWlxActivateUserShell = (PFWLXACTIVATEUSERSHELL) GetProcAddress(m_dll, "WlxActivateUserShell");
m_pfWlxLoggedOnSAS = (PFWLXLOGGEDONSAS) GetProcAddress(m_dll, "WlxLoggedOnSAS");
m_pfWlxDisplayLockedNotice = (PFWLXDISPLAYLOCKEDNOTICE) GetProcAddress(m_dll, "WlxDisplayLockedNotice");
m_pfWlxWkstaLockedSAS = (PFWLXWKSTALOCKEDSAS) GetProcAddress(m_dll, "WlxWkstaLockedSAS");
m_pfWlxIsLockOk = (PFWLXISLOCKOK) GetProcAddress(m_dll, "WlxIsLockOk");
m_pfWlxIsLogoffOk = (PFWLXISLOGOFFOK) GetProcAddress(m_dll, "WlxIsLogoffOk");
m_pfWlxLogoff = (PFWLXLOGOFF) GetProcAddress(m_dll, "WlxLogoff");
m_pfWlxShutdown = (PFWLXSHUTDOWN) GetProcAddress(m_dll, "WlxShutdown");
m_pfWlxStartApplication = (PFWLXSTARTAPPLICATION) GetProcAddress(m_dll, "WlxStartApplication");
m_pfWlxScreenSaverNotify = (PFWLXSCREENSAVERNOTIFY) GetProcAddress(m_dll, "WlxScreenSaverNotify");
m_pfWlxNetworkProviderLoad = (PFWLXNETWORKPROVIDERLOAD) GetProcAddress(m_dll, "WlxNetworkProviderLoad");
m_pfWlxDisplayStatusMessage = (PFWLXDISPLAYSTATUSMESSAGE) GetProcAddress(m_dll, "WlxDisplayStatusMessage");
m_pfWlxGetStatusMessage = (PFWLXGETSTATUSMESSAGE) GetProcAddress(m_dll, "WlxGetStatusMessage");
m_pfWlxRemoveStatusMessage = (PFWLXREMOVESTATUSMESSAGE) GetProcAddress(m_dll, "WlxRemoveStatusMessage");
m_pfWlxGetConsoleSwitchCredentials = (PFWLXGETCONSOLESWITCHCREDENTIALS) GetProcAddress(m_dll, "WlxGetConsoleSwitchCredentials");
m_pfWlxReconnectNotify = (PFWLXRECONNECTNOTIFY) GetProcAddress(m_dll, "WlxReconnectNotify");
m_pfWlxDisconnectNotify = (PFWLXDISCONNECTNOTIFY) GetProcAddress(m_dll, "WlxDisconnectNotify");
return true;
}
void GinaWrapper::Unload()
{
if(!IsLoaded()) return;
if(FreeLibrary(m_dll))
{
m_ginaContext = 0;
m_dll = 0;
m_pfWlxNegotiate = 0;
m_pfWlxInitialize = 0;
m_pfWlxDisplaySASNotice = 0;
m_pfWlxLoggedOutSAS = 0;
m_pfWlxActivateUserShell = 0;
m_pfWlxLoggedOnSAS = 0;
m_pfWlxDisplayLockedNotice = 0;
m_pfWlxWkstaLockedSAS = 0;
m_pfWlxIsLockOk = 0;
m_pfWlxIsLogoffOk = 0;
m_pfWlxLogoff = 0;
m_pfWlxShutdown = 0;
m_pfWlxStartApplication = 0;
m_pfWlxScreenSaverNotify = 0;
m_pfWlxNetworkProviderLoad = 0;
m_pfWlxDisplayStatusMessage = 0;
m_pfWlxGetStatusMessage = 0;
m_pfWlxRemoveStatusMessage = 0;
m_pfWlxGetConsoleSwitchCredentials = 0;
m_pfWlxReconnectNotify = 0;
m_pfWlxDisconnectNotify = 0;
}
}
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
using System.Configuration.Install;
using System.Reflection;
using log4net;
namespace Service
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
if (System.Environment.UserInteractive)
{
// Initalize logging and grab a logger
pGina.Shared.Logging.Logging.Init();
ILog m_log = LogManager.GetLogger("Service Install");
try
{
string parameter = string.Concat(args);
switch (parameter)
{
case "--install":
m_log.DebugFormat("Installing service...");
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
break;
case "--uninstall":
m_log.DebugFormat("Uninstalling service...");
ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
break;
case "--start":
m_log.Debug("Starting service...");
Start(args);
break;
case "--stop":
m_log.Debug("Stopping service...");
Stop();
break;
}
}
catch (Exception e)
{
m_log.ErrorFormat("Uncaught exception in UserInteractive mode: {0}", e);
Environment.Exit(1);
}
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new pGinaServiceHost()
};
ServiceBase.Run(ServicesToRun);
}
}
private static void Start(string[] args)
{
foreach (ServiceController ctrl in ServiceController.GetServices())
{
if (ctrl.ServiceName == "pGina")
{
ctrl.Start(args);
break;
}
}
}
private static void Stop()
{
foreach (ServiceController ctrl in ServiceController.GetServices())
{
if (ctrl.ServiceName == "pGina")
{
ctrl.Stop();
break;
}
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include "PipeClient.h"
#include "BinaryReader.h"
#include "BinaryWriter.h"
namespace pGina
{
namespace NamedPipes
{
PipeClient::PipeClient(std::wstring const& path)
: m_path(path), m_connectTimeout(NMPWAIT_USE_DEFAULT_WAIT), m_pipe(INVALID_HANDLE_VALUE)
{
}
PipeClient::PipeClient(std::wstring const& path, int connectTimeout)
: m_path(path), m_connectTimeout(connectTimeout), m_pipe(INVALID_HANDLE_VALUE)
{
}
PipeClient::~PipeClient()
{
Close();
}
bool PipeClient::Connect()
{
return Connect(m_connectTimeout);
}
bool PipeClient::Connect(int timeout)
{
if(!WaitNamedPipe(m_path.c_str(), (DWORD) timeout))
return false;
if((m_pipe = CreateFile(m_path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL)) ==
INVALID_HANDLE_VALUE)
return false;
return true;
}
pGina::Memory::Buffer * PipeClient::ReadLengthEncodedBuffer()
{
pGina::Memory::Buffer * lengthBuffer = ReadBuffer(sizeof(int));
if(lengthBuffer == 0) return 0;
int length = 0;
{
pGina::Memory::BinaryReader reader(lengthBuffer);
length = reader.ReadInt32();
delete lengthBuffer; // No longer needed, not that reader() should no longer be used, hence its scoping
lengthBuffer = 0;
}
if(length <= 0)
return 0;
return ReadBuffer(length);
}
bool PipeClient::WriteLengthEncodedBuffer(pGina::Memory::Buffer *buffer)
{
pGina::Memory::Buffer lengthBuffer(4);
pGina::Memory::BinaryWriter writer(lengthBuffer);
writer.Write(buffer->Length());
if(WriteBuffer(&lengthBuffer))
{
return WriteBuffer(buffer);
}
return false;
}
pGina::Memory::Buffer * PipeClient::ReadBuffer(int size)
{
if(size <= 0)
return 0;
pGina::Memory::Buffer * buffer = new pGina::Memory::Buffer(size);
unsigned char * ptr = buffer->Raw();
int length = buffer->Length();
while(length > 0)
{
int read = Read(ptr, length);
if(read == 0)
{
delete buffer;
return false;
}
ptr += read;
length -= read;
}
return buffer;
}
bool PipeClient::WriteBuffer(pGina::Memory::Buffer *buffer)
{
if(buffer && buffer->Length() > 0)
{
unsigned char * ptr = buffer->Raw();
int length = buffer->Length();
while(length > 0)
{
int written = Write(ptr, length);
if(written == 0)
return false;
ptr += written;
length -= written;
}
}
return true;
}
int PipeClient::Read(unsigned char * buffer, int len)
{
DWORD bytesRead = 0;
if(ReadFile(m_pipe, buffer, (DWORD) len, &bytesRead, NULL))
return bytesRead;
return 0;
}
int PipeClient::Write(unsigned char * buffer, int len)
{
DWORD bytesWritten = 0;
if(WriteFile(m_pipe, buffer, (DWORD) len, &bytesWritten, NULL))
return bytesWritten;
return 0;
}
void PipeClient::Close()
{
if(m_pipe != INVALID_HANDLE_VALUE)
{
CloseHandle(m_pipe);
m_pipe = INVALID_HANDLE_VALUE;
}
}
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.IO;
using log4net;
namespace pGina.Plugin.Ldap
{
enum Methods
{
PLAIN,
MD5,
SMD5,
SHA1,
SSHA1,
NTLM,
LM,
Timestamps,
Timestampd,
Timestampt,
SHA256,
SSHA256,
SHA384,
SSHA384,
SHA512,
SSHA512,
ADPWD,
}
class AttribConvert
{
public static readonly List<string> Attribs = new List<string>(new string[] {
// the name must match properties in UserInformation
"Fullname",
"usri4_max_storage",
"usri4_profile",
"usri4_home_dir_drive",
"usri4_home_dir",
"Email",
"LoginScript",
"pgSMB_Filename",
"pgSMB_SMBshare",
"script_authe_sys",
"script_autho_sys",
"script_gateway_sys",
"script_notification_sys",
"script_notification_usr",
"script_changepwd_sys",
"script_changepwd_usr"
});
}
abstract class AttribMethod
{
internal ILog m_logger = LogManager.GetLogger("LdapHash");
public string Name { get { return m_name; } }
protected string m_name;
public Methods Method { get { return m_method; } }
protected Methods m_method;
public static Dictionary<Methods, AttribMethod> methods;
static AttribMethod()
{
methods = new Dictionary<Methods, AttribMethod>();
methods.Add(Methods.PLAIN, new PasswordHashMethodPlain());
methods.Add(Methods.MD5, new PasswordHashMethodMD5());
methods.Add(Methods.SMD5, new PasswordHashMethodSMD5());
methods.Add(Methods.SHA1, new PasswordHashMethodSHA1());
methods.Add(Methods.SSHA1, new PasswordHashMethodSSHA1());
methods.Add(Methods.SHA256, new PasswordHashMethodSHA256());
methods.Add(Methods.SSHA256, new PasswordHashMethodSSHA256());
methods.Add(Methods.SHA384, new PasswordHashMethodSHA384());
methods.Add(Methods.SSHA384, new PasswordHashMethodSSHA384());
methods.Add(Methods.SHA512, new PasswordHashMethodSHA512());
methods.Add(Methods.SSHA512, new PasswordHashMethodSSHA512());
methods.Add(Methods.NTLM, new PasswordHashMethodNTLM());
methods.Add(Methods.LM, new PasswordHashMethodLM());
methods.Add(Methods.ADPWD, new PasswordADPWD());
}
public abstract string hash(string pw);
protected byte[] GenerateSalt(uint length)
{
byte[] salt = new byte[length];
try
{
using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
{
crypto.GetBytes(salt);
}
}
catch (Exception ex)
{
m_logger.FatalFormat("GenerateSalt Error:{0}", ex.Message);
}
return salt;
}
protected byte[] Appendbytes(byte[] source, byte[] append)
{
byte[] combine = new byte[source.Length + append.Length];
try
{
Buffer.BlockCopy(source, 0, combine, 0, source.Length);
Buffer.BlockCopy(append, 0, combine, source.Length, append.Length);
}
catch (Exception ex)
{
m_logger.FatalFormat("Appendbytes Error:{0}", ex.Message);
}
return combine;
}
}
abstract class TimeMethod
{
internal ILog m_logger = LogManager.GetLogger("LdapTime");
public string Name { get { return m_name; } }
protected string m_name;
public Methods Method { get { return m_method; } }
protected Methods m_method;
public static Dictionary<Methods, TimeMethod> methods;
static TimeMethod()
{
methods = new Dictionary<Methods, TimeMethod>();
methods.Add(Methods.Timestamps, new PasswordTimestampUNIX());
methods.Add(Methods.Timestampd, new PasswordTimestampSHADOW());
methods.Add(Methods.Timestampt, new PasswordTimestampNT());
}
public abstract string time();
public abstract string time(TimeSpan add);
}
class PasswordADPWD : AttribMethod
{
public PasswordADPWD()
{
m_name = "Select to change an AD password";
m_method = Methods.ADPWD;
}
public override string hash(string pw)
{
return pw;
}
}
class PasswordHashMethodPlain : AttribMethod
{
public PasswordHashMethodPlain()
{
m_name = "Plain Text";
m_method = Methods.PLAIN;
}
public override string hash(string pw)
{
return pw;
}
}
class PasswordHashMethodMD5 : AttribMethod
{
public PasswordHashMethodMD5()
{
m_name = "MD5";
m_method = Methods.MD5;
}
public override string hash(string password)
{
byte[] md5 = null;
try
{
using (MD5 algorithm = new MD5CryptoServiceProvider())
{
md5 = algorithm.ComputeHash(Encoding.UTF8.GetBytes(password));
}
}
catch (Exception ex)
{
m_logger.FatalFormat("MD5 Error:", ex.Message);
}
return "{MD5}" + Convert.ToBase64String(md5);
}
}
class PasswordHashMethodSMD5 : AttribMethod
{
public PasswordHashMethodSMD5()
{
m_name = "SMD5 (Salted MD5)";
m_method = Methods.SMD5;
}
public override string hash(string password)
{
byte[] smd5 = null;
byte[] salt = GenerateSalt(16);
try
{
using (MD5 algorithm = new MD5CryptoServiceProvider())
{
byte[] combine = Appendbytes(Encoding.UTF8.GetBytes(password), salt);
smd5 = algorithm.ComputeHash(combine);
smd5 = Appendbytes(smd5, salt);
}
}
catch (Exception ex)
{
m_logger.FatalFormat("SMD5 Error:", ex.Message);
}
return "{SMD5}" + Convert.ToBase64String(smd5);
}
}
class PasswordHashMethodSHA1 : AttribMethod
{
public PasswordHashMethodSHA1()
{
m_name = "SHA1";
m_method = Methods.SHA1;
}
public override string hash(string password)
{
byte[] sha = null;
try
{
using (HashAlgorithm algorithm = new SHA1Managed())
{
sha = algorithm.ComputeHash(Encoding.UTF8.GetBytes(password));
}
}
catch (Exception ex)
{
m_logger.FatalFormat("SHA Error:", ex.Message);
}
return "{SHA}" + Convert.ToBase64String(sha);
}
}
class PasswordHashMethodSSHA1 : AttribMethod
{
public PasswordHashMethodSSHA1()
{
m_name = "SSHA1 (Salted SHA1)";
m_method = Methods.SSHA1;
}
public override string hash(string password)
{
byte[] ssha = null;
byte[] salt = GenerateSalt(16);
try
{
using (HashAlgorithm algorithm = new SHA1Managed())
{
byte[] combine = Appendbytes(Encoding.UTF8.GetBytes(password), salt);
ssha = algorithm.ComputeHash(combine);
ssha = Appendbytes(ssha, salt);
}
}
catch (Exception ex)
{
m_logger.FatalFormat("SSHA Error:", ex.Message);
}
return "{SSHA}" + Convert.ToBase64String(ssha);
}
}
class PasswordHashMethodSHA256 : AttribMethod
{
public PasswordHashMethodSHA256()
{
m_name = "SHA256";
m_method = Methods.SHA256;
}
public override string hash(string password)
{
byte[] sha = null;
try
{
using (HashAlgorithm algorithm = new SHA256Managed())
{
sha = algorithm.ComputeHash(Encoding.UTF8.GetBytes(password));
}
}
catch (Exception ex)
{
m_logger.FatalFormat("SHA Error:", ex.Message);
}
return "{SHA256}" + Convert.ToBase64String(sha);
}
}
class PasswordHashMethodSSHA256 : AttribMethod
{
public PasswordHashMethodSSHA256()
{
m_name = "SSHA256 (Salted SHA256)";
m_method = Methods.SSHA256;
}
public override string hash(string password)
{
byte[] ssha = null;
byte[] salt = GenerateSalt(16);
try
{
using (HashAlgorithm algorithm = new SHA256Managed())
{
byte[] combine = Appendbytes(Encoding.UTF8.GetBytes(password), salt);
ssha = algorithm.ComputeHash(combine);
ssha = Appendbytes(ssha, salt);
}
}
catch (Exception ex)
{
m_logger.FatalFormat("SSHA Error:", ex.Message);
}
return "{SSHA256}" + Convert.ToBase64String(ssha);
}
}
class PasswordHashMethodSHA384 : AttribMethod
{
public PasswordHashMethodSHA384()
{
m_name = "SHA384";
m_method = Methods.SHA384;
}
public override string hash(string password)
{
byte[] sha = null;
try
{
using (HashAlgorithm algorithm = new SHA384Managed())
{
sha = algorithm.ComputeHash(Encoding.UTF8.GetBytes(password));
}
}
catch (Exception ex)
{
m_logger.FatalFormat("SHA Error:", ex.Message);
}
return "{SHA384}" + Convert.ToBase64String(sha);
}
}
class PasswordHashMethodSSHA384 : AttribMethod
{
public PasswordHashMethodSSHA384()
{
m_name = "SSHA384 (Salted SHA384)";
m_method = Methods.SSHA384;
}
public override string hash(string password)
{
byte[] ssha = null;
byte[] salt = GenerateSalt(16);
try
{
using (HashAlgorithm algorithm = new SHA384Managed())
{
byte[] combine = Appendbytes(Encoding.UTF8.GetBytes(password), salt);
ssha = algorithm.ComputeHash(combine);
ssha = Appendbytes(ssha, salt);
}
}
catch (Exception ex)
{
m_logger.FatalFormat("SSHA Error:", ex.Message);
}
return "{SSHA384}" + Convert.ToBase64String(ssha);
}
}
class PasswordHashMethodSHA512 : AttribMethod
{
public PasswordHashMethodSHA512()
{
m_name = "SHA512";
m_method = Methods.SHA512;
}
public override string hash(string password)
{
byte[] sha = null;
try
{
using (HashAlgorithm algorithm = new SHA512Managed())
{
sha = algorithm.ComputeHash(Encoding.UTF8.GetBytes(password));
}
}
catch (Exception ex)
{
m_logger.FatalFormat("SHA Error:", ex.Message);
}
return "{SHA512}" + Convert.ToBase64String(sha);
}
}
class PasswordHashMethodSSHA512 : AttribMethod
{
public PasswordHashMethodSSHA512()
{
m_name = "SSHA512 (Salted SHA512)";
m_method = Methods.SSHA512;
}
public override string hash(string password)
{
byte[] ssha = null;
byte[] salt = GenerateSalt(16);
try
{
using (HashAlgorithm algorithm = new SHA512Managed())
{
byte[] combine = Appendbytes(Encoding.UTF8.GetBytes(password), salt);
ssha = algorithm.ComputeHash(combine);
ssha = Appendbytes(ssha, salt);
}
}
catch (Exception ex)
{
m_logger.FatalFormat("SSHA Error:", ex.Message);
}
return "{SSHA512}" + Convert.ToBase64String(ssha);
}
}
class PasswordHashMethodNTLM : AttribMethod
{
#region advapi32.dll
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CryptAcquireContext(ref IntPtr hProv, string pszContainer, string pszProvider, uint dwProvType, uint dwFlags);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool CryptCreateHash(IntPtr hProv, uint algId, IntPtr hKey, uint dwFlags, ref IntPtr phHash);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool CryptHashData(IntPtr hHash, byte[] pbData, uint dataLen, uint flags);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool CryptGetHashParam(IntPtr hHash, Int32 dwParam, Byte[] pbData, ref Int32 pdwDataLen, Int32 dwFlags);
[DllImport("Advapi32.dll", EntryPoint = "CryptReleaseContext", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CryptReleaseContext(IntPtr hProv, Int32 dwFlags /* Reserved. Must be 0*/ );
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool CryptDestroyHash(IntPtr hHash);
#endregion
#region Structs/Enums
/// <summary>
/// Source: WinCrypt.h
/// </summary>
enum HashParameters
{
HP_ALGID = 0x0001, // Hash algorithm
HP_HASHVAL = 0x0002, // Hash value
HP_HASHSIZE = 0x0004 // Hash value size
}
/// <summary>
/// Source: WinCrypt.h
/// </summary>
public enum CryptAlgClass : uint
{
ALG_CLASS_ANY = (0),
ALG_CLASS_SIGNATURE = (1 << 13),
ALG_CLASS_MSG_ENCRYPT = (2 << 13),
ALG_CLASS_DATA_ENCRYPT = (3 << 13),
ALG_CLASS_HASH = (4 << 13),
ALG_CLASS_KEY_EXCHANGE = (5 << 13),
ALG_CLASS_ALL = (7 << 13)
}
/// <summary>
/// Source: WinCrypt.h
/// </summary>
public enum CryptAlgType : uint
{
ALG_TYPE_ANY = (0),
ALG_TYPE_DSS = (1 << 9),
ALG_TYPE_RSA = (2 << 9),
ALG_TYPE_BLOCK = (3 << 9),
ALG_TYPE_STREAM = (4 << 9),
ALG_TYPE_DH = (5 << 9),
ALG_TYPE_SECURECHANNEL = (6 << 9)
}
/// <summary>
/// Source: WinCrypt.h
/// </summary>
public enum CryptAlgSID : uint
{
ALG_SID_ANY = (0),
ALG_SID_RSA_ANY = 0,
ALG_SID_RSA_PKCS = 1,
ALG_SID_RSA_MSATWORK = 2,
ALG_SID_RSA_ENTRUST = 3,
ALG_SID_RSA_PGP = 4,
ALG_SID_DSS_ANY = 0,
ALG_SID_DSS_PKCS = 1,
ALG_SID_DSS_DMS = 2,
ALG_SID_ECDSA = 3,
ALG_SID_DES = 1,
ALG_SID_3DES = 3,
ALG_SID_DESX = 4,
ALG_SID_IDEA = 5,
ALG_SID_CAST = 6,
ALG_SID_SAFERSK64 = 7,
ALG_SID_SAFERSK128 = 8,
ALG_SID_3DES_112 = 9,
ALG_SID_CYLINK_MEK = 12,
ALG_SID_RC5 = 13,
ALG_SID_AES_128 = 14,
ALG_SID_AES_192 = 15,
ALG_SID_AES_256 = 16,
ALG_SID_AES = 17,
ALG_SID_SKIPJACK = 10,
ALG_SID_TEK = 11,
ALG_SID_RC2 = 2,
ALG_SID_RC4 = 1,
ALG_SID_SEAL = 2,
ALG_SID_DH_SANDF = 1,
ALG_SID_DH_EPHEM = 2,
ALG_SID_AGREED_KEY_ANY = 3,
ALG_SID_KEA = 4,
ALG_SID_ECDH = 5,
ALG_SID_MD2 = 1,
ALG_SID_MD4 = 2,
ALG_SID_MD5 = 3,
ALG_SID_SHA = 4,
ALG_SID_SHA1 = 4,
ALG_SID_MAC = 5,
ALG_SID_RIPEMD = 6,
ALG_SID_RIPEMD160 = 7,
ALG_SID_SSL3SHAMD5 = 8,
ALG_SID_HMAC = 9,
ALG_SID_TLS1PRF = 10,
ALG_SID_HASH_REPLACE_OWF = 11,
ALG_SID_SHA_256 = 12,
ALG_SID_SHA_384 = 13,
ALG_SID_SHA_512 = 14,
ALG_SID_SSL3_MASTER = 1,
ALG_SID_SCHANNEL_MASTER_HASH = 2,
ALG_SID_SCHANNEL_MAC_KEY = 3,
ALG_SID_PCT1_MASTER = 4,
ALG_SID_SSL2_MASTER = 5,
ALG_SID_TLS1_MASTER = 6,
ALG_SID_SCHANNEL_ENC_KEY = 7,
ALG_SID_ECMQV = 1
}
/// <summary>
/// Source: WinCrypt.h
/// </summary>
public enum CryptAlg : uint
{
CALG_MD2 = (CryptAlgClass.ALG_CLASS_HASH | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_MD2),
CALG_MD4 = (CryptAlgClass.ALG_CLASS_HASH | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_MD4),
CALG_MD5 = (CryptAlgClass.ALG_CLASS_HASH | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_MD5),
CALG_SHA = (CryptAlgClass.ALG_CLASS_HASH | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_SHA),
CALG_SHA1 = (CryptAlgClass.ALG_CLASS_HASH | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_SHA1),
CALG_MAC = (CryptAlgClass.ALG_CLASS_HASH | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_MAC),
CALG_RSA_SIGN = (CryptAlgClass.ALG_CLASS_SIGNATURE | CryptAlgType.ALG_TYPE_RSA | CryptAlgSID.ALG_SID_RSA_ANY),
CALG_DSS_SIGN = (CryptAlgClass.ALG_CLASS_SIGNATURE | CryptAlgType.ALG_TYPE_DSS | CryptAlgSID.ALG_SID_DSS_ANY),
CALG_NO_SIGN = (CryptAlgClass.ALG_CLASS_SIGNATURE | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_ANY),
CALG_RSA_KEYX = (CryptAlgClass.ALG_CLASS_KEY_EXCHANGE | CryptAlgType.ALG_TYPE_RSA | CryptAlgSID.ALG_SID_RSA_ANY),
CALG_DES = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_BLOCK | CryptAlgSID.ALG_SID_DES),
CALG_3DES_112 = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_BLOCK | CryptAlgSID.ALG_SID_3DES_112),
CALG_3DES = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_BLOCK | CryptAlgSID.ALG_SID_3DES),
CALG_DESX = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_BLOCK | CryptAlgSID.ALG_SID_DESX),
CALG_RC2 = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_BLOCK | CryptAlgSID.ALG_SID_RC2),
CALG_RC4 = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_STREAM | CryptAlgSID.ALG_SID_RC4),
CALG_SEAL = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_STREAM | CryptAlgSID.ALG_SID_SEAL),
CALG_DH_SF = (CryptAlgClass.ALG_CLASS_KEY_EXCHANGE | CryptAlgType.ALG_TYPE_DH | CryptAlgSID.ALG_SID_DH_SANDF),
CALG_DH_EPHEM = (CryptAlgClass.ALG_CLASS_KEY_EXCHANGE | CryptAlgType.ALG_TYPE_DH | CryptAlgSID.ALG_SID_DH_EPHEM),
CALG_AGREEDKEY_ANY = (CryptAlgClass.ALG_CLASS_KEY_EXCHANGE | CryptAlgType.ALG_TYPE_DH | CryptAlgSID.ALG_SID_AGREED_KEY_ANY),
CALG_KEA_KEYX = (CryptAlgClass.ALG_CLASS_KEY_EXCHANGE | CryptAlgType.ALG_TYPE_DH | CryptAlgSID.ALG_SID_KEA),
CALG_HUGHES_MD5 = (CryptAlgClass.ALG_CLASS_KEY_EXCHANGE | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_MD5),
CALG_SKIPJACK = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_BLOCK | CryptAlgSID.ALG_SID_SKIPJACK),
CALG_TEK = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_BLOCK | CryptAlgSID.ALG_SID_TEK),
CALG_CYLINK_MEK = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_BLOCK | CryptAlgSID.ALG_SID_CYLINK_MEK),
CALG_SSL3_SHAMD5 = (CryptAlgClass.ALG_CLASS_HASH | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_SSL3SHAMD5),
CALG_SSL3_MASTER = (CryptAlgClass.ALG_CLASS_MSG_ENCRYPT | CryptAlgType.ALG_TYPE_SECURECHANNEL | CryptAlgSID.ALG_SID_SSL3_MASTER),
CALG_SCHANNEL_MASTER_HASH = (CryptAlgClass.ALG_CLASS_MSG_ENCRYPT | CryptAlgType.ALG_TYPE_SECURECHANNEL | CryptAlgSID.ALG_SID_SCHANNEL_MASTER_HASH),
CALG_SCHANNEL_MAC_KEY = (CryptAlgClass.ALG_CLASS_MSG_ENCRYPT | CryptAlgType.ALG_TYPE_SECURECHANNEL | CryptAlgSID.ALG_SID_SCHANNEL_MAC_KEY),
CALG_SCHANNEL_ENC_KEY = (CryptAlgClass.ALG_CLASS_MSG_ENCRYPT | CryptAlgType.ALG_TYPE_SECURECHANNEL | CryptAlgSID.ALG_SID_SCHANNEL_ENC_KEY),
CALG_PCT1_MASTER = (CryptAlgClass.ALG_CLASS_MSG_ENCRYPT | CryptAlgType.ALG_TYPE_SECURECHANNEL | CryptAlgSID.ALG_SID_PCT1_MASTER),
CALG_SSL2_MASTER = (CryptAlgClass.ALG_CLASS_MSG_ENCRYPT | CryptAlgType.ALG_TYPE_SECURECHANNEL | CryptAlgSID.ALG_SID_SSL2_MASTER),
CALG_TLS1_MASTER = (CryptAlgClass.ALG_CLASS_MSG_ENCRYPT | CryptAlgType.ALG_TYPE_SECURECHANNEL | CryptAlgSID.ALG_SID_TLS1_MASTER),
CALG_RC5 = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_BLOCK | CryptAlgSID.ALG_SID_RC5),
CALG_HMAC = (CryptAlgClass.ALG_CLASS_HASH | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_HMAC),
CALG_TLS1PRF = (CryptAlgClass.ALG_CLASS_HASH | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_TLS1PRF),
CALG_HASH_REPLACE_OWF = (CryptAlgClass.ALG_CLASS_HASH | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_HASH_REPLACE_OWF),
CALG_AES_128 = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_BLOCK | CryptAlgSID.ALG_SID_AES_128),
CALG_AES_192 = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_BLOCK | CryptAlgSID.ALG_SID_AES_192),
CALG_AES_256 = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_BLOCK | CryptAlgSID.ALG_SID_AES_256),
CALG_AES = (CryptAlgClass.ALG_CLASS_DATA_ENCRYPT | CryptAlgType.ALG_TYPE_BLOCK | CryptAlgSID.ALG_SID_AES),
CALG_SHA_256 = (CryptAlgClass.ALG_CLASS_HASH | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_SHA_256),
CALG_SHA_384 = (CryptAlgClass.ALG_CLASS_HASH | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_SHA_384),
CALG_SHA_512 = (CryptAlgClass.ALG_CLASS_HASH | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_SHA_512),
CALG_ECDH = (CryptAlgClass.ALG_CLASS_KEY_EXCHANGE | CryptAlgType.ALG_TYPE_DH | CryptAlgSID.ALG_SID_ECDH),
CALG_ECMQV = (CryptAlgClass.ALG_CLASS_KEY_EXCHANGE | CryptAlgType.ALG_TYPE_ANY | CryptAlgSID.ALG_SID_ECMQV),
CALG_ECDSA = (CryptAlgClass.ALG_CLASS_SIGNATURE | CryptAlgType.ALG_TYPE_DSS | CryptAlgSID.ALG_SID_ECDSA)
}
/// <summary>
/// Source: WinCrypt.h
/// </summary>
public enum CryptProvType : uint
{
PROV_RSA_FULL = 1,
PROV_RSA_SIG = 2,
PROV_DSS = 3,
PROV_FORTEZZA = 4,
PROV_MS_EXCHANGE = 5,
PROV_SSL = 6,
PROV_RSA_SCHANNEL = 12,
PROV_DSS_DH = 13,
PROV_EC_ECDSA_SIG = 14,
PROV_EC_ECNRA_SIG = 15,
PROV_EC_ECDSA_FULL = 16,
PROV_EC_ECNRA_FULL = 17,
PROV_DH_SCHANNEL = 18,
PROV_SPYRUS_LYNKS = 20,
PROV_RNG = 21,
PROV_INTEL_SEC = 22,
PROV_REPLACE_OWF = 23,
PROV_RSA_AES = 24
}
/// <summary>
/// Source: WinCrypt.h
/// </summary>
public enum CryptContext : uint
{
CRYPT_VERIFYCONTEXT = 0xF0000000,
CRYPT_NEWKEYSET = 0x00000008,
CRYPT_DELETEKEYSET = 0x00000010,
CRYPT_MACHINE_KEYSET = 0x00000020,
CRYPT_SILENT = 0x00000040,
CRYPT_DEFAULT_CONTAINER_OPTIONAL = 0x00000080
}
#endregion
public PasswordHashMethodNTLM()
{
m_name = "NTLM Hash (sambaNTPassword, MD4)";
m_method = Methods.NTLM;
}
public override string hash(string password)
{
IntPtr lHCryptprov = IntPtr.Zero;
IntPtr lHHash = IntPtr.Zero;
byte[] hdata = new byte[16];
int length = 16;
byte[] pass = <PASSWORD>(password);
try
{
if (CryptAcquireContext(ref lHCryptprov, null, null, (uint)CryptProvType.PROV_RSA_AES, (uint)CryptContext.CRYPT_VERIFYCONTEXT))
{
if (CryptCreateHash(lHCryptprov, (uint)CryptAlg.CALG_MD4, IntPtr.Zero, 0, ref lHHash))
{
if (CryptHashData(lHHash, pass, (uint)pass.Length, 0))
{
if (!CryptGetHashParam(lHHash, (int)HashParameters.HP_HASHVAL, hdata, ref length, 0))
{
string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).ToString();
m_logger.FatalFormat("CryptGetHashParam Error:{0}", errorMessage);
}
}
else
{
string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).ToString();
m_logger.FatalFormat("CryptHashData Error:{0}", errorMessage);
}
}
else
{
string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).ToString();
m_logger.FatalFormat("CryptCreateHash Error:{0}", errorMessage);
}
}
else
{
string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).ToString();
m_logger.FatalFormat("CryptAcquireContext Error:{0}", errorMessage);
}
}
catch (Exception ex)
{
m_logger.FatalFormat(ex.Message);
}
finally
{
if (lHHash != IntPtr.Zero)
CryptDestroyHash(lHHash);
if (lHCryptprov != IntPtr.Zero)
CryptReleaseContext(lHCryptprov, 0);
}
return BitConverter.ToString(hdata).Replace("-", "");
}
}
class PasswordHashMethodLM : AttribMethod
{
public PasswordHashMethodLM()
{
m_name = "LM Hash (sambaLMPassword, DES)";
m_method = Methods.LM;
}
public override string hash(string password)
{
string hash = null;
password = <PASSWORD>();
if (password.Length > 14)
password = <PASSWORD>.Substring(0, 14);
try
{
hash = BitConverter.ToString(LMhash.Compute(password)).Replace("-", "");
}
catch (Exception ex)
{
m_logger.FatalFormat("Compute Error:{0}", ex.Message);
}
return hash;
}
}
class PasswordTimestampUNIX : TimeMethod
{
public PasswordTimestampUNIX()
{
m_name = "Timestamp sec since '70";
m_method = Methods.Timestamps;
}
public override string time()
{
TimeSpan span = new TimeSpan();
try
{
span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0));
}
catch (Exception ex)
{
m_logger.FatalFormat("PasswordTimestampUNIX Error:{0}", ex.Message);
}
return Convert.ToInt32(span.TotalSeconds).ToString();
}
public override string time(TimeSpan add)
{
TimeSpan span = new TimeSpan();
try
{
span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0));
span += add;
}
catch (Exception ex)
{
m_logger.FatalFormat("PasswordTimestampUNIX Error:{0}", ex.Message);
}
return Convert.ToInt32(span.TotalSeconds).ToString();
}
}
class PasswordTimestampSHADOW : TimeMethod
{
public PasswordTimestampSHADOW()
{
m_name = "Timestamp days since '70";
m_method = Methods.Timestampd;
}
public override string time()
{
TimeSpan span = new TimeSpan();
try
{
span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0));
}
catch (Exception ex)
{
m_logger.FatalFormat("PasswordTimestampSHADOW Error:{0}", ex.Message);
}
return Convert.ToInt32(span.TotalDays).ToString();
}
public override string time(TimeSpan add)
{
TimeSpan span = new TimeSpan();
try
{
span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0));
span += add;
}
catch (Exception ex)
{
m_logger.FatalFormat("PasswordTimestampSHADOW Error:{0}", ex.Message);
}
return Convert.ToInt32(span.TotalDays).ToString();
}
}
class PasswordTimestampNT : TimeMethod
{
public PasswordTimestampNT()
{
m_name = "Timestamp ticks since 1601";
m_method = Methods.Timestampt;
}
public override string time()
{
TimeSpan span = new TimeSpan();
try
{
span = (DateTime.UtcNow - new DateTime(1601, 1, 1, 0, 0, 0, 0));
}
catch (Exception ex)
{
m_logger.FatalFormat("PasswordTimestampNT Error:{0}", ex.Message);
}
return Convert.ToInt64(span.Ticks).ToString();
}
public override string time(TimeSpan add)
{
TimeSpan span = new TimeSpan();
try
{
span = (DateTime.UtcNow - new DateTime(1601, 1, 1, 0, 0, 0, 0));
span += add;
}
catch (Exception ex)
{
m_logger.FatalFormat("PasswordTimestampNT Error:{0}", ex.Message);
}
return Convert.ToInt64(span.Ticks).ToString();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.ServiceProcess;
using log4net;
using MySql.Data.MySqlClient;
using pGina.Shared.Types;
namespace pGina.Plugin.MySqlLogger
{
class SessionLogger : ILoggerMode
{
private ILog m_logger = LogManager.GetLogger("MySqlLoggerPlugin");
private MySqlConnection m_conn;
public SessionLogger(){ }
//Logs the session if it's a LogOn or LogOff event.
public bool Log(int SessionId, System.ServiceProcess.SessionChangeReason Reason, SessionProperties properties)
{
if (m_conn == null)
throw new InvalidOperationException("No MySQL Connection present.");
string username = "--UNKNOWN--";
if (properties != null)
{
UserInformation ui = properties.GetTrackedSingle<UserInformation>();
if ((bool)Settings.Store.UseModifiedName)
username = ui.Username;
else
username = ui.OriginalUsername;
}
//Logon Event
if (Reason == SessionChangeReason.SessionLogon)
{
if(m_conn.State != System.Data.ConnectionState.Open)
m_conn.Open();
string table = Settings.Store.SessionTable;
//Update the existing entry for this machine/ip if it exists.
string updatesql = string.Format("UPDATE {0} SET logoutstamp=NOW() " +
"WHERE logoutstamp=0 and machine=@machine and ipaddress=@ipaddress", table);
MySqlCommand cmd = new MySqlCommand(updatesql, m_conn);
cmd.Prepare();
cmd.Parameters.AddWithValue("@machine", Environment.MachineName);
cmd.Parameters.AddWithValue("@ipaddress", getIPAddress());
cmd.ExecuteNonQuery();
//Insert new entry for this logon event
string insertsql = string.Format("INSERT INTO {0} (dbid, loginstamp, logoutstamp, username,machine,ipaddress) " +
"VALUES (NULL, NOW(), 0, @username, @machine, @ipaddress)", table);
cmd = new MySqlCommand(insertsql, m_conn);
cmd.Prepare();
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@machine", Environment.MachineName);
cmd.Parameters.AddWithValue("ipaddress", getIPAddress());
cmd.ExecuteNonQuery();
m_logger.DebugFormat("Logged LogOn event for {0} at {1}", username, getIPAddress());
}
//LogOff Event
else if (Reason == SessionChangeReason.SessionLogoff)
{
if (m_conn.State != System.Data.ConnectionState.Open)
m_conn.Open();
string table = Settings.Store.SessionTable;
string updatesql = string.Format("UPDATE {0} SET logoutstamp=NOW() "+
"WHERE logoutstamp=0 AND username=@username AND machine=@machine "+
"AND ipaddress=@ipaddress", table);
MySqlCommand cmd = new MySqlCommand(updatesql, m_conn);
cmd.Prepare();
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@machine", Environment.MachineName);
cmd.Parameters.AddWithValue("@ipaddress", getIPAddress());
cmd.ExecuteNonQuery();
m_logger.DebugFormat("Logged LogOff event for {0} at {1}", username, getIPAddress());
}
return true;
}
//Tests the table based on the registry data. Returns a string indicating the table status.
public string TestTable()
{
if (m_conn == null)
throw new InvalidOperationException("No MySQL Connection present.");
try
{ //Open the connection if it's not presently open
if (m_conn.State != System.Data.ConnectionState.Open)
m_conn.Open();
string table = Settings.Store.SessionTable;
MySqlCommand cmd = new MySqlCommand("SHOW TABLES", m_conn);
bool tableExists = false;
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (Convert.ToString(rdr[0]) == table)
tableExists = true;
}
rdr.Close();
if (!tableExists)
return "Connection was successful, but no table exists. Click \"Create Table\" to create the required table.";
//Table exists, verify columns
string[] columns = { "dbid", "loginstamp", "logoutstamp", "username", "machine", "ipaddress" };
cmd = new MySqlCommand("DESCRIBE " + table, m_conn);
rdr = cmd.ExecuteReader();
int colCt = 0;
//Check each column name and match it against the list of columns, keep count of how many match
while (rdr.Read())
{
string colName = Convert.ToString(rdr[0]);
if (!columns.Contains(colName))
{
rdr.Close();
return "Table exists, but has invalid columns.";
}
colCt++;
}
rdr.Close();
//Check if each column was present
if (colCt == columns.Length)
return "Table exists and is setup correctly.";
else
return "Table exists, but appears to have incorrect columns.";
}
catch (MySqlException ex)
{
return String.Format("Error: {0}", ex.Message);
}
}
//Creates the table based on the registry data. Returns a string indicating the table status.
public string CreateTable()
{
if (m_conn == null)
throw new InvalidOperationException("No MySQL Connection present.");
try
{
if (m_conn.State != System.Data.ConnectionState.Open)
m_conn.Open();
string table = Settings.Store.SessionTable;
string sql = string.Format(
"CREATE TABLE {0} (" +
" dbid BIGINT NOT NULL AUTO_INCREMENT ," +
" loginstamp DATETIME NOT NULL, " +
" logoutstamp DATETIME NOT NULL, " +
" username TEXT NOT NULL, " +
" machine TEXT NOT NULL, " +
" ipaddress TEXT NOT NULL, " +
" INDEX (dbid))", table);
MySqlCommand cmd = new MySqlCommand(sql, m_conn);
cmd.ExecuteNonQuery();
return "Table created.";
}
catch (MySqlException ex)
{
return String.Format("Error: {0}", ex.Message);
}
}
//Provides the MySQL connection to use
public void SetConnection(MySqlConnection m_conn)
{
this.m_conn = m_conn;
}
//Returns the IPv4 address of the current machine
private string getIPAddress(){
IPAddress[] ipList = Dns.GetHostAddresses("");
// Grab the first IPv4 address in the list
foreach (IPAddress addr in ipList)
{
if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return addr.ToString();
}
}
return "-INVALID IP ADDRESS-";
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include "Themes.h"
// Theme uses some unnamed functions, these are the definitions
typedef DWORD (WINAPI *pThemeWait)(DWORD dwTimeout);
typedef BOOL (WINAPI *pThemeWatch)(void);
namespace pGina
{
namespace GINA
{
/* static */
void Themes::Init()
{
HMODULE hDll = LoadLibrary(L"shsvcs.dll");
if(hDll)
return;
pThemeWait themeWait = (pThemeWait) GetProcAddress(hDll, "ThemeWaitForServiceReady");
pThemeWatch themeWatch = (pThemeWatch) GetProcAddress(hDll, "ThemeWatchForStart");
if(themeWait && themeWatch)
{
themeWait(5000);
themeWatch();
}
FreeLibrary(hDll);
}
}
}<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <Windows.h>
#include <string>
#include <Message.h>
#include <PipeClient.h>
namespace pGina
{
namespace Protocol
{
typedef enum MessageType
{
Unknown = 0x00,
Hello = 0x01,
Disconnect = 0x02,
Ack = 0x03,
Log = 0x04,
LoginRequest = 0x05,
LoginResponse = 0x06,
DynLabelRequest = 0x07,
DynLabelResponse= 0x08,
LoginInfoChange = 0x09,
UserInfoRequest = 0x0a,
UserInfoResponse = 0x0b,
ChangePasswordRequest = 0x0c,
ChangePasswordResponse = 0x0d,
};
class MessageBase
{
public:
virtual void FromDynamicMessage(pGina::Messaging::Message * msg)
{
if(msg->Exists<unsigned char>(L"MessageType"))
{
Type(static_cast<MessageType>(msg->Property<unsigned char>(L"MessageType")));
}
}
virtual pGina::Messaging::Message * ToDynamicMessage()
{
pGina::Messaging::Message * msg = new pGina::Messaging::Message();
msg->Property<unsigned char>(L"MessageType", (unsigned char) Type(), pGina::Messaging::Byte);
return msg;
}
MessageType Type() { return m_type; }
void Type(MessageType t) { m_type = t; }
protected:
MessageType m_type;
};
MessageBase * SendRecvPipeMessage(pGina::NamedPipes::PipeClient &client, MessageBase *msg);
MessageBase * SendRecvPipeMessage(pGina::NamedPipes::PipeClient &client, MessageBase &msg);
class HelloMessage : public MessageBase
{
public:
HelloMessage()
{
Type(Hello);
}
};
class DisconnectMessage : public MessageBase
{
public:
DisconnectMessage()
{
Type(Disconnect);
}
};
class AckMessage : public MessageBase
{
public:
AckMessage()
{
Type(Ack);
}
};
class LogMessage : public MessageBase
{
public:
LogMessage()
{
Type(Log);
}
LogMessage(std::wstring const& name, std::wstring const& level, std::wstring const& message)
{
Type(Log);
LoggerName(name);
LoggedMessage(message);
Level(level);
}
std::wstring const& LoggerName() { return m_loggerName; }
void LoggerName(std::wstring const& v) { m_loggerName = v; }
std::wstring const& LoggedMessage() { return m_loggedMessage; }
void LoggedMessage(std::wstring const& v) { m_loggedMessage = v; }
std::wstring const& Level() { return m_level; }
void Level(std::wstring const& v) { m_level = v; }
virtual void FromDynamicMessage(pGina::Messaging::Message * msg)
{
MessageBase::FromDynamicMessage(msg);
if(msg->Exists<std::wstring>(L"LoggerName"))
LoggerName(msg->Property<std::wstring>(L"LoggerName"));
if(msg->Exists<std::wstring>(L"LoggedMessage"))
LoggedMessage(msg->Property<std::wstring>(L"LoggedMessage"));
if(msg->Exists<std::wstring>(L"Level"))
Level(msg->Property<std::wstring>(L"Level"));
}
virtual pGina::Messaging::Message * ToDynamicMessage()
{
pGina::Messaging::Message * msg = MessageBase::ToDynamicMessage();
msg->Property<std::wstring>(L"LoggerName", LoggerName(), pGina::Messaging::String);
msg->Property<std::wstring>(L"LoggedMessage", LoggedMessage(), pGina::Messaging::String);
msg->Property<std::wstring>(L"Level", Level(), pGina::Messaging::String);
return msg;
}
private:
std::wstring m_loggerName;
std::wstring m_loggedMessage;
std::wstring m_level;
};
class LoginRequestMessage : public MessageBase
{
public:
enum LoginReason
{
Login = 0,
Unlock,
CredUI,
};
LoginRequestMessage()
{
Type(LoginRequest);
SessionFromProcessId();
}
LoginRequestMessage(std::wstring const& username, std::wstring const& domain, std::wstring const& password, LoginReason reason)
{
Type(LoginRequest);
Username(username);
Domain(domain);
Password(<PASSWORD>);
SessionFromProcessId();
Reason(reason);
}
LoginRequestMessage(const wchar_t * username, const wchar_t * domain, const wchar_t *password, LoginReason reason)
{
Type(LoginRequest);
Username(username ? username : L"");
Domain(domain ? domain : L"");
Password(password ? password : L"");
SessionFromProcessId();
Reason(reason);
}
std::wstring const& Username() { return m_username; }
void Username(std::wstring const& v) { m_username = v; }
std::wstring const& Password() { return m_password; }
void Password(std::wstring const& v) { m_password = v; }
std::wstring const& Domain() { return m_domain; }
void Domain(std::wstring const& v) { m_domain = v; }
DWORD Session() { return m_session; }
void Session(DWORD const& v) { m_session = v; }
LoginReason Reason() { return m_reason; }
void Reason(LoginReason v) { m_reason = v; }
virtual void FromDynamicMessage(pGina::Messaging::Message * msg)
{
MessageBase::FromDynamicMessage(msg);
if(msg->Exists<std::wstring>(L"Username"))
Username(msg->Property<std::wstring>(L"Username"));
if(msg->Exists<std::wstring>(L"Domain"))
Domain(msg->Property<std::wstring>(L"Domain"));
if(msg->Exists<std::wstring>(L"Password"))
Password(msg->Property<std::wstring>(L"Password"));
if(msg->Exists<int>(L"Session"))
Session(msg->Property<int>(L"Session"));
if(msg->Exists<unsigned char>(L"Reason"))
Reason((LoginReason) msg->Property<unsigned char>(L"Reason"));
}
virtual pGina::Messaging::Message * ToDynamicMessage()
{
pGina::Messaging::Message * msg = MessageBase::ToDynamicMessage();
msg->Property<std::wstring>(L"Username", Username(), pGina::Messaging::String);
msg->Property<std::wstring>(L"Domain", Domain(), pGina::Messaging::String);
msg->Property<std::wstring>(L"Password", Password(), pGina::Messaging::String);
msg->Property<int>(L"Session", Session(), pGina::Messaging::Integer);
msg->Property<unsigned char>(L"Reason", (unsigned char) (Reason()), pGina::Messaging::Byte);
return msg;
}
protected:
std::wstring m_username;
std::wstring m_domain;
std::wstring m_password;
int m_session;
LoginReason m_reason;
protected:
void SessionFromProcessId()
{
DWORD sessionId = -1;
if(ProcessIdToSessionId(GetCurrentProcessId(), &sessionId))
Session(sessionId);
}
};
class LoginResponseMessage : public LoginRequestMessage
{
public:
LoginResponseMessage()
{
Type(LoginResponse);
}
std::wstring Message() { return m_message; }
void Message(std::wstring const& v) { m_message = v; }
bool Result() { return m_result; }
void Result(bool v) { m_result = v; }
virtual void FromDynamicMessage(pGina::Messaging::Message * msg)
{
LoginRequestMessage::FromDynamicMessage(msg);
if(msg->Exists<std::wstring>(L"Message"))
Message(msg->Property<std::wstring>(L"Message"));
if(msg->Exists<bool>(L"Result"))
Result(msg->Property<bool>(L"Result"));
}
virtual pGina::Messaging::Message * ToDynamicMessage()
{
pGina::Messaging::Message * msg = LoginRequestMessage::ToDynamicMessage();
msg->Property<std::wstring>(L"Message", Message(), pGina::Messaging::String);
msg->Property<bool>(L"Result", Result(), pGina::Messaging::Boolean);
return msg;
}
private:
bool m_result;
std::wstring m_message;
};
/* Request for text to be placed within a label in the UI. */
class DynamicLabelRequestMessage : public MessageBase
{
public:
DynamicLabelRequestMessage()
{
Type(DynLabelRequest);
}
DynamicLabelRequestMessage( std::wstring const& name )
{
Type(DynLabelRequest);
m_name = name;
}
std::wstring const& Name() { return m_name; }
void Name(std::wstring const& v) { m_name = v; }
virtual void FromDynamicMessage(pGina::Messaging::Message * msg)
{
MessageBase::FromDynamicMessage(msg);
if(msg->Exists<std::wstring>(L"Name"))
Name(msg->Property<std::wstring>(L"Name"));
}
virtual pGina::Messaging::Message * ToDynamicMessage()
{
pGina::Messaging::Message * msg = MessageBase::ToDynamicMessage();
msg->Property<std::wstring>(L"Name", Name(), pGina::Messaging::String);
return msg;
}
private:
std::wstring m_name;
};
/* Response containing text for a label in the UI. */
class DynamicLabelResponseMessage : public DynamicLabelRequestMessage
{
public:
DynamicLabelResponseMessage()
{
Type(DynLabelResponse);
}
std::wstring const& Text() { return m_text; }
void Text(std::wstring const& v) { m_text = v; }
virtual void FromDynamicMessage(pGina::Messaging::Message * msg)
{
DynamicLabelRequestMessage::FromDynamicMessage(msg);
if(msg->Exists<std::wstring>(L"Text"))
Text(msg->Property<std::wstring>(L"Text"));
}
virtual pGina::Messaging::Message * ToDynamicMessage()
{
pGina::Messaging::Message * msg = DynamicLabelRequestMessage::ToDynamicMessage();
msg->Property<std::wstring>(L"Text", Text(), pGina::Messaging::String);
return msg;
}
private:
std::wstring m_text;
};
/* Request for user information based on session ID. */
class UserInformationRequestMessage : public MessageBase
{
public:
UserInformationRequestMessage()
{
Type(UserInfoRequest);
SessionID(-1);
}
UserInformationRequestMessage( int sess_id )
{
Type(UserInfoRequest);
m_sessid = sess_id;
}
int const& SessionID() { return m_sessid; }
void SessionID(int v) { m_sessid = v; }
virtual void FromDynamicMessage(pGina::Messaging::Message * msg)
{
MessageBase::FromDynamicMessage(msg);
if(msg->Exists<int>(L"SessionID"))
SessionID(msg->Property<int>(L"SessionID"));
}
virtual pGina::Messaging::Message * ToDynamicMessage()
{
pGina::Messaging::Message * msg = MessageBase::ToDynamicMessage();
msg->Property<int>(L"SessionID", SessionID(), pGina::Messaging::Integer);
return msg;
}
private:
int m_sessid;
};
/* Response containing user information. */
class UserInformationResponseMessage : public UserInformationRequestMessage
{
public:
UserInformationResponseMessage()
{
Type(UserInfoResponse);
}
std::wstring const& OriginalUsername() { return m_orig_uname; }
void OriginalUsername(std::wstring const& v) { m_orig_uname = v; }
std::wstring const& Username() { return m_uname; }
void Username(std::wstring const& v) { m_uname = v; }
std::wstring const& Domain() { return m_domain; }
void Domain(std::wstring const& v) { m_domain = v; }
virtual void FromDynamicMessage(pGina::Messaging::Message * msg)
{
UserInformationRequestMessage::FromDynamicMessage(msg);
if(msg->Exists<std::wstring>(L"OriginalUsername"))
OriginalUsername(msg->Property<std::wstring>(L"OriginalUsername"));
if(msg->Exists<std::wstring>(L"Username"))
Username(msg->Property<std::wstring>(L"Username"));
if(msg->Exists<std::wstring>(L"Domain"))
Domain(msg->Property<std::wstring>(L"Domain"));
}
virtual pGina::Messaging::Message * ToDynamicMessage()
{
pGina::Messaging::Message * msg = UserInformationRequestMessage::ToDynamicMessage();
msg->Property<std::wstring>(L"OriginalUsername", OriginalUsername(), pGina::Messaging::String);
msg->Property<std::wstring>(L"Username", Username(), pGina::Messaging::String);
msg->Property<std::wstring>(L"Domain", Domain(), pGina::Messaging::String);
return msg;
}
private:
std::wstring m_orig_uname;
std::wstring m_uname;
std::wstring m_domain;
};
class LoginInfoChangeMessage : public LoginRequestMessage
{
public:
LoginInfoChangeMessage() :
m_fromSession(0),
m_toSession(0)
{
Type(LoginInfoChange);
}
LoginInfoChangeMessage(const wchar_t * username, const wchar_t * domain, const wchar_t *password) :
LoginRequestMessage(username, domain, password, Login),
m_fromSession(0),
m_toSession(0)
{
Type(LoginInfoChange);
}
int FromSession() { return m_fromSession; }
void FromSession(int v) { m_fromSession = v; }
int ToSession() { return m_toSession; }
void ToSession(int v) { m_toSession = v; }
virtual void FromDynamicMessage(pGina::Messaging::Message * msg)
{
LoginRequestMessage::FromDynamicMessage(msg);
if(msg->Exists<int>(L"FromSession"))
FromSession(msg->Property<int>(L"FromSession"));
if(msg->Exists<int>(L"ToSession"))
ToSession(msg->Property<int>(L"ToSession"));
}
virtual pGina::Messaging::Message * ToDynamicMessage()
{
pGina::Messaging::Message * msg = LoginRequestMessage::ToDynamicMessage();
msg->Property<int>(L"ToSession", ToSession(), pGina::Messaging::Integer);
msg->Property<int>(L"FromSession", FromSession(), pGina::Messaging::Integer);
return msg;
}
private:
int m_fromSession;
int m_toSession;
};
class ChangePasswordRequestMessage : public MessageBase
{
public:
ChangePasswordRequestMessage()
{
Type(ChangePasswordRequest);
Username(L"");
Domain(L"");
OldPassword(L"");
NewPassword(L"");
SessionFromProcessId();
}
ChangePasswordRequestMessage(std::wstring const& username, std::wstring const& domain,
std::wstring const& oldPassword, std::wstring const& newPassword)
{
Type(ChangePasswordRequest);
Username(username);
Domain(domain);
OldPassword(oldPassword);
NewPassword(<PASSWORD>);
SessionFromProcessId();
}
std::wstring const& Username() { return m_username; }
void Username(std::wstring const& v) { m_username = v; }
std::wstring const& OldPassword() { return m_oldPassword; }
void OldPassword(std::wstring const& v) { m_oldPassword = v; }
std::wstring const& NewPassword() { return m_newPassword; }
void NewPassword(std::wstring const& v) { m_newPassword = v; }
std::wstring const& Domain() { return m_domain; }
void Domain(std::wstring const& v) { m_domain = v; }
DWORD Session() { return m_session; }
void Session(DWORD const& v) { m_session = v; }
virtual void FromDynamicMessage(pGina::Messaging::Message * msg)
{
MessageBase::FromDynamicMessage(msg);
if(msg->Exists<std::wstring>(L"Username"))
Username(msg->Property<std::wstring>(L"Username"));
if(msg->Exists<std::wstring>(L"Domain"))
Domain(msg->Property<std::wstring>(L"Domain"));
if(msg->Exists<int>(L"Session"))
Session(msg->Property<int>(L"Session"));
if(msg->Exists<std::wstring>(L"OldPassword"))
OldPassword(msg->Property<std::wstring>(L"OldPassword"));
if(msg->Exists<std::wstring>(L"NewPassword"))
OldPassword(msg->Property<std::wstring>(L"NewPassword"));
}
virtual pGina::Messaging::Message * ToDynamicMessage()
{
pGina::Messaging::Message * msg = MessageBase::ToDynamicMessage();
msg->Property<std::wstring>(L"Username", Username(), pGina::Messaging::String);
msg->Property<std::wstring>(L"Domain", Domain(), pGina::Messaging::String);
msg->Property<int>(L"Session", Session(), pGina::Messaging::Integer);
msg->Property<std::wstring>(L"OldPassword", OldPassword(), pGina::Messaging::String);
msg->Property<std::wstring>(L"NewPassword", NewPassword(), pGina::Messaging::String);
return msg;
}
protected:
std::wstring m_username;
std::wstring m_domain;
int m_session;
std::wstring m_oldPassword;
std::wstring m_newPassword;
protected:
void SessionFromProcessId()
{
DWORD sessionId = -1;
if(ProcessIdToSessionId(GetCurrentProcessId(), &sessionId))
Session(sessionId);
}
};
class ChangePasswordResponseMessage : public ChangePasswordRequestMessage
{
public:
ChangePasswordResponseMessage()
{
Type(ChangePasswordResponse);
}
std::wstring Message() { return m_message; }
void Message(std::wstring const& v) { m_message = v; }
bool Result() { return m_result; }
void Result(bool v) { m_result = v; }
virtual void FromDynamicMessage(pGina::Messaging::Message * msg)
{
ChangePasswordRequestMessage::FromDynamicMessage(msg);
if(msg->Exists<std::wstring>(L"Message"))
Message(msg->Property<std::wstring>(L"Message"));
if(msg->Exists<bool>(L"Result"))
Result(msg->Property<bool>(L"Result"));
}
virtual pGina::Messaging::Message * ToDynamicMessage()
{
pGina::Messaging::Message * msg = ChangePasswordRequestMessage::ToDynamicMessage();
msg->Property<std::wstring>(L"Message", Message(), pGina::Messaging::String);
msg->Property<bool>(L"Result", Result(), pGina::Messaging::Boolean);
return msg;
}
private:
bool m_result;
std::wstring m_message;
};
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Reflection;
using Abstractions;
namespace pGina.CredentialProvider.Registration
{
public enum OperationMode
{
INSTALL, UNINSTALL, DISABLE, ENABLE
}
public class Settings
{
// What to do when ExecuteDefaultAction is called.
public OperationMode OpMode { get; set; }
// The GUID of the CP (not needed for GINA)
public Guid ProviderGuid { get; set; }
// The short name of the DLL (not including the extension)
public string ShortName { get; set; }
// The path to the directory containing the DLL (or to a parent directory
// if the DLL is contained in architecture specific subdirectories 'x64' and
// 'Win32'.)
public string Path { get; set; }
public Settings()
{
// Defaults
this.ProviderGuid = new Guid("{D0BEFEFB-3D2C-44DA-BBAD-3B2D04557246}");
this.Path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
this.ShortName = null;
this.OpMode = OperationMode.INSTALL;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using log4net;
using pGina.Shared.Interfaces;
namespace pGina.Plugin.Kerberos
{
public class PluginImpl : IPluginAuthentication, IPluginConfiguration
{
private ILog m_logger = LogManager.GetLogger("Kerberos");
#region Init-plugin
public static Guid PluginUuid
{
get { return new Guid("{16E22B15-4116-4FA4-9BB2-57D54BF61A43}"); }
}
public PluginImpl()
{
using (Process me = Process.GetCurrentProcess())
{
m_logger.DebugFormat("Plugin initialized on {0} in PID: {1} Session: {2}", Environment.MachineName, me.Id, me.SessionId);
}
}
public string Name
{
get { return "KRB5 Authentication Plugin"; }
}
public string Description
{
get { return "Authenticates all users through kerberos"; }
}
public Guid Uuid
{
get { return PluginUuid; }
}
public string Version
{
get
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
#endregion
public void Configure()
{
pGina.Plugin.Kerberos.Configuration myDialog = new pGina.Plugin.Kerberos.Configuration();
myDialog.ShowDialog();
}
public void Starting() { }
public void Stopping() { }
/**
* P/Invoke for the unmanaged function that will deal with the actual athentication of a user through Kerberos
* */
[DllImport("authdll.dll", EntryPoint = "auth_user", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int auth_userx86(string Username, string Password, string Domain, string Ticket);
[DllImport("authdllx64.dll", EntryPoint = "auth_user", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int auth_userx64(string Username, string Password, string Domain, string Ticket);
public static int auth_user(string Username, string Password, string Domain, string Ticket)
{
return IntPtr.Size == 8 /* 64bit */ ? auth_userx64(Username, Password, Domain, Ticket) : auth_userx86(Username, Password, Domain, Ticket);
}
public pGina.Shared.Types.BooleanResult AuthenticateUser(pGina.Shared.Types.SessionProperties properties)
{
pGina.Shared.Types.UserInformation userInfo = properties.GetTrackedSingle<pGina.Shared.Types.UserInformation>();
// Get the Kerberos Realm we are authenticating against from the registry
string krbRealm = Settings.Store.Realm;
//m_logger.InfoFormat("Kerberos Target Realm: {0}", krbRealm);
/**
* Call unmanaged DLL that will deal with Microsofts AcquireCredentialHandle() and InitializeSecurityContext() calls after creating a new SEC_WIN_AUTH_IDENTITY structure
* from the supplied user name, password, and domain. The return result will indicate either success or various kerberos error messages.
* */
int r = auth_user(userInfo.Username, userInfo.Password, krbRealm, "krbtgt/" + krbRealm.ToUpper());
switch (r)
{
/*
* The SPN kerberos target service could not be reached. Format should be <service-name>/REALM where the service is usually krbtgt (kerberos ticket granting ticket) followed by
* the realm you are targeting (all capitals) such as MYREALM.UTAH.EDU
*
* ex: krbtgt/MYREALM.UTAH.EDU
* */
case -2146893039:
return new pGina.Shared.Types.BooleanResult() { Success = false, Message = "Failed to contact authenticating kerberos authority." };
/*
* The user name and/or password supplied at login through pGina does not match in the kerberos realm.
* */
case -2146893044:
return new pGina.Shared.Types.BooleanResult() { Success = false, Message = "Failed due to bad password and/or user name." };
/*
* The SPN for your kerberos target was incorrect. Format should be <service-name>/REALM where the service is usually krbtgt (kerberos ticket granting ticket) followed by
* the realm you are targeting (all capitals) such as MYREALM.UTAH.EDU
*
* ex: krbtgt/MYREALM.UTAH.EDU
* */
case -2146893053:
return new pGina.Shared.Types.BooleanResult() { Success = false, Message = "Failed due to bad kerberos Security Principal Name." };
/*
* Success
* */
case 0:
return new pGina.Shared.Types.BooleanResult() { Success = true, Message = "Success" };
default:
return new pGina.Shared.Types.BooleanResult() { Success = false, Message = "Failed to authenticate due to unknown error." + r };
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using pGina.Shared.Interfaces;
using pGina.Shared.Types;
using MySql.Data.MySqlClient;
namespace pGina.Plugin.MySQLAuth
{
public class PluginImpl : IPluginAuthentication, IPluginAuthorization, IPluginAuthenticationGateway, IPluginConfiguration
{
public static readonly Guid PluginUuid = new Guid("{A89DF410-53CA-4FE1-A6CA-4479B841CA19}");
private ILog m_logger = LogManager.GetLogger("MySQLAuth");
public Shared.Types.BooleanResult AuthenticateUser(Shared.Types.SessionProperties properties)
{
Shared.Types.UserInformation userInfo = properties.GetTrackedSingle<Shared.Types.UserInformation>();
m_logger.DebugFormat("Authenticate: {0}", userInfo.Username);
UserEntry entry = null;
try
{
using (MySqlUserDataSource dataSource = new MySqlUserDataSource())
{
entry = dataSource.GetUserEntry(userInfo.Username);
}
}
catch (MySqlException ex)
{
if (ex.Number == 1042)
m_logger.ErrorFormat("Unable to connect to host: {0}", Settings.Store.Host);
else
{
m_logger.ErrorFormat("{0}", ex);
throw;
}
}
catch (Exception e)
{
m_logger.ErrorFormat("Unexpected error: {0}", e);
throw;
}
if (entry != null)
{
m_logger.DebugFormat("Retrieved info for user {0} from MySQL. Password uses {1}.",
entry.Name, entry.HashAlg.ToString());
bool passwordOk = entry.VerifyPassword(userInfo.Password);
if (passwordOk)
{
m_logger.DebugFormat("Authentication successful for {0}", userInfo.Username);
return new Shared.Types.BooleanResult() { Success = true, Message = "Success." };
}
else
{
m_logger.DebugFormat("Authentication failed for {0}", userInfo.Username);
return new Shared.Types.BooleanResult() { Success = false, Message = "Invalid username or password." };
}
}
else
{
m_logger.DebugFormat("Authentication failed for {0}", userInfo.Username);
return new Shared.Types.BooleanResult() { Success = false, Message = "Invalid username or password." };
}
}
public string Description
{
get { return "Uses a MySQL server as the account database."; }
}
public string Name
{
get { return "MySQL"; }
}
public void Starting()
{
}
public void Stopping()
{
}
public Guid Uuid
{
get { return PluginUuid; }
}
public string Version
{
get
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public void Configure()
{
Configuration dialog = new Configuration();
dialog.ShowDialog();
}
public Shared.Types.BooleanResult AuthenticatedUserGateway(Shared.Types.SessionProperties properties)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
try
{
using (MySqlUserDataSource dataSource = new MySqlUserDataSource())
{
List<GroupGatewayRule> rules = GroupRuleLoader.GetGatewayRules();
foreach (GroupGatewayRule rule in rules)
{
m_logger.DebugFormat("Checking rule: {0}", rule.ToString());
if (rule.RuleMatch(dataSource.IsMemberOfGroup(userInfo.Username, rule.Group)))
{
m_logger.DebugFormat("Rule is a match, adding to {0}", rule.LocalGroup);
userInfo.Groups.Add(new GroupInformation { Name = rule.LocalGroup });
}
else
{
m_logger.DebugFormat("Rule is not a match");
}
}
}
}
catch(MySqlException e)
{
bool preventLogon = Settings.Store.PreventLogonOnServerError;
if( preventLogon )
{
m_logger.DebugFormat("Encountered MySQL server error, and preventing logon: {0}", e.Message);
return new BooleanResult {
Success = false,
Message = string.Format("Preventing logon due to server error: {0}", e.Message)
};
}
else
{
m_logger.DebugFormat("Encoutered MySQL server error, but returning success anyway. Error: {0}", e.Message);
return new BooleanResult {
Success = true,
Message = string.Format("Encountered server error: {0}", e.Message)
};
}
}
catch (Exception e)
{
m_logger.ErrorFormat("Unexpected error: {0}", e);
throw;
}
// Always return success
return new Shared.Types.BooleanResult { Success = true };
}
public BooleanResult AuthorizeUser(SessionProperties properties)
{
m_logger.Debug("MySql Plugin Authorization");
bool requireAuth = Settings.Store.AuthzRequireMySqlAuth;
// If we require authentication, and we failed to auth this user, then we
// fail authorization.
if (requireAuth)
{
PluginActivityInformation actInfo = properties.GetTrackedSingle<PluginActivityInformation>();
try
{
BooleanResult mySqlResult = actInfo.GetAuthenticationResult(this.Uuid);
if (!mySqlResult.Success)
{
m_logger.InfoFormat("Deny because MySQL auth failed, and configured to require MySQL auth.");
return new BooleanResult()
{
Success = false,
Message = "Deny because MySQL authentication failed."
};
}
}
catch (KeyNotFoundException)
{
// The plugin is not enabled for authentication
m_logger.ErrorFormat("MySQL is not enabled for authentication, and authz is configured to require auth.");
return new BooleanResult
{
Success = false,
Message = "Deny because MySQL auth did not execute, and configured to require MySQL auth."
};
}
}
// Get the authz rules from registry
List<GroupAuthzRule> rules = GroupRuleLoader.GetAuthzRules();
if (rules.Count == 0)
{
throw new Exception("No authorization rules found.");
}
try
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
string user = userInfo.Username;
using (MySqlUserDataSource dataSource = new MySqlUserDataSource())
{
foreach (GroupAuthzRule rule in rules)
{
m_logger.DebugFormat("Checking rule: {0}", rule.ToString());
bool inGroup = false;
if (rule.RuleCondition != GroupRule.Condition.ALWAYS)
{
inGroup = dataSource.IsMemberOfGroup(user, rule.Group);
m_logger.DebugFormat("User '{0}' {1} a member of '{2}'", user,
inGroup ? "is" : "is not", rule.Group);
}
if (rule.RuleMatch(inGroup))
{
if (rule.AllowOnMatch)
return new BooleanResult
{
Success = true,
Message = string.Format("Allow via rule '{0}'", rule.ToString() )
};
else
return new BooleanResult
{
Success = false,
Message = string.Format("Deny via rule '{0}'", rule.ToString())
};
}
}
}
// If we get this far, no rules matched. This should never happen since
// the last rule should always match (the default). Throw.
throw new Exception("Missing default authorization rule.");
}
catch (Exception e)
{
m_logger.ErrorFormat("Exception during authorization: {0}", e);
throw;
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include <Windows.h>
#include "Credential.h"
#include "Dll.h"
#pragma warning(push)
#pragma warning(disable : 4995)
#include <shlwapi.h>
#pragma warning(pop)
#include <pGinaNativeLib.h>
#include <Macros.h>
#include "ClassFactory.h"
#include "TileUiTypes.h"
#include "TileUiLogon.h"
#include "TileUiUnlock.h"
#include "TileUiChangePassword.h"
#include "SerializationHelpers.h"
#include "ServiceStateHelper.h"
#include "ProviderGuid.h"
#include "resource.h"
#include <wincred.h>
namespace pGina
{
namespace CredProv
{
IFACEMETHODIMP Credential::QueryInterface(__in REFIID riid, __deref_out void **ppv)
{
// And more crazy ass v-table madness, yay COM again!
static const QITAB qitCredUI[] =
{
QITABENT(Credential, ICredentialProviderCredential),
{ 0 },
};
static const QITAB qit[] =
{
QITABENT(Credential, ICredentialProviderCredential),
QITABENT(Credential, IConnectableCredentialProviderCredential),
{0},
};
if (m_usageScenario == CPUS_CREDUI)
{
return QISearch(this, qitCredUI, riid, ppv);
}
return QISearch(this, qit, riid, ppv);
}
IFACEMETHODIMP_(ULONG) Credential::AddRef()
{
return InterlockedIncrement(&m_referenceCount);
}
IFACEMETHODIMP_(ULONG) Credential::Release()
{
LONG count = InterlockedDecrement(&m_referenceCount);
if (!count)
delete this;
return count;
}
IFACEMETHODIMP Credential::Advise(__in ICredentialProviderCredentialEvents* pcpce)
{
// Release any ref for current ptr (if any)
UnAdvise();
m_logonUiCallback = pcpce;
if(m_logonUiCallback)
{
m_logonUiCallback->AddRef();
}
return S_OK;
}
IFACEMETHODIMP Credential::UnAdvise()
{
if(m_logonUiCallback)
{
m_logonUiCallback->Release();
m_logonUiCallback = NULL;
}
return S_OK;
}
IFACEMETHODIMP Credential::SetSelected(__out BOOL* pbAutoLogon)
{
// We don't do anything special here, but twould be the place to react to our tile being selected
*pbAutoLogon = FALSE;
return S_OK;
}
IFACEMETHODIMP Credential::SetDeselected()
{
// No longer selected, if we have any password fields set, lets zero/clear/free them
ClearZeroAndFreeAnyPasswordFields(true);
return S_OK;
}
IFACEMETHODIMP Credential::GetFieldState(__in DWORD dwFieldID, __out CREDENTIAL_PROVIDER_FIELD_STATE* pcpfs, __out CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE* pcpfis)
{
if(!m_fields || dwFieldID >= m_fields->fieldCount || !pcpfs || !pcpfis)
return E_INVALIDARG;
*pcpfs = m_fields->fields[dwFieldID].fieldStatePair.fieldState;
*pcpfis = m_fields->fields[dwFieldID].fieldStatePair.fieldInteractiveState;
return S_OK;
}
IFACEMETHODIMP Credential::GetStringValue(__in DWORD dwFieldID, __deref_out PWSTR* ppwsz)
{
if(!m_fields || dwFieldID >= m_fields->fieldCount || !ppwsz)
return E_INVALIDARG;
if(IsFieldDynamic(dwFieldID))
{
std::wstring text = GetTextForField(dwFieldID);
if( ! text.empty() )
return SHStrDupW( text.c_str(), ppwsz );
}
// We copy our value with SHStrDupW which uses CoTask alloc, caller owns result
if(m_fields->fields[dwFieldID].wstr)
return SHStrDupW(m_fields->fields[dwFieldID].wstr, ppwsz);
*ppwsz = NULL;
return S_OK;
}
IFACEMETHODIMP Credential::GetBitmapValue(__in DWORD dwFieldID, __out HBITMAP* phbmp)
{
if(!m_fields || dwFieldID >= m_fields->fieldCount || !phbmp)
return E_INVALIDARG;
if(m_fields->fields[dwFieldID].fieldDescriptor.cpft != CPFT_TILE_IMAGE)
return E_INVALIDARG;
HBITMAP bitmap = NULL;
std::wstring tileImage = pGina::Registry::GetString(L"TileImage", L"");
if(tileImage.empty() || tileImage.length() == 1)
{
// Use builtin
bitmap = LoadBitmap(GetMyInstance(), MAKEINTRESOURCE(IDB_PGINA_LOGO));
}
else
{
pDEBUG(L"Credential::GetBitmapValue: Loading image from: %s", tileImage.c_str());
bitmap = (HBITMAP) LoadImageW((HINSTANCE) NULL, tileImage.c_str(), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
}
if (!pGina::Service::StateHelper::GetState())
bitmap = LoadBitmap(GetMyInstance(), MAKEINTRESOURCE(IDB_PGINA_ERROR));
if(!bitmap)
return HRESULT_FROM_WIN32(GetLastError());
*phbmp = bitmap;
return S_OK;
}
IFACEMETHODIMP Credential::GetCheckboxValue(__in DWORD dwFieldID, __out BOOL* pbChecked, __deref_out PWSTR* ppwszLabel)
{
return E_NOTIMPL;
}
IFACEMETHODIMP Credential::GetComboBoxValueCount(__in DWORD dwFieldID, __out DWORD* pcItems, __out_range(<,*pcItems) DWORD* pdwSelectedItem)
{
return E_NOTIMPL;
}
IFACEMETHODIMP Credential::GetComboBoxValueAt(__in DWORD dwFieldID, __in DWORD dwItem, __deref_out PWSTR* ppwszItem)
{
return E_NOTIMPL;
}
IFACEMETHODIMP Credential::GetSubmitButtonValue(__in DWORD dwFieldID, __out DWORD* pdwAdjacentTo)
{
if(!m_fields || dwFieldID >= m_fields->fieldCount || !pdwAdjacentTo)
return E_INVALIDARG;
if(m_fields->fields[dwFieldID].fieldDescriptor.cpft != CPFT_SUBMIT_BUTTON)
return E_INVALIDARG;
*pdwAdjacentTo = m_fields->submitAdjacentTo;
return S_OK;
}
IFACEMETHODIMP Credential::SetStringValue(__in DWORD dwFieldID, __in PCWSTR pwz)
{
if(!m_fields || dwFieldID >= m_fields->fieldCount)
return E_INVALIDARG;
if(m_fields->fields[dwFieldID].fieldDescriptor.cpft != CPFT_EDIT_TEXT &&
m_fields->fields[dwFieldID].fieldDescriptor.cpft != CPFT_PASSWORD_TEXT &&
m_fields->fields[dwFieldID].fieldDescriptor.cpft != CPFT_SMALL_TEXT &&
m_fields->fields[dwFieldID].fieldDescriptor.cpft != CPFT_LARGE_TEXT)
return E_INVALIDARG;
if(m_fields->fields[dwFieldID].wstr)
{
CoTaskMemFree(m_fields->fields[dwFieldID].wstr);
m_fields->fields[dwFieldID].wstr = NULL;
}
if(pwz)
{
return SHStrDupW(pwz, &m_fields->fields[dwFieldID].wstr);
}
return S_OK;
}
IFACEMETHODIMP Credential::SetCheckboxValue(__in DWORD dwFieldID, __in BOOL bChecked)
{
return E_NOTIMPL;
}
IFACEMETHODIMP Credential::SetComboBoxSelectedValue(__in DWORD dwFieldID, __in DWORD dwSelectedItem)
{
return E_NOTIMPL;
}
IFACEMETHODIMP Credential::CommandLinkClicked(__in DWORD dwFieldID)
{
return E_NOTIMPL;
}
IFACEMETHODIMP Credential::Connect(IQueryContinueWithStatus *pqcws)
{
// Reset m_loginResult
m_loginResult.Username(L"");
m_loginResult.Password(L"");
m_loginResult.Domain(L"");
m_loginResult.Message(L"");
m_loginResult.Result(false);
// Workout what our username, and password are. Plugins are responsible for parsing out domain\machine name if needed
PWSTR username = FindUsernameValue();
PWSTR password = FindPasswordValue();
pGina::Transactions::User::LoginResult loginResult;
std::wstring title;
pGina::Memory::ObjectCleanupPool cleanup;
if (pGina::Registry::GetBool(L"PreferLocalAuthentication", false))
{
std::wstring dom = username;
size_t pos = dom.find(L"\\");
if (pos == std::wstring::npos)
{
pos = dom.find(L"@");
if (pos == std::wstring::npos)
{
pDEBUG(L"Credential::Connect: no \"\\\" or \"@\" found in username but PreferLocalAuthentication defined: change username to: \".\\%s\"", dom.c_str());
dom = L".\\";
dom.append(username);
username = _wcsdup(dom.c_str());
}
}
}
pGina::Protocol::LoginRequestMessage::LoginReason reason = pGina::Protocol::LoginRequestMessage::Login;
switch(m_usageScenario)
{
case CPUS_LOGON:
if ( !pGina::Helpers::IsUserLocalAdmin(username) && !pGina::Service::StateHelper::GetState() )
{
pDEBUG(L"Credential::Connect: pGina service is unavailable");
m_loginResult.Message(L"Your login request failed, because the pGina service is not running!\nOnly useres from the local administrator group are able to login.\n\nPlease contact your system administrator.\nReboot the machine to fix this issue.");
SetStringValue(m_fields->usernameFieldIdx, (PCWSTR)L"");
SetStringValue(m_fields->passwordFieldIdx, (PCWSTR)L"");
return S_OK;
}
break;
case CPUS_UNLOCK_WORKSTATION:
reason = pGina::Protocol::LoginRequestMessage::Unlock;
break;
case CPUS_CREDUI:
reason = pGina::Protocol::LoginRequestMessage::CredUI;
break;
case CPUS_CHANGE_PASSWORD:
PWSTR domain = NULL;
PWSTR newPassword = NULL;
PWSTR newPasswordConfirm = NULL;
if ( !pGina::Service::StateHelper::GetState() )
{
pDEBUG(L"Credential::Connect: pGina service is unavailable");
m_loginResult.Message(L"Your password change request failed, because the pGina service is not running!\n\nPlease contact your system administrator.\nReboot the machine to fix this issue.");
return S_OK;
}
title = L"Processing password change for ";
title.append(username);
hdialog = CreateWindowEx(WS_EX_TOPMOST, L"Static", title.c_str(), WS_DLGFRAME, (int)(GetSystemMetrics(SM_CXFULLSCREEN)/2)-137, (int)GetSystemMetrics(SM_CYFULLSCREEN)/2, 275, 15, ::GetForegroundWindow(), NULL, GetMyInstance(), NULL);
if(hdialog != NULL)
{
ShowWindow(hdialog, SW_SHOW);
}
else
{
BlockInput(true);
}
if(m_fields)
{
newPassword = m_fields->fields[CredProv::CPUIFI_NEW_PASSWORD].wstr;
newPasswordConfirm = m_fields->fields[CredProv::CPUIFI_CONFIRM_NEW_PASSWORD].wstr;
}
// Check that the new password and confirmation are exactly the same, if not
// return a failure.
if( (newPassword == NULL || newPasswordConfirm == NULL) || wcscmp(newPassword, newPasswordConfirm ) != 0 )
{
m_loginResult.Message(L"New passwords do not match");
if (hdialog != NULL)
{
DestroyWindow(hdialog);
}
else
{
BlockInput(false);
}
return S_OK;
}
pGina::Service::StateHelper::PushUsername(username, password, pGina::Service::StateHelper::GetLoginChangePassword());
std::wstring dom = username;
size_t pos = dom.find(L"\\");
if (pos != std::wstring::npos)
{
// Down-Level Logon Name
// LogonUser wants username as user principal name if domain is null
// split the Down-Level Logon Name username into username and domain
std::wstring user = dom.substr(pos+1, dom.size()-pos-1);
dom = dom.substr(0,pos);
if (_wcsicmp(dom.c_str(), L"localhost") == 0)
{
dom = L".";
}
pDEBUG(L"Subst domain from username %s %s", user.c_str(), dom.c_str());
username = _wcsdup(user.c_str());
domain = _wcsdup(dom.c_str());
}
else
{
pos = dom.find(L"@");
if (pos != std::wstring::npos)
{
std::wstring user = dom.substr(0, pos);
dom = dom.substr(pos+1, dom.size()-pos-1);
if (_wcsicmp(dom.c_str(), L"@localhost") == 0)
{
dom = L".";
}
pDEBUG(L"Subst domain from username %s %s", user.c_str(), dom.c_str());
username = _wcsdup(user.c_str());
domain = _wcsdup(dom.c_str());
}
}
if (pos == std::wstring::npos)
{
// ctrl+alt+entf event
DWORD mySession = pGina::Helpers::GetCurrentSessionId();
dom = pGina::Helpers::GetSessionDomainName(mySession);
domain = _wcsdup(dom.c_str());
}
cleanup.AddFree(domain);
HANDLE hToken;
if (!LogonUser(username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &hToken))
{
// ERROR_PASSWORD_EXPIRED 1330
// ERROR_PASSWORD_MUST_CHANGE 1907
int passwdChangeRequired[3] = {GetLastError(), ERROR_PASSWORD_EXPIRED, ERROR_PASSWORD_MUST_CHANGE};
pERROR(L"Credential::Connect: CPUS_CHANGE_PASSWORD LogonUser failed:%i", passwdChangeRequired[0]);
for (int x = 1; x < 3; x++)
{
if (passwdChangeRequired[0] == passwdChangeRequired[x])
{
pERROR(L"Credential::Connect: CPUS_CHANGE_PASSWORD LogonUser failed converted to success %d", passwdChangeRequired[0]);
passwdChangeRequired[0] = 0;
break;
}
}
if (passwdChangeRequired[0] == 0)
{
CloseHandle(hToken);
}
else
{
pDEBUG(L"Your old password does not match");
m_loginResult.Message(L"Your old password does not match");
if (hdialog != NULL)
{
DestroyWindow(hdialog);
}
else
{
BlockInput(false);
}
return S_OK;
}
}
else
{
CloseHandle(hToken);
}
loginResult = pGina::Transactions::User::ProcessChangePasswordForUser( username, domain, password, newPassword );
if( !loginResult.Result() )
{
if(loginResult.Message().empty())
{
loginResult.Message(L"Failed to change password, no message from plugins.");
pDEBUG(L"Failed to change password, no message from plugins.");
}
pDEBUG(L"pGina::Transactions::User::ProcessChangePasswordForUser failed: %s", loginResult.Message().c_str());
m_loginResult.Message(loginResult.Message());
if (hdialog != NULL)
{
DestroyWindow(hdialog);
}
else
{
BlockInput(false);
}
return S_OK;
}
pGina::Service::StateHelper::PushUsername(pGina::Service::StateHelper::GetUsername(), newPassword, pGina::Service::StateHelper::GetLoginChangePassword());
if(loginResult.Message().length() > 0)
m_loginResult.Message(loginResult.Message());
else
m_loginResult.Message(L"pGina: Your password was successfully changed");
pDEBUG(L"change password success");
m_loginResult.Username(loginResult.Username());
m_loginResult.Password(loginResult.Password());
m_loginResult.Domain(loginResult.Domain());
m_loginResult.Result(true);
return S_OK;
break;
}
if (m_usageScenario == CPUS_CREDUI)
{
title = L"Processing UAC for ";
title.append(username);
hdialog = CreateWindowEx(WS_EX_TOPMOST, L"Static", title.c_str(), WS_DLGFRAME, (int)(GetSystemMetrics(SM_CXFULLSCREEN)/2)-137, (int)GetSystemMetrics(SM_CYFULLSCREEN)/2, 275, 15, ::GetForegroundWindow(), NULL, GetMyInstance(), NULL);
if(hdialog != NULL)
{
ShowWindow(hdialog, SW_SHOW);
}
else
{
BlockInput(true);
}
}
else
{
title = L"Processing logon for ";
title.append(username);
hThread_dialog = CreateThread(NULL, 0, Credential::Thread_dialog, (LPVOID) title.c_str(), 0, NULL);
if( pqcws )
{
pqcws->SetStatusMessage(L"You will be logged in.\nPlease wait ...");
}
}
pDEBUG(L"Credential::Connect: Processing login for %s", username);
loginResult = pGina::Transactions::User::ProcessLoginForUser(username, NULL, password, reason);
if(!loginResult.Result() && (m_usageScenario != CPUS_CREDUI))
{
pERROR(L"Credential::Connect: Failed attempt");
if(loginResult.Message().length() > 0)
{
m_loginResult.Message(loginResult.Message());
}
else
{
m_loginResult.Message(L"Plugins did not provide a specific error message");
}
if (hThread_dialog != NULL)
{
Credential::Thread_dialog_close(hThread_dialog);
}
return S_OK;
}
// At this point the info has passed to the service and been validated, so now we have to pack it up and provide it back to
// LogonUI/Winlogon as a serialized/packed logon structure.
pGina::Service::StateHelper::PushUsername(username, (password)? password: L"", pGina::Service::StateHelper::GetLoginChangePassword());
m_loginResult.Username(loginResult.Username());
m_loginResult.Password(<PASSWORD>());
m_loginResult.Domain(loginResult.Domain());
m_loginResult.Result(true);
return S_OK;
}
IFACEMETHODIMP Credential::GetSerialization(__out CREDENTIAL_PROVIDER_GET_SERIALIZATION_RESPONSE* pcpgsr, __out CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION* pcpcs,
__deref_out_opt PWSTR* ppwszOptionalStatusText, __out CREDENTIAL_PROVIDER_STATUS_ICON* pcpsiOptionalStatusIcon)
{
// Credential::Connect will have executed prior to this method, which contacts the
// service, so m_loginResult should have the result from the plugins.
if (m_usageScenario == CPUS_CREDUI)
{
Credential::Connect(NULL);
}
if (m_usageScenario == CPUS_CHANGE_PASSWORD && m_loginResult.Result())
{
if(m_loginResult.Message().length() > 0)
SHStrDupW(m_loginResult.Message().c_str(), ppwszOptionalStatusText);
else
SHStrDupW(L"pGina: Your password was successfully changed", ppwszOptionalStatusText);
*pcpgsr = CPGSR_NO_CREDENTIAL_FINISHED;
*pcpsiOptionalStatusIcon = CPSI_SUCCESS;
if (hdialog != NULL)
{
DestroyWindow(hdialog);
}
else
{
BlockInput(false);
}
return S_OK;
}
if (!m_loginResult.Result())
{
if(m_loginResult.Message().length() > 0)
{
SHStrDupW(m_loginResult.Message().c_str(), ppwszOptionalStatusText);
}
else
{
SHStrDupW(L"Process login failed, but a specific error message was not provided", ppwszOptionalStatusText);
}
if (hThread_dialog != NULL)
{
Credential::Thread_dialog_close(hThread_dialog);
}
if(hdialog != NULL)
{
DestroyWindow(hdialog);
}
else
{
BlockInput(false);
}
if (pGina::Registry::GetBool(L"LastUsernameEnable", false))
{
std::wstring sessionUname = pGina::Registry::GetString( L"LastUsername", L"");
if (!sessionUname.empty())
{
m_fields->fields[m_fields->usernameFieldIdx].fieldStatePair.fieldInteractiveState = CPFIS_NONE;
m_fields->fields[m_fields->passwordFieldIdx].fieldStatePair.fieldInteractiveState = CPFIS_FOCUSED;
}
else
{
ClearZeroAndFreeFields(CPFT_EDIT_TEXT, false);
m_fields->fields[m_fields->usernameFieldIdx].fieldStatePair.fieldInteractiveState = CPFIS_FOCUSED;
m_fields->fields[m_fields->passwordFieldIdx].fieldStatePair.fieldInteractiveState = CPFIS_NONE;
}
}
else
{
ClearZeroAndFreeFields(CPFT_EDIT_TEXT, false);
m_fields->fields[m_fields->usernameFieldIdx].fieldStatePair.fieldInteractiveState = CPFIS_FOCUSED;
m_fields->fields[m_fields->passwordFieldIdx].fieldStatePair.fieldInteractiveState = CPFIS_NONE;
}
ClearZeroAndFreeFields(CPFT_PASSWORD_TEXT, false);
*pcpgsr = CPGSR_NO_CREDENTIAL_FINISHED;
*pcpsiOptionalStatusIcon = CPSI_ERROR;
// Win 10 Workarround to redraw the CP after an error
if (Credential::ISwin10())
{
Provider::m_redraw = true;
}
return S_FALSE;
}
pGina::Memory::ObjectCleanupPool cleanup;
PWSTR username = m_loginResult.Username().length() > 0 ? _wcsdup(m_loginResult.Username().c_str()) : NULL;
PWSTR password = m_loginResult.Password().length() > 0 ? _wcsdup(m_loginResult.Password().c_str()) : NULL;
PWSTR domain = m_loginResult.Domain().length() > 0 ? _wcsdup(m_loginResult.Domain().c_str()) : NULL;
cleanup.AddFree(username);
cleanup.AddFree(password);
cleanup.AddFree(domain);
PWSTR protectedPassword = NULL;
HRESULT result = Microsoft::Sample::ProtectIfNecessaryAndCopyPassword(password, m_usageScenario, &protectedPassword);
if(!SUCCEEDED(result))
{
if (hThread_dialog != NULL)
{
Credential::Thread_dialog_close(hThread_dialog);
}
if(hdialog != NULL)
{
DestroyWindow(hdialog);
}
else
{
BlockInput(false);
}
return result;
}
cleanup.Add(new pGina::Memory::CoTaskMemFreeCleanup(protectedPassword));
// CredUI we use CredPackAuthenticationBuffer
if(m_usageScenario == CPUS_CREDUI)
{
// Need username/domain as a single string
PWSTR domainUsername = NULL;
result = Microsoft::Sample::DomainUsernameStringAlloc(domain, username, &domainUsername);
if(SUCCEEDED(result))
{
DWORD size = 0;
BYTE* rawbits = NULL;
if(!CredPackAuthenticationBufferW((CREDUIWIN_PACK_32_WOW & m_usageFlags) ? CRED_PACK_WOW_BUFFER : 0, domainUsername, protectedPassword, rawbits, &size))
{
if(GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
rawbits = (BYTE *)HeapAlloc(GetProcessHeap(), 0, size);
if (rawbits)
{
if(!CredPackAuthenticationBufferW((CREDUIWIN_PACK_32_WOW & m_usageFlags) ? CRED_PACK_WOW_BUFFER : 0, domainUsername, protectedPassword, rawbits, &size))
{
result = HRESULT_FROM_WIN32(GetLastError());
HeapFree(GetProcessHeap(), 0, rawbits);
}
else
{
pcpcs->rgbSerialization = rawbits;
pcpcs->cbSerialization = size;
result = S_OK;
}
}
else
{
result = E_OUTOFMEMORY;
}
}
else
{
result = E_FAIL;
}
}
else
{
result = E_FAIL;
}
}
if(!SUCCEEDED(result))
{
HeapFree(GetProcessHeap(), 0, domainUsername);
if(hdialog != NULL)
{
DestroyWindow(hdialog);
MessageBox(::GetForegroundWindow(), m_loginResult.Message().c_str(), L"Error during login", MB_OK);
}
else
{
BlockInput(false);
}
pGina::Transactions::LoginInfo::Move(username, L"", L"", pGina::Helpers::GetCurrentSessionId(), -1);
return result;
}
}
else if( CPUS_LOGON == m_usageScenario || CPUS_UNLOCK_WORKSTATION == m_usageScenario )
{
// Init kiul
KERB_INTERACTIVE_UNLOCK_LOGON kiul;
result = Microsoft::Sample::KerbInteractiveUnlockLogonInit(domain, username, (password)? password : L"", m_usageScenario, &kiul);
if(!SUCCEEDED(result))
{
if (hThread_dialog != NULL)
{
Credential::Thread_dialog_close(hThread_dialog);
}
return result;
}
// Pack for the negotiate package and include our CLSID
result = Microsoft::Sample::KerbInteractiveUnlockLogonPack(kiul, &pcpcs->rgbSerialization, &pcpcs->cbSerialization);
if(!SUCCEEDED(result))
{
if (hThread_dialog != NULL)
{
Credential::Thread_dialog_close(hThread_dialog);
}
return result;
}
}
ULONG authPackage = 0;
result = Microsoft::Sample::RetrieveNegotiateAuthPackage(&authPackage);
if(!SUCCEEDED(result))
{
if (hThread_dialog != NULL)
{
Credential::Thread_dialog_close(hThread_dialog);
}
if(hdialog != NULL)
{
DestroyWindow(hdialog);
}
else
{
BlockInput(false);
}
return result;
}
pcpcs->ulAuthenticationPackage = authPackage;
pcpcs->clsidCredentialProvider = CLSID_CpGinaProvider;
*pcpgsr = CPGSR_RETURN_CREDENTIAL_FINISHED;
if (hThread_dialog != NULL)
{
Credential::Thread_dialog_close(hThread_dialog);
}
if(hdialog != NULL)
{
DestroyWindow(hdialog);
}
else
{
BlockInput(false);
}
return S_OK;
}
IFACEMETHODIMP Credential::ReportResult(__in NTSTATUS ntsStatus, __in NTSTATUS ntsSubstatus, __deref_out_opt PWSTR* ppwszOptionalStatusText,
__out CREDENTIAL_PROVIDER_STATUS_ICON* pcpsiOptionalStatusIcon)
{
// ERROR_PASSWORD_EXPIRED 1330
// ERROR_PASSWORD_MUST_CHANGE 1907
// ERROR_PASSWORD_CHANGE_REQUIRED 1938
pDEBUG(L"Credential::ReportResult(0x%08x, 0x%08x)", ntsStatus, ntsSubstatus);
*ppwszOptionalStatusText = NULL;
*pcpsiOptionalStatusIcon = CPSI_NONE;
if (ntsStatus == STATUS_PASSWORD_MUST_CHANGE || (ntsStatus == STATUS_ACCOUNT_RESTRICTION && ntsSubstatus == STATUS_PASSWORD_EXPIRED))
{
pGina::Service::StateHelper::PushUsername(pGina::Service::StateHelper::GetUsername().c_str(), pGina::Service::StateHelper::GetPassword().c_str(), true);
m_usageScenario = CPUS_CHANGE_PASSWORD;
pGina::Service::StateHelper::SetProvScenario(m_usageScenario);
}
if (SUCCEEDED(HRESULT_FROM_NT(ntsStatus)))
{
pGina::Service::StateHelper::PushUsername(L"", L"", false);
}
return S_OK;
}
IFACEMETHODIMP Credential::Disconnect()
{
return E_NOTIMPL;
}
Credential::Credential() :
m_referenceCount(1),
m_usageScenario(CPUS_INVALID),
m_logonUiCallback(NULL),
m_fields(NULL),
m_usageFlags(0)
{
AddDllReference();
//if( pGina::Registry::GetBool(L"ShowServiceStatusInLogonUi", true) )
pGina::Service::StateHelper::AddTarget(this);
}
Credential::~Credential()
{
pGina::Service::StateHelper::RemoveTarget(this);
ClearZeroAndFreeAnyTextFields(false); // Free memory used to back text fields, no ui update
ReleaseDllReference();
}
void Credential::Initialize(CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus, UI_FIELDS const& fields, DWORD usageFlags, const wchar_t *username, const wchar_t *password)
{
m_usageScenario = cpus;
m_usageFlags = usageFlags;
if (m_usageScenario == CPUS_LOGON && !pGina::Service::StateHelper::GetState())
{
HANDLE hThread_dialog = CreateThread(NULL, 0, Credential::Thread_dialog, (LPVOID) L"waiting for the pGina service ...", 0, NULL);
for (int x = 0; x < 60; x++)
{
if (pGina::Service::StateHelper::GetState()) break;
Sleep(1000);
}
Credential::Thread_dialog_close(hThread_dialog);
}
// Allocate and copy our UI_FIELDS struct, we need our own copy to set/track the state of
// our fields over time
m_fields = (UI_FIELDS *) (malloc(sizeof(UI_FIELDS) + (sizeof(UI_FIELD) * fields.fieldCount)));
m_fields->fieldCount = fields.fieldCount;
m_fields->submitAdjacentTo = fields.submitAdjacentTo;
m_fields->usernameFieldIdx = fields.usernameFieldIdx;
m_fields->passwordFieldIdx = fields.passwordFieldIdx;
m_fields->statusFieldIdx = fields.statusFieldIdx;
for(DWORD x = 0; x < fields.fieldCount; x++)
{
m_fields->fields[x].fieldDescriptor = fields.fields[x].fieldDescriptor;
m_fields->fields[x].fieldStatePair = fields.fields[x].fieldStatePair;
m_fields->fields[x].fieldDataSource = fields.fields[x].fieldDataSource;
m_fields->fields[x].wstr = NULL;
if(fields.fields[x].wstr && !IsFieldDynamic(x))
{
SHStrDup(fields.fields[x].wstr, &m_fields->fields[x].wstr);
}
if(IsFieldDynamic(x))
{
std::wstring text = GetTextForField(x);
if( ! text.empty() )
{
SHStrDup( text.c_str(), &m_fields->fields[x].wstr );
}
}
}
if(username != NULL)
{
SHStrDupW(username, &(m_fields->fields[m_fields->usernameFieldIdx].wstr));
// If the username field has focus, hand focus over to the password field
if(m_fields->fields[m_fields->usernameFieldIdx].fieldStatePair.fieldInteractiveState == CPFIS_FOCUSED)
{
m_fields->fields[m_fields->usernameFieldIdx].fieldStatePair.fieldInteractiveState = CPFIS_NONE;
m_fields->fields[m_fields->passwordFieldIdx].fieldStatePair.fieldInteractiveState = CPFIS_FOCUSED;
}
}
else if(m_usageScenario == CPUS_UNLOCK_WORKSTATION)
{
DWORD mySession = pGina::Helpers::GetCurrentSessionId();
std::wstring username, domain; // Username and domain to be determined
std::wstring usernameFieldValue; // The value for the username field
std::wstring machineName = pGina::Helpers::GetMachineName();
// Get user information from service (if available)
pDEBUG(L"Retrieving user information from service.");
pGina::Transactions::LoginInfo::UserInformation userInfo =
pGina::Transactions::LoginInfo::GetUserInformation(mySession);
pDEBUG(L"Received: original uname: '%s' uname: '%s' domain: '%s'",
userInfo.OriginalUsername().c_str(), userInfo.Username().c_str(), userInfo.Domain().c_str());
// Grab the domain if available
if( ! userInfo.Domain().empty() )
domain = userInfo.Domain();
// Are we configured to use the original username?
if( pGina::Registry::GetBool(L"UseOriginalUsernameInUnlockScenario", false) )
username = userInfo.OriginalUsername();
else
username = userInfo.Username();
// If we didn't get a username/domain from the service, try to get it from WTS
if( username.empty() )
username = pGina::Helpers::GetSessionUsername(mySession);
if( domain.empty() )
domain = pGina::Helpers::GetSessionDomainName(mySession);
if(!domain.empty() && _wcsicmp(domain.c_str(), machineName.c_str()) != 0)
{
usernameFieldValue += domain;
usernameFieldValue += L"\\";
}
usernameFieldValue += username;
SHStrDupW(usernameFieldValue.c_str(), &(m_fields->fields[m_fields->usernameFieldIdx].wstr));
}
else if( CPUS_CHANGE_PASSWORD == m_usageScenario )
{
DWORD mySession = pGina::Helpers::GetCurrentSessionId();
std::wstring sessionUname = pGina::Helpers::GetSessionUsername(mySession);
SHStrDupW(sessionUname.c_str(), &(m_fields->fields[m_fields->usernameFieldIdx].wstr));
m_fields->fields[m_fields->usernameFieldIdx].fieldStatePair.fieldState = CPFS_HIDDEN;
m_fields->fields[m_fields->passwordFieldIdx].fieldStatePair.fieldInteractiveState = CPFIS_FOCUSED;
}
else if( CPUS_LOGON == m_usageScenario )
{
if( pGina::Registry::GetBool(L"LastUsernameEnable", false) )
{
std::wstring sessionUname = pGina::Registry::GetString( L"LastUsername", L"");
if (!sessionUname.empty())
{
SHStrDupW(sessionUname.c_str(), &(m_fields->fields[m_fields->usernameFieldIdx].wstr));
m_fields->fields[m_fields->usernameFieldIdx].fieldStatePair.fieldInteractiveState = CPFIS_NONE;
m_fields->fields[m_fields->passwordFieldIdx].fieldStatePair.fieldInteractiveState = CPFIS_FOCUSED;
}
}
}
if(password != NULL)
{
SHStrDupW(password, &(m_fields->fields[m_fields->passwordFieldIdx].wstr));
}
// Hide MOTD field if not enabled
if( ! pGina::Registry::GetBool(L"EnableMotd", true) )
{
if( m_usageScenario == CPUS_LOGON )
m_fields->fields[CredProv::LUIFI_MOTD].fieldStatePair.fieldState = CPFS_HIDDEN;
if( m_usageScenario == CPUS_CHANGE_PASSWORD )
m_fields->fields[CredProv::CPUIFI_MOTD].fieldStatePair.fieldState = CPFS_HIDDEN;
}
// Hide service status if configured to do so
if( ! pGina::Registry::GetBool(L"ShowServiceStatusInLogonUi", true) )
{
if( m_usageScenario == CPUS_UNLOCK_WORKSTATION )
m_fields->fields[CredProv::LOIFI_STATUS].fieldStatePair.fieldState = CPFS_HIDDEN;
else if( m_usageScenario == CPUS_LOGON )
m_fields->fields[CredProv::LUIFI_STATUS].fieldStatePair.fieldState = CPFS_HIDDEN;
else if( m_usageScenario == CPUS_CHANGE_PASSWORD )
m_fields->fields[CredProv::CPUIFI_STATUS].fieldStatePair.fieldState = CPFS_HIDDEN;
}
}
void Credential::ClearZeroAndFreeAnyPasswordFields(bool updateUi)
{
ClearZeroAndFreeFields(CPFT_PASSWORD_TEXT, updateUi);
}
void Credential::ClearZeroAndFreeAnyTextFields(bool updateUi)
{
ClearZeroAndFreeFields(CPFT_PASSWORD_TEXT, updateUi);
ClearZeroAndFreeFields(CPFT_EDIT_TEXT, updateUi);
}
void Credential::ClearZeroAndFreeFields(CREDENTIAL_PROVIDER_FIELD_TYPE type, bool updateUi)
{
if(!m_fields) return;
for(DWORD x = 0; x < m_fields->fieldCount; x++)
{
if(m_fields->fields[x].fieldDescriptor.cpft == type)
{
if(m_fields->fields[x].wstr)
{
size_t len = wcslen(m_fields->fields[x].wstr);
SecureZeroMemory(m_fields->fields[x].wstr, len * sizeof(wchar_t));
CoTaskMemFree(m_fields->fields[x].wstr);
m_fields->fields[x].wstr = NULL;
// If we've been advised, we can tell the UI so the UI correctly reflects that this
// field is not set any longer (set it to empty string)
if(m_logonUiCallback && updateUi)
{
m_logonUiCallback->SetFieldString(this, m_fields->fields[x].fieldDescriptor.dwFieldID, L"");
}
}
}
}
}
PWSTR Credential::FindUsernameValue()
{
if(!m_fields) return NULL;
return m_fields->fields[m_fields->usernameFieldIdx].wstr;
}
PWSTR Credential::FindPasswordValue()
{
if(!m_fields) return NULL;
return m_fields->fields[m_fields->passwordFieldIdx].wstr;
}
DWORD Credential::FindStatusId()
{
if(!m_fields) return 0;
return m_fields->statusFieldIdx;
}
bool Credential::IsFieldDynamic(DWORD dwFieldID)
{
// Retrieve data for dynamic fields
return (m_fields->fields[dwFieldID].fieldDataSource == SOURCE_DYNAMIC ||
(m_fields->fields[dwFieldID].fieldDataSource == SOURCE_CALLBACK && m_fields->fields[dwFieldID].labelCallback != NULL) ||
m_fields->fields[dwFieldID].fieldDataSource == SOURCE_STATUS);
}
std::wstring Credential::GetTextForField(DWORD dwFieldID)
{
// Retrieve data for dynamic fields
if( m_fields->fields[dwFieldID].fieldDataSource == SOURCE_DYNAMIC )
{
return pGina::Transactions::TileUi::GetDynamicLabel( m_fields->fields[dwFieldID].fieldDescriptor.pszLabel );
}
else if(m_fields->fields[dwFieldID].fieldDataSource == SOURCE_CALLBACK && m_fields->fields[dwFieldID].labelCallback != NULL)
{
return m_fields->fields[dwFieldID].labelCallback(m_fields->fields[dwFieldID].fieldDescriptor.pszLabel, m_fields->fields[dwFieldID].fieldDescriptor.dwFieldID);
}
else if(m_fields->fields[dwFieldID].fieldDataSource == SOURCE_STATUS)
{
return pGina::Service::StateHelper::GetStateText();
}
return L"";
}
void Credential::ServiceStateChanged(bool newState)
{
ClearZeroAndFreeFields(CPFT_PASSWORD_TEXT, true);
if( !pGina::Registry::GetBool(L"LastUsernameEnable", false) )
{
ClearZeroAndFreeFields(CPFT_EDIT_TEXT, true);
}
if(m_logonUiCallback)
{
std::wstring text = pGina::Service::StateHelper::GetStateText();
m_logonUiCallback->SetFieldString(this, FindStatusId(), text.c_str());
}
}
DWORD WINAPI Credential::Thread_dialog(LPVOID lpParameter)
{
HWND dialog;
dialog = CreateWindowEx(WS_EX_TOPMOST, L"Static", (LPWSTR)lpParameter, WS_DLGFRAME, (int)(GetSystemMetrics(SM_CXFULLSCREEN)/2)-137, (int)GetSystemMetrics(SM_CYFULLSCREEN)/2, 275, 15, ::GetForegroundWindow(), NULL, GetMyInstance(), NULL);
if(dialog == NULL)
{
pDEBUG(L"Credential::Thread_dialog: CreateWindowEx Error %X", HRESULT_FROM_WIN32(::GetLastError()));
}
ShowWindow(dialog, SW_SHOW);
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, GetCurrentThreadId());
SuspendThread(hThread);
CloseHandle(hThread);
DestroyWindow(dialog);
return 0;
}
void Credential::Thread_dialog_close(HANDLE thread)
{
while (ResumeThread(thread) == 0)
Sleep(1050);
WaitForSingleObject(thread, 1000);
CloseHandle(thread);
}
// https://stackoverflow.com/questions/36543301/detecting-windows-10-version/36543774#36543774
BOOL Credential::ISwin10()
{
RTL_OSVERSIONINFOW rovi = { 0 };
HMODULE hMod = ::GetModuleHandle(L"ntdll.dll");
if (hMod)
{
Credential::RtlGetVersionPtr fxPtr = (Credential::RtlGetVersionPtr)::GetProcAddress(hMod, "RtlGetVersion");
if (fxPtr != nullptr)
{
rovi.dwOSVersionInfoSize = sizeof(rovi);
if (fxPtr(&rovi) != 0)
{
rovi.dwMajorVersion = 10;
}
}
FreeLibrary(hMod);
}
if (rovi.dwMajorVersion == 10)
{
return true;
}
return false;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace pGina.Plugin.MySqlLogger
{
public partial class Configuration : Form
{
public Configuration()
{
InitializeComponent();
InitUI();
}
private void InitUI()
{
this.sessionModeCB.Checked = Settings.Store.SessionMode;
this.eventModeCB.Checked = Settings.Store.EventMode;
string host = Settings.Store.Host;
this.hostTB.Text = host;
string port = string.Format("{0}", Settings.Store.Port); //Might be stored as an int
this.portTB.Text = port;
string db = Settings.Store.Database;
this.dbTB.Text = db;
string sessionTable = Settings.Store.SessionTable;
this.sessionTableTB.Text = sessionTable;
string eventTable = Settings.Store.EventTable;
this.eventTableTB.Text = eventTable;
string user = Settings.Store.User;
this.userTB.Text = user;
string pass = Settings.Store.GetEncryptedSetting("Password");
this.passwdTB.Text = pass;
bool setting = Settings.Store.EvtLogon;
this.logonEvtCB.Checked = setting;
setting = Settings.Store.EvtLogoff;
this.logoffEvtCB.Checked = setting;
setting = Settings.Store.EvtLock;
this.lockEvtCB.Checked = setting;
setting = Settings.Store.EvtUnlock;
this.unlockEvtCB.Checked = setting;
setting = Settings.Store.EvtConsoleConnect;
this.consoleConnectEvtCB.Checked = setting;
setting = Settings.Store.EvtConsoleDisconnect;
this.consoleDisconnectEvtCB.Checked = setting;
setting = Settings.Store.EvtRemoteControl;
this.remoteControlEvtCB.Checked = setting;
setting = Settings.Store.EvtRemoteConnect;
this.remoteConnectEvtCB.Checked = setting;
setting = Settings.Store.EvtRemoteDisconnect;
this.remoteDisconnectEvtCB.Checked = setting;
this.useModNameCB.Checked = Settings.Store.UseModifiedName;
updateUIOnModeChange();
}
private void okBtn_Click(object sender, EventArgs e)
{
if (Save())
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
}
private void cancelBtn_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
private bool Save()
{
try
{
int port = Convert.ToInt32((String)this.portTB.Text.Trim());
Settings.Store.Port = this.portTB.Text.Trim();
}
catch (FormatException)
{
MessageBox.Show("Invalid port number.");
return false;
}
if (sessionModeCB.Checked && eventModeCB.Checked
&& sessionTableTB.Text.Trim() == eventTableTB.Text.Trim())
{
MessageBox.Show("The Event Table must be different from the Session Table.");
return false;
}
Settings.Store.SessionMode = sessionModeCB.Checked;
Settings.Store.EventMode = eventModeCB.Checked;
Settings.Store.Host = this.hostTB.Text.Trim();
Settings.Store.Database = this.dbTB.Text.Trim();
Settings.Store.EventTable = this.eventTableTB.Text.Trim();
Settings.Store.SessionTable = this.sessionTableTB.Text.Trim();
Settings.Store.User = this.userTB.Text.Trim();
Settings.Store.SetEncryptedSetting("Password", this.passwdTB.Text);
Settings.Store.EvtLogon = this.logonEvtCB.Checked;
Settings.Store.EvtLogoff = this.logoffEvtCB.Checked;
Settings.Store.EvtLock = this.lockEvtCB.Checked;
Settings.Store.EvtUnlock = this.unlockEvtCB.Checked;
Settings.Store.EvtConsoleConnect = this.consoleConnectEvtCB.Checked;
Settings.Store.EvtConsoleDisconnect = this.consoleDisconnectEvtCB.Checked;
Settings.Store.EvtRemoteControl = this.remoteControlEvtCB.Checked;
Settings.Store.EvtRemoteConnect = this.remoteConnectEvtCB.Checked;
Settings.Store.EvtRemoteDisconnect = this.remoteDisconnectEvtCB.Checked;
Settings.Store.UseModifiedName = this.useModNameCB.Checked;
return true;
}
private void testButton_Click(object sender, EventArgs e)
{
if (!Save()) //Will pop up a message box with appropriate error.
return;
try
{
string sessionModeMsg = null;
string eventModeMsg = null;
if ((bool)Settings.Store.SessionMode)
{
ILoggerMode mode = LoggerModeFactory.getLoggerMode(LoggerMode.SESSION);
sessionModeMsg = mode.TestTable();
}
if ((bool)Settings.Store.EventMode)
{
ILoggerMode mode = LoggerModeFactory.getLoggerMode(LoggerMode.EVENT);
eventModeMsg = mode.TestTable();
}
//Show one or both messages
if (sessionModeMsg != null && eventModeMsg != null)
{
MessageBox.Show(String.Format("Event Mode Table: {0}\nSession Mode Table: {1}", eventModeMsg, sessionModeMsg));
}
else
{
MessageBox.Show(sessionModeMsg ?? eventModeMsg);
}
}
catch (Exception ex)
{
MessageBox.Show(String.Format("The following error occurred: {0}", ex.Message));
}
//Since the server info may change, close the connection
LoggerModeFactory.closeConnection();
}
private void createTableBtn_Click(object sender, EventArgs e)
{
if (!Save())
return;
try
{
string sessionModeMsg = null;
string eventModeMsg = null;
if ((bool)Settings.Store.SessionMode)
{
ILoggerMode mode = LoggerModeFactory.getLoggerMode(LoggerMode.SESSION);
sessionModeMsg = mode.CreateTable();
}
if ((bool)Settings.Store.EventMode)
{
ILoggerMode mode = LoggerModeFactory.getLoggerMode(LoggerMode.EVENT);
eventModeMsg = mode.CreateTable();
}
//Show one or both messages
if (sessionModeMsg != null && eventModeMsg != null)
{
MessageBox.Show(String.Format("Event Mode Table: {0}\nSession Mode Table: {1}", eventModeMsg, sessionModeMsg));
}
else
{
MessageBox.Show(sessionModeMsg ?? eventModeMsg);
}
}
catch (Exception ex)
{
MessageBox.Show("The following error occurred: {0}", ex.Message);
}
//Since the server info may change, close the current connection
LoggerModeFactory.closeConnection();
}
private void updateUIOnModeChange()
{ //Enables/disables the events box based on the mode selected.
eventsBox.Enabled = eventModeCB.Checked;
eventTableTB.Enabled = eventModeCB.Checked;
sessionTableTB.Enabled = sessionModeCB.Checked;
}
private void showPassCB_CheckedChanged(object sender, EventArgs e)
{
this.passwdTB.UseSystemPasswordChar = !this.showPassCB.Checked;
}
private void ModeChange(object sender, EventArgs e)
{
updateUIOnModeChange();
}
private void Btn_help(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/mysql_logger.html");
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
namespace pGina.Configuration
{
class CredProvFilterConfig
{
private static readonly string CRED_PROV_KEY = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers";
public static List<CredProv> LoadCredProvsAndFilterSettings()
{
Dictionary<Guid, CredProv> result = new Dictionary<Guid, CredProv>();
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(CRED_PROV_KEY))
{
if (key != null)
{
string[] subKeys = key.GetSubKeyNames();
foreach (string sub in subKeys)
{
using (RegistryKey cpKey = key.OpenSubKey(sub))
{
if (cpKey != null)
{
CredProv credProv = null;
try
{
credProv = new CredProv
{
Uuid = new Guid(sub)
};
}
catch (System.FormatException)
{
// Ignore entries that are not GUIDs
continue;
}
object name = cpKey.GetValue("");
if (name != null)
{
credProv.Name = name.ToString();
}
else
{
credProv.Name = credProv.Uuid.ToString();
}
if (!result.ContainsKey(credProv.Uuid))
{
result.Add(credProv.Uuid, credProv);
}
}
}
}
}
}
// Load filter settings from registry
string[] filterSettings = pGina.Core.Settings.Get.CredentialProviderFilters;
List<CredProv> filterSettingsList = new List<CredProv>();
foreach (string s in filterSettings)
filterSettingsList.Add(CredProv.FromRegString(s));
// Merge registry settings into the dictionary
foreach (CredProv cp in filterSettingsList)
{
if (result.ContainsKey(cp.Uuid))
{
cp.Name = result[cp.Uuid].Name;
result[cp.Uuid] = cp;
}
}
return result.Values.ToList();
}
public static void SaveFilterSettings(List<CredProv> list)
{
List<string> filters = new List<string>();
foreach (CredProv cp in list)
{
if (cp.FilterEnabled())
{
filters.Add(cp.ToRegString());
}
}
string[] result = filters.ToArray();
pGina.Core.Settings.Get.CredentialProviderFilters = result;
}
}
class CredProv
{
public string Name { get; set; }
public Guid Uuid { get; set; }
public bool FilterLogon { get; set; }
public bool FilterUnlock { get; set; }
public bool FilterChangePass { get; set; }
public bool FilterCredUI { get; set; }
public bool FilterEnabled()
{
return FilterLogon || FilterUnlock || FilterChangePass || FilterCredUI;
}
public string ToRegString()
{
int filter = 0;
if (FilterLogon) filter |= 0x1;
if (FilterUnlock) filter |= 0x2;
if (FilterChangePass) filter |= 0x4;
if (FilterCredUI) filter |= 0x8;
return string.Format("{{{0}}}\t{1}", Uuid.ToString(), filter);
}
public static CredProv FromRegString(string str)
{
string[] parts = str.Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
CredProv result = new CredProv
{
Uuid = new Guid(parts[0])
};
int filter = Convert.ToInt32(parts[1]);
if ((filter & 0x1) != 0) result.FilterLogon = true;
if ((filter & 0x2) != 0) result.FilterUnlock = true;
if ((filter & 0x4) != 0) result.FilterChangePass = true;
if ((filter & 0x8) != 0) result.FilterCredUI = true;
return result;
}
}
}
<file_sep>using System;
using System.DirectoryServices.AccountManagement;
using System.Diagnostics;
using pGina.Shared.Interfaces;
using pGina.Shared.Types;
using log4net;
namespace pGina.Plugin.HttpAuth
{
public class PluginImpl : IPluginConfiguration, IPluginAuthentication, IPluginAuthenticationGateway, IPluginChangePassword
{
private static ILog m_logger = LogManager.GetLogger("HttpAuth");
#region Init-plugin
public static Guid PluginUuid
{
get { return new Guid("{C4FF794F-5843-4BEF-90BA-B5E4E488C662}"); }
}
public PluginImpl()
{
using (Process me = Process.GetCurrentProcess())
{
m_logger.DebugFormat("Plugin initialized on {0} in PID: {1} Session: {2}", Environment.MachineName, me.Id, me.SessionId);
}
}
public string Name
{
get { return "HttpAuth"; }
}
public string Description
{
get { return "Uses http(s) request to obtain user info"; }
}
public Guid Uuid
{
get { return PluginUuid; }
}
public string Version
{
get
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
#endregion
public void Starting() { }
public void Stopping() { }
public void Configure()
{
Configuration dialog = new Configuration();
dialog.ShowDialog();
}
public BooleanResult AuthenticateUser(SessionProperties properties)
{
// this method shall say if our credentials are valid
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
return HttpAccessor.getResponse(userInfo.Username, userInfo.Password);
}
public BooleanResult AuthenticatedUserGateway(SessionProperties properties)
{
// this method shall perform some other tasks ...
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
UInfo uinfo = HttpAccessor.getUserInfo(userInfo.Username);
if (uinfo != null)
{
m_logger.DebugFormat("AuthenticatedUserGateway: Uinfo: {0}", uinfo.ToString());
foreach (string group in uinfo.groups)
{
userInfo.AddGroup(new GroupInformation() { Name = group });
}
properties.AddTrackedSingle<UserInformation>(userInfo);
// and what else ??? :)
}
return new BooleanResult() { Success = true };
}
public BooleanResult ChangePassword(SessionProperties properties, ChangePasswordPluginActivityInfo pluginInfo)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
m_logger.DebugFormat("ChangePassword(): {0}", userInfo.ToString());
// Verify the old password
if (Abstractions.WindowsApi.pInvokes.ValidateCredentials(userInfo.Username, userInfo.oldPassword))
{
m_logger.DebugFormat("Authenticated via old password: {0}", userInfo.Username);
}
else
{
return new BooleanResult { Success = false, Message = "Current password or username is not valid." };
}
return HttpAccessor.getPwChangeResponse(userInfo.Username, userInfo.Password, userInfo.oldPassword);
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Threading;
using System.ServiceProcess;
using System.ComponentModel;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Net;
using log4net;
using pGina.Shared.Settings;
using pGina.Shared.Logging;
using pGina.Shared.Interfaces;
using pGina.Core;
using pGina.Core.Messages;
using pGina.Shared.Types;
using Abstractions.Pipes;
using Abstractions.Logging;
using Abstractions.Helpers;
namespace pGina.Service.Impl
{
public class Service
{
private ILog m_logger = LogManager.GetLogger("pGina.Service.Impl");
private ILog m_abstractLogger = LogManager.GetLogger("Abstractions");
private PipeServer m_server = null;
private ObjectCache<int, List<SessionProperties>> m_sessionPropertyCache = new ObjectCache<int, List<SessionProperties>>();
private List<int> sessionlogoff = new List<int>();
static Service()
{
try
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Framework.Init();
}
catch (Exception ex)
{
EventLog.WriteEntry("pGina", ex.ToString(), EventLogEntryType.Error);
throw;
}
}
public static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args)
{
try
{
ILog logger = LogManager.GetLogger("pGina.Service.Exception");
Exception e = args.ExceptionObject as Exception;
logger.ErrorFormat("CurrentDomain_UnhandledException: {0}", e);
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), "", "", String.Format("pGina: CurrentDomain_UnhandledException {0}", Environment.MachineName), e.ToString());
}
catch
{
// don't kill the existing exception stack with one of our own
}
}
private void HookUpAbstractionsLibraryLogging()
{
LibraryLogging.AddListener(LibraryLogging.Level.Debug, m_abstractLogger.DebugFormat);
LibraryLogging.AddListener(LibraryLogging.Level.Error, m_abstractLogger.ErrorFormat);
LibraryLogging.AddListener(LibraryLogging.Level.Info, m_abstractLogger.InfoFormat);
LibraryLogging.AddListener(LibraryLogging.Level.Warn, m_abstractLogger.WarnFormat);
}
private void DetachAbstractionsLibraryLogging()
{
LibraryLogging.RemoveListener(LibraryLogging.Level.Debug, m_abstractLogger.DebugFormat);
LibraryLogging.RemoveListener(LibraryLogging.Level.Error, m_abstractLogger.ErrorFormat);
LibraryLogging.RemoveListener(LibraryLogging.Level.Info, m_abstractLogger.InfoFormat);
LibraryLogging.RemoveListener(LibraryLogging.Level.Warn, m_abstractLogger.WarnFormat);
}
public string[] PluginDirectories
{
get { return Core.Settings.Get.PluginDirectories; }
}
public Service()
{
try
{
string pipeName = Core.Settings.Get.ServicePipeName;
int maxClients = Core.Settings.Get.MaxClients;
m_logger.InfoFormat("pGina version: {0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
m_logger.DebugFormat("Service created - PipeName: {0} MaxClients: {1}", pipeName, maxClients);
m_logger.DebugFormat("System Info: {0}", Abstractions.Windows.OsInfo.OsDescription());
m_server = new PipeServer(pipeName, maxClients, (Func<IDictionary<string, object>, IDictionary<string, object>>)HandleMessage);
m_logger.DebugFormat("Using plugin directories: ");
foreach (string dir in PluginDirectories)
m_logger.DebugFormat(" {0}", dir);
}
catch (Exception e)
{
EventLog.WriteEntry("pGina", e.ToString(), EventLogEntryType.Error);
m_logger.ErrorFormat("Service startup error: {0}", e.ToString());
throw;
}
}
public void Start()
{
m_logger.InfoFormat("Starting service");
HookUpAbstractionsLibraryLogging();
m_server.Start();
PluginDriver.Starting();
}
public void Stop()
{
m_logger.InfoFormat("Stopping service");
PluginDriver.Stopping();
DetachAbstractionsLibraryLogging();
m_server.Stop();
}
public Boolean OnCustomCommand()
{
Boolean result = Convert.ToBoolean(sessionlogoff.Count);
foreach (IPluginLogoffRequestAddTime plugin in PluginLoader.GetOrderedPluginsOfType<IPluginLogoffRequestAddTime>())
{
try
{
if (plugin.LogoffRequestAddTime())
result = true;
}
catch (Exception e)
{
m_logger.ErrorFormat("Ignoring unhandled exception from {0}: {1}", plugin.Uuid, e);
result = false;
}
}
return result;
}
public void SessionChange(int sessionID, SessionChangeReason evnt)
{
m_logger.InfoFormat("SessionChange:{0} {1}", sessionID, (int)evnt);
Thread rem_local = new Thread(() => SessionChangeThread(sessionID, evnt));
rem_local.Start();
}
/*
public void SessionChange(SessionChangeDescription changeDescription)
{
m_logger.InfoFormat("SessionChange: {0} -> {1}", changeDescription.SessionId, changeDescription.Reason);
try
{
lock (m_sessionPropertyCache)
{
foreach (IPluginEventNotifications plugin in PluginLoader.GetOrderedPluginsOfType<IPluginEventNotifications>())
{
try
{
if (m_sessionPropertyCache.Exists(changeDescription.SessionId))
plugin.SessionChange(changeDescription, m_sessionPropertyCache.Get(changeDescription.SessionId));
else
plugin.SessionChange(changeDescription, null);
}
catch (Exception e)
{
m_logger.ErrorFormat("Ignoring unhandled exception from {0}: {1}", plugin.Uuid, e);
}
}
// If this is a logout, remove from our map
if (changeDescription.Reason == SessionChangeReason.SessionLogoff && m_sessionPropertyCache.Exists(changeDescription.SessionId))
m_sessionPropertyCache.Remove(changeDescription.SessionId);
}
}
catch (Exception e)
{
m_logger.ErrorFormat("Exception while handling SessionChange event: {0}", e);
}
}*/
// This will be called on seperate threads, 1 per client connection and
// represents a connected client - that is, until we return null,
// the connection remains open and operations on behalf of this client
// should occur in this thread etc. The current managed thread id
// can be used to differentiate between instances if scope requires.
private IDictionary<string, object> HandleMessage(IDictionary<string, object> msg)
{
int instance = Thread.CurrentThread.ManagedThreadId;
ILog logger = LogManager.GetLogger(string.Format("HandleMessage[{0}]", instance));
MessageType type = (MessageType) Enum.ToObject(typeof (MessageType), msg["MessageType"]);
// Very noisy, not usually worth having on, configurable via "TraceMsgTraffic" boolean
bool traceMsgTraffic = pGina.Core.Settings.Get.GetSetting("TraceMsgTraffic", false);
if (traceMsgTraffic)
{
logger.DebugFormat("{0} message received", type);
}
switch (type)
{
case MessageType.Disconnect:
// We ack, and mark this as LastMessage, which tells the pipe framework
// not to expect further messages
IDictionary<string, object> disconnectAck = new EmptyMessage(MessageType.Ack).ToDict(); // Ack
disconnectAck["LastMessage"] = true;
return disconnectAck;
case MessageType.Hello:
return new EmptyMessage(MessageType.Hello).ToDict(); // Ack with our own hello
case MessageType.Log:
HandleLogMessage(new LogMessage(msg));
return new EmptyMessage(MessageType.Ack).ToDict(); // Ack
case MessageType.LoginRequest:
return HandleLoginRequest(new LoginRequestMessage(msg)).ToDict();
case MessageType.DynLabelRequest:
return HandleDynamicLabelRequest(new DynamicLabelRequestMessage(msg)).ToDict();
case MessageType.LoginInfoChange:
return HandleLoginInfoChange(new LoginInfoChangeMessage(msg)).ToDict();
case MessageType.UserInfoRequest:
return HandleUserInfoRequest(new UserInformationRequestMessage(msg)).ToDict();
case MessageType.ChangePasswordRequest:
return HandleChangePasswordRequest(new ChangePasswordRequestMessage(msg)).ToDict();
default:
return null; // Unknowns get disconnected
}
}
private void HandleLogMessage(LogMessage msg)
{
ILog logger = LogManager.GetLogger(string.Format("RemoteLog[{0}]", msg.LoggerName));
switch (msg.Level.ToLower())
{
case "info":
logger.InfoFormat("{0}", msg.LoggedMessage);
break;
case "debug":
logger.DebugFormat("{0}", msg.LoggedMessage);
break;
case "error":
logger.ErrorFormat("{0}", msg.LoggedMessage);
break;
case "warn":
logger.WarnFormat("{0}", msg.LoggedMessage);
break;
default:
logger.DebugFormat("{0}", msg.LoggedMessage);
break;
}
}
private LoginResponseMessage HandleLoginRequest(LoginRequestMessage msg)
{
try
{
PluginDriver sessionDriver = new PluginDriver();
bool LastUsernameEnable = Settings.Get.LastUsernameEnable;
string oriUsername = msg.Username; //to distinguish email from domain
msg = SplitDomainfromUsername(msg);
sessionDriver.UserInformation.Username = msg.Username;
sessionDriver.UserInformation.Password = (String.IsNullOrEmpty(msg.Password)) ? "" : msg.Password;
sessionDriver.UserInformation.Domain = msg.Domain;
sessionDriver.UserInformation.SessionID = msg.Session;
if (msg.Reason == LoginRequestMessage.LoginReason.CredUI)
{
sessionDriver.SessionProperties.CREDUI = true;
}
if (String.IsNullOrEmpty(sessionDriver.UserInformation.Username))
{
return new LoginResponseMessage() { Result = false, Message = String.Format("No Username supplied\n\n'{0}' was entered and parsed to '{1}'", msg.Username, sessionDriver.UserInformation.Username) };
}
// check if a plugin still does some logoff work for this user
Boolean thisUserLogoff = false;
foreach (IPluginLogoffRequestAddTime plugin in PluginLoader.GetOrderedPluginsOfType<IPluginLogoffRequestAddTime>())
{
if (plugin.LoginUserRequest(sessionDriver.UserInformation.Username))
thisUserLogoff = true;
}
if (thisUserLogoff)
{
return new LoginResponseMessage() { Result = false, Message = String.Format("Still logoff work to do for user {0}\nWait a view seconds and retry", sessionDriver.UserInformation.Username) };
}
// do the domain logon
string domainmember = Abstractions.WindowsApi.pInvokes.GetMachineDomainMembershipEX();
m_logger.InfoFormat("domain check:[{0}] [{1}] [{2}]", Regex.IsMatch(msg.Username, "\\|@"), !String.IsNullOrEmpty(domainmember), !sessionDriver.UserInformation.Domain.Equals(Environment.MachineName, StringComparison.CurrentCultureIgnoreCase));
if ((Regex.IsMatch(msg.Username, "\\|@") || !String.IsNullOrEmpty(domainmember)) && !sessionDriver.UserInformation.Domain.Equals(Environment.MachineName, StringComparison.CurrentCultureIgnoreCase))
{
m_logger.DebugFormat("domain logon: Username:{0} domainmember:{1} domain:{2}", msg.Username, domainmember, sessionDriver.UserInformation.Domain);
// if domain was provided by username and it got messed up ...
if (String.IsNullOrEmpty(sessionDriver.UserInformation.Domain) && Regex.IsMatch(msg.Username, "\\|@"))
{
return new LoginResponseMessage() { Result = false, Message = String.Format("No Domainname supplied\n\n'{0}' was entered and parsed to '{1}'", msg.Username, sessionDriver.UserInformation.Domain) };
}
if (Abstractions.WindowsApi.pInvokes.DomainMember(sessionDriver.UserInformation.Domain))
{
m_logger.InfoFormat("DomainMember");
// pc is member of this domain provided by the username field
if (Abstractions.WindowsApi.pInvokes.ValidateUser(sessionDriver.UserInformation.Username, sessionDriver.UserInformation.Domain, sessionDriver.UserInformation.Password))
{
if (LastUsernameEnable && msg.Reason == LoginRequestMessage.LoginReason.Login)
{
Settings.s_settings.SetSetting("LastUsername", String.Format("{0}\\{1}", sessionDriver.UserInformation.Domain, sessionDriver.UserInformation.Username));
}
m_logger.InfoFormat("Sucess");
return new LoginResponseMessage()
{
Result = true,
Message = "",
Username = sessionDriver.UserInformation.Username,
Domain = sessionDriver.UserInformation.Domain,
Password = <PASSWORD>
};
}
else
{
string message = String.Format("The provided account:{0} name does not exist on:{1} or the password is wrong", sessionDriver.UserInformation.Username, sessionDriver.UserInformation.Domain);
m_logger.InfoFormat(message);
return new LoginResponseMessage()
{
Result = false,
Message = message,
Username = sessionDriver.UserInformation.Username,
Domain = sessionDriver.UserInformation.Domain,
Password = <PASSWORD>Driver.UserInformation.<PASSWORD>
};
}
}
else if (!String.IsNullOrEmpty(domainmember))
{
m_logger.InfoFormat("GetMachineDomainMembership");
// pc is member of a domain
sessionDriver.UserInformation.Domain = domainmember;
if (Abstractions.WindowsApi.pInvokes.ValidateUser(sessionDriver.UserInformation.Username, sessionDriver.UserInformation.Domain, sessionDriver.UserInformation.Password))
{
if (LastUsernameEnable && msg.Reason == LoginRequestMessage.LoginReason.Login)
{
Settings.s_settings.SetSetting("LastUsername", String.Format("{0}\\{1}", sessionDriver.UserInformation.Domain, sessionDriver.UserInformation.Username));
}
m_logger.InfoFormat("Sucess");
return new LoginResponseMessage()
{
Result = true,
Message = "",
Username = sessionDriver.UserInformation.Username,
Domain = sessionDriver.UserInformation.Domain,
Password = <PASSWORD>
};
}
else
{
m_logger.InfoFormat("Failed, query Remote({0}) SAM", domainmember);
sessionDriver.UserInformation.Domain = Environment.MachineName;
}
}
}
// for those who are logging in by using a mail address
if (oriUsername.Contains("@") && !oriUsername.ToLower().Contains("@" + Environment.MachineName.ToLower()))
{
sessionDriver.UserInformation.Username = oriUsername;
sessionDriver.UserInformation.Domain = Environment.MachineName;
m_logger.DebugFormat("Reintegrate username from username:{0} domain:{1} to {2} and domain:{3}", msg.Username, msg.Domain, oriUsername, Environment.MachineName);
}
// mail mod end
BooleanResult result = new BooleanResult() { Success = true, Message = "" };
if (new[] { LoginRequestMessage.LoginReason.Login, LoginRequestMessage.LoginReason.CredUI }.Contains(msg.Reason))
{
m_logger.DebugFormat("Processing LoginRequest for: {0} in session: {1} reason: {2}", sessionDriver.UserInformation.Username, msg.Session, msg.Reason);
Boolean isLoggedIN = false;
Boolean isUACLoggedIN = false;
// is this user a local user and was not created by pGina
Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4 userinfo4 = new Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4();
if (Abstractions.WindowsApi.pInvokes.UserGet(sessionDriver.UserInformation.Username, ref userinfo4))
{
if (!userinfo4.comment.Contains("pGina created"))
{
result.Success = Abstractions.WindowsApi.pInvokes.ValidateUser(sessionDriver.UserInformation.Username, sessionDriver.UserInformation.Domain, sessionDriver.UserInformation.Password);
if (result.Success)
{
if (LastUsernameEnable && msg.Reason == LoginRequestMessage.LoginReason.Login)
{
Settings.s_settings.SetSetting("LastUsername", String.Format("{0}", sessionDriver.UserInformation.Username));
}
}
return new LoginResponseMessage()
{
Result = result.Success,
Message = (result.Success) ? "Local non pGina user" : "Unknown username or bad password",
Username = sessionDriver.UserInformation.Username,
Domain = sessionDriver.UserInformation.Domain,
Password = <PASSWORD>
};
}
}
Dictionary<int, List<string>> contextALL = Abstractions.WindowsApi.pInvokes.GetSessionContext();
List<string> Users = Abstractions.WindowsApi.pInvokes.GetSessionContextParser(-1, contextALL);
List<string> iUsers = Abstractions.WindowsApi.pInvokes.GetInteractiveUserList();
foreach (string user in Users)
{
m_logger.DebugFormat("Program running as user:{0}", user);
if (user.Equals(sessionDriver.UserInformation.Username, StringComparison.CurrentCultureIgnoreCase))
{
//the user is still logged in
isLoggedIN = true;
if (iUsers.Any(s => s.EndsWith("\\" + sessionDriver.UserInformation.Username, StringComparison.CurrentCultureIgnoreCase)))
{
int Locked_sessionID = Convert.ToInt32(iUsers.Find(s => s.EndsWith("\\" + sessionDriver.UserInformation.Username, StringComparison.CurrentCultureIgnoreCase)).Split('\\').First());
m_logger.DebugFormat("User:{0} is Locked in Session:{1}", sessionDriver.UserInformation.Username, Locked_sessionID);
// verify that this unlock is present somewhere in m_sessionPropertyCache
// if not, this login is not backed by m_sessionPropertyCache
if (m_sessionPropertyCache.GetAll().Any(i => i == Locked_sessionID))
{
UserInformation uInfo = m_sessionPropertyCache.Get(Locked_sessionID).First().GetTrackedSingle<UserInformation>();
if (!uInfo.Username.Equals(sessionDriver.UserInformation.Username, StringComparison.CurrentCultureIgnoreCase))
{
// that should never ever happen
m_logger.ErrorFormat("User {0} is Locked in Session {1} but the username doesn't match the session information pGina contains. '{0}' vs. '{2}'", sessionDriver.UserInformation.Username, Locked_sessionID, uInfo.Username);
return new LoginResponseMessage() { Result = false, Message = String.Format("User {0} is Locked in Session {1} but the username doesn't match the session information pGina contains\n\n'{0}' vs '{2}'", sessionDriver.UserInformation.Username, Locked_sessionID, uInfo.Username) };
}
}
else
{
m_logger.ErrorFormat("User {0} is Locked in Session {1} but was not authenticated by pGina. Unable to find SessionProperty in m_sessionPropertyCache.Get({1})", sessionDriver.UserInformation.Username, Locked_sessionID);
return new LoginResponseMessage() { Result = false, Message = String.Format("User {0} is Locked in Session {1} but was not authenticated by pGina\n\nIt is possible that another Credential Provider was used\nor the pGina service has crashed.\n", sessionDriver.UserInformation.Username, Locked_sessionID) };
}
}
else
{
// verify that this UACed login is present somewhere in m_sessionPropertyCache
// if not, this login is not backed by m_sessionPropertyCache
foreach (int session in m_sessionPropertyCache.GetAll())
{
if (m_sessionPropertyCache.Get(session).Any(s => s.GetTrackedSingle<UserInformation>().Username.Equals(sessionDriver.UserInformation.Username, StringComparison.CurrentCultureIgnoreCase)))
{
m_logger.DebugFormat("User:{0} is pGina UACed in Session:{1}", sessionDriver.UserInformation.Username, session);
isUACLoggedIN = true;
break;
}
}
// is this user a local user and was not created by pGina
/*Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4 userinfo4 = new Abstractions.WindowsApi.pInvokes.structenums.USER_INFO_4();
if (Abstractions.WindowsApi.pInvokes.UserGet(sessionDriver.UserInformation.Username, ref userinfo4))
{
if (!userinfo4.comment.Contains("pGina created"))
{
m_logger.DebugFormat("User:{0} is local non pGina", sessionDriver.UserInformation.Username);
isUACLoggedIN = true;
}
}*/
if (!isUACLoggedIN)
{
List<string> runas_in_session = new List<string>();
foreach (KeyValuePair<int, List<string>> pair in contextALL)
{
if (pair.Value.Any(s => s.Equals(sessionDriver.UserInformation.Username, StringComparison.CurrentCultureIgnoreCase)))
{
runas_in_session.Add(iUsers.DefaultIfEmpty("").FirstOrDefault(s => s.StartsWith(pair.Key.ToString())));
}
}
m_logger.DebugFormat("There is a program running as {0} but it was'nt started with pGina. I can't log you in because this would conflict with the current running process. Session in which a process is running:{1}", sessionDriver.UserInformation.Username, String.Join(",", runas_in_session));
return new LoginResponseMessage() { Result = false, Message = String.Format("There is a program running as {0} but it was'nt started with pGina.\nI can't log you in because this would conflict with the current running process.\n\nSession in which a process is running:\n{1}", sessionDriver.UserInformation.Username, String.Join("\n", runas_in_session)) };
}
}
}
}
if (!isLoggedIN)
{
result = sessionDriver.PerformLoginProcess();
}
else
{
// testing. ValidateCredentials would be correct here
if (!Abstractions.WindowsApi.pInvokes.ValidateUser(sessionDriver.UserInformation.Username, sessionDriver.UserInformation.Domain, sessionDriver.UserInformation.Password))
{
m_logger.ErrorFormat("Query local SAM: Bad password");
return new LoginResponseMessage()
{
Result = false,
Message = "Bad password",
Username = sessionDriver.UserInformation.Username,
Domain = sessionDriver.UserInformation.Domain,
Password = sessionDriver.UserInformation.<PASSWORD>
};
}
}
if (result.Success && (!isLoggedIN || msg.Reason == LoginRequestMessage.LoginReason.CredUI || isUACLoggedIN))
{
lock (m_sessionPropertyCache)
{
List<SessionProperties> ses = new List<SessionProperties>();
if (m_sessionPropertyCache.Exists(msg.Session))
{
ses = m_sessionPropertyCache.Get(msg.Session);
}
bool partof = false;
foreach (SessionProperties sess in ses)
{
UserInformation ui = sess.GetTrackedSingle<UserInformation>();
m_logger.InfoFormat("compare stored-user:{0} this-user:{1}", ui.Username, sessionDriver.UserInformation.Username);
if (sessionDriver.UserInformation.Username.Equals(ui.Username, StringComparison.CurrentCultureIgnoreCase))
{
partof = true;
m_logger.InfoFormat("contain user {0} in sessioninfo:{1} GUID:{2}", ui.Username, msg.Session, sess.Id);
break;
}
}
if (!partof)
{
if (isLoggedIN)
{
UserInformation ui = FindUserInfoInPropertyCache(sessionDriver.UserInformation.Username);
if (ui != null)
{
ui.SessionID = msg.Session;
sessionDriver.SessionProperties.AddTrackedSingle<UserInformation>(ui);
}
}
else
{
// add local profile path
// its not sure that the profile realy ends up there
// a win profile loading error can redirect the path to a temp path too
UserInformation ui = sessionDriver.SessionProperties.GetTrackedSingle<UserInformation>();
if (ui != null)
{
// worst case empty string
ui.LocalProfilePath = Abstractions.Windows.User.GetProfileDir(ui.Username, ui.Password, ui.SID);
sessionDriver.SessionProperties.AddTrackedSingle<UserInformation>(ui);
m_logger.InfoFormat("ses add LocalProfilePath:[{0}]", ui.LocalProfilePath);
}
}
ses.Add(sessionDriver.SessionProperties);
m_logger.InfoFormat("add user {0} to sessioninfo:{1} GUID:{2} CREDUI:{3}", sessionDriver.UserInformation.Username, msg.Session, sessionDriver.SessionProperties.Id, (msg.Reason == LoginRequestMessage.LoginReason.CredUI) ? "true" : "false");
m_logger.InfoFormat("ses username:{0} description:{1} credui:{2} isLoggedIN:{3}", ses.Last().GetTrackedSingle<UserInformation>().Username, ses.Last().GetTrackedSingle<UserInformation>().Description, ses.Last().CREDUI, isLoggedIN);
m_sessionPropertyCache.Add(msg.Session, ses);
}
}
}
}
else
{
// check if username is equal originalusername
// if not return originalusername and password
bool originalUsernameUnlock = Settings.Get.UseOriginalUsernameInUnlockScenario;
if (originalUsernameUnlock && LoginRequestMessage.LoginReason.Unlock == msg.Reason)
{
m_logger.InfoFormat("Unlock with original Username:{0} for Session:{1}", sessionDriver.UserInformation.Username, msg.Session);
lock (m_sessionPropertyCache)
{
List<SessionProperties> ses = new List<SessionProperties>();
if (m_sessionPropertyCache.Exists(msg.Session))
{
ses = m_sessionPropertyCache.Get(msg.Session);
}
// the first entry is always the interactive user
SessionProperties sess = ses.DefaultIfEmpty(new SessionProperties(Guid.Empty, true)).FirstOrDefault();
UserInformation ui = sess.GetTrackedSingle<UserInformation>();
if (ui.Username != ui.OriginalUsername)
{
if (ui.OriginalPassword == sessionDriver.UserInformation.Password)
{
sessionDriver.UserInformation.Username = ui.Username;
sessionDriver.UserInformation.Domain = Environment.MachineName;
sessionDriver.UserInformation.Password = <PASSWORD>;
result.Success = true;
m_logger.InfoFormat("Unlock as:{0} for Session:{1}", sessionDriver.UserInformation.Username, msg.Session);
}
else
{
result.Success = false;
result.Message = "Password incorrect!";
}
}
}
}
else
{
m_logger.DebugFormat("Parse Request for: {0} in session: {1} reason: {2}", sessionDriver.UserInformation.Username, msg.Session, msg.Reason);
}
}
if (LastUsernameEnable && msg.Reason == LoginRequestMessage.LoginReason.Login && result.Success)
{
Settings.s_settings.SetSetting("LastUsername", String.Format("{0}", sessionDriver.UserInformation.Username));
}
return new LoginResponseMessage()
{
Result = result.Success,
Message = result.Message,
Username = sessionDriver.UserInformation.Username,
Domain = sessionDriver.UserInformation.Domain,
Password = <PASSWORD>
};
}
catch (Exception e)
{
m_logger.ErrorFormat("Internal error, unexpected exception while handling login request: {0}", e);
return new LoginResponseMessage() { Result = false, Message = "Internal error" };
}
}
private DynamicLabelResponseMessage HandleDynamicLabelRequest(DynamicLabelRequestMessage msg)
{
switch (msg.Name)
{
case "MOTD":
string text = Settings.Get.Motd;
string motd = FormatMotd(text);
return new DynamicLabelResponseMessage() { Name = msg.Name, Text = motd };
// Others can be added here.
}
return new DynamicLabelResponseMessage();
}
private UserInformationResponseMessage HandleUserInfoRequest(UserInformationRequestMessage msg)
{
lock (m_sessionPropertyCache)
{
if (m_sessionPropertyCache.Exists(msg.SessionID))
{
SessionProperties props = m_sessionPropertyCache.Get(msg.SessionID).First();
UserInformation userInfo = props.GetTrackedSingle<UserInformation>();
return new UserInformationResponseMessage
{
OriginalUsername = userInfo.OriginalUsername,
Username = userInfo.Username,
Domain = userInfo.Domain
};
}
}
return new UserInformationResponseMessage();
}
private EmptyMessage HandleLoginInfoChange(LoginInfoChangeMessage msg)
{
m_logger.DebugFormat("Changing login info at request of client, User {0} moving from {1} to {2}", msg.Username, msg.FromSession, msg.ToSession);
lock (m_sessionPropertyCache)
{
if (m_sessionPropertyCache.Exists(msg.FromSession))
{
if (msg.ToSession != -1)
{
m_sessionPropertyCache.Add(msg.ToSession, m_sessionPropertyCache.Get(msg.FromSession));
m_sessionPropertyCache.Remove(msg.FromSession);
}
else
{
List<SessionProperties> props = m_sessionPropertyCache.Get(msg.FromSession);
for (int x = props.Count-1; x >= 0 ; x--)
{
UserInformation uInfo = props[x].GetTrackedSingle<UserInformation>();
if (uInfo.Username.Equals(msg.Username, StringComparison.CurrentCultureIgnoreCase))
{
if (x == 0)
{
m_sessionPropertyCache.Remove(msg.FromSession);
break;
}
else
{
props.RemoveAt(x);
m_sessionPropertyCache.Add(msg.FromSession, props);
}
}
}
}
}
}
return new EmptyMessage(MessageType.Ack);
}
private string FormatMotd(string text)
{
string motd = text;
// Version
string pattern = @"\%v";
if (Regex.IsMatch(motd, pattern))
{
string vers = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
motd = Regex.Replace(motd, pattern, vers);
}
// IP Address
pattern = @"\%i";
if (Regex.IsMatch(motd, pattern))
{
// Get IP address of this computer
IPAddress[] ipList = Dns.GetHostAddresses("");
string ip = "";
// Grab the first IPv4 address in the list
foreach (IPAddress addr in ipList)
{
if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ip = addr.ToString();
break;
}
}
motd = Regex.Replace(motd, pattern, ip);
}
// machine name
pattern = @"\%m";
if (Regex.IsMatch(motd, pattern))
{
motd = Regex.Replace(motd, pattern, Environment.MachineName);
}
// Date
pattern = @"\%d";
if (Regex.IsMatch(motd, pattern))
{
string today = DateTime.Today.ToString("MMMM dd, yyyy");
motd = Regex.Replace(motd, pattern, today);
}
// DNS name
pattern = @"\%n";
if (Regex.IsMatch(motd, pattern))
{
string dns = Dns.GetHostName();
motd = Regex.Replace(motd, pattern, dns);
}
return motd;
}
/// <summary>
/// m_sessionPropertyCache must be locked
/// </summary>
/// <param name="username"></param>
/// <returns>Dict<sessionID,pos in the list></returns>
private Dictionary<int, int> FindUserInPropertyCache(string username)
{
Dictionary<int, int> ret = new Dictionary<int, int>();
List<int> SessionsList = m_sessionPropertyCache.GetAll(); //all pgina watched sessions
//Dictionary<int, List<string>> othersessioncontext = new Dictionary<int, List<string>>(); //all exept my sessions, a list of usernames in which a process is running
foreach (int Sessions in SessionsList)
{
List<SessionProperties> ses = m_sessionPropertyCache.Get(Sessions);
for (int x = 0; x < ses.Count; x++)
{
UserInformation uInfo = ses[x].GetTrackedSingle<UserInformation>();
if (uInfo.Username.Equals(username, StringComparison.CurrentCultureIgnoreCase))
{
ret.Add(Sessions, x);
}
}
}
return ret;
}
/// <summary>
/// m_sessionPropertyCache must be locked
/// </summary>
/// <param name="username"></param>
/// <returns>null == not found</returns>
private UserInformation FindUserInfoInPropertyCache(string username)
{
UserInformation uInfo = null;
Dictionary<int, int> foundIN = FindUserInPropertyCache(username);
if (foundIN.Count == 0)
{
return null;
}
foreach (KeyValuePair<int, int> pair in foundIN)
{
List<SessionProperties> sesProps = m_sessionPropertyCache.Get(pair.Key);
if (pair.Value == 0) //0 is an interactive session
{
return sesProps[pair.Value].GetTrackedSingle<UserInformation>();
}
uInfo = sesProps[pair.Value].GetTrackedSingle<UserInformation>();
}
return uInfo;
}
private void SessionChangeThread(int sessionID, SessionChangeReason evnt)
{
m_logger.InfoFormat("SessionChange: {0} -> {1}", sessionID, evnt);
try
{
lock (m_sessionPropertyCache)
{
if (evnt == SessionChangeReason.SessionLogon && m_sessionPropertyCache.Exists(sessionID))
{
// if a user tried to logon but didnt pass the logonscreen (windows 8 and 10 lock screen bug) trash the info stored about that session
UserInformation uInfo = m_sessionPropertyCache.Get(sessionID).First().GetTrackedSingle<UserInformation>();
string sessionID_is = String.Format("{0}@{1}", Abstractions.WindowsApi.pInvokes.GetUserName(sessionID), Abstractions.WindowsApi.pInvokes.GetUserDomain(sessionID));
string sessionID_should = String.Format("{0}@{1}", uInfo.Username, uInfo.Domain);
if (!sessionID_is.Equals(sessionID_should, StringComparison.CurrentCultureIgnoreCase))
{
m_logger.InfoFormat("SessionLogon missmatch {0} != {1} removing SessionProperties", sessionID_is, sessionID_should);
m_sessionPropertyCache.Remove(sessionID);
return;
}
}
if (evnt == SessionChangeReason.SessionLogoff)
{
sessionlogoff.Add(sessionID);
m_logger.InfoFormat("Logoff in progress {0}", sessionID);
CREDUIhelper(sessionID);
}
foreach (IPluginEventNotifications plugin in PluginLoader.GetOrderedPluginsOfType<IPluginEventNotifications>())
{
if (m_sessionPropertyCache.Exists(sessionID))
{
foreach (SessionProperties props in m_sessionPropertyCache.Get(sessionID))
{
plugin.SessionChange(sessionID, evnt, props);
}
}
else
{
plugin.SessionChange(sessionID, evnt, null);
}
}
if (evnt == SessionChangeReason.SessionLogoff)
{
sessionlogoff.Remove(sessionID);
m_logger.InfoFormat("Logoff completed {0}", sessionID);
}
// If this is a logout, remove from our map
if (evnt == SessionChangeReason.SessionLogoff && m_sessionPropertyCache.Exists(sessionID))
{
//m_logger.InfoFormat("delete sessionInfos:{0} from sessionID:{1}", String.Join(" ", m_sessionPropertyCache.Get(sessionID).Select(l => l.Id).ToList()), sessionID);
m_sessionPropertyCache.Remove(sessionID);
}
}
}
catch (Exception e)
{
m_logger.ErrorFormat("Exception while handling SessionChange event: {0}", e);
}
}
/// <summary>
/// m_sessionPropertyCache must be locked
/// </summary>
/// <param name="session"></param>
private void CREDUIhelper(int session)
{
m_logger.InfoFormat("CREDUIhelper:({0})", session);
List<SessionProperties> mysessionList = m_sessionPropertyCache.Get(session); //list of all users in my session
if (mysessionList.Count == 0)
{
m_logger.InfoFormat("User:? in session:{0} is unknown to pGina", session);
return;
}
UserInformation userInfo = m_sessionPropertyCache.Get(session).First().GetTrackedSingle<UserInformation>(); //this user is logging of right now (my user)
List<int> SessionsList = m_sessionPropertyCache.GetAll(); //all pgina watched sessions
Dictionary<int,List<string>> othersessioncontext = new Dictionary<int,List<string>>(); //all exept my sessions, a list of usernames in which a process is running
foreach (int Sessions in SessionsList)
{
if (session != Sessions) //if not my session
{
//get all usersNames from processes that dont run in my own session (context in which those processes are running)
List<string> sesscontext = Abstractions.WindowsApi.pInvokes.GetSessionContext(Sessions);
othersessioncontext.Add(Sessions, sesscontext);
}
}
List<string> InteractiveUserList = Abstractions.WindowsApi.pInvokes.GetInteractiveUserList(); //get interactive users
foreach (SessionProperties s in m_sessionPropertyCache.Get(session))
{
m_logger.InfoFormat("info: username:{0} credui:{1} description:{2} session:{3}", s.GetTrackedSingle<UserInformation>().Username, s.CREDUI, s.GetTrackedSingle<UserInformation>().Description, session);
}
//catch runas.exe credui processes
foreach (KeyValuePair<int, List<string>> context in othersessioncontext)
{
// all usersNames from processes in session bla.Key format: sessionID\username
m_logger.InfoFormat("othersessioncontext: {0}", String.Join(" ", context.Value.Select(s => String.Format("{0}\\{1}", context.Key, s))));
List<SessionProperties> othersessionList = m_sessionPropertyCache.Get(context.Key); //sessionlist of SessionProperties
foreach (string user in context.Value)
{
if (!othersessionList.Any(s => s.GetTrackedSingle<UserInformation>().Username.Equals(user, StringComparison.CurrentCultureIgnoreCase)))
{
//user is not part of othersessionList
bool cancopy = false;
foreach (int Session in SessionsList)
{
if (context.Key != Session && !cancopy) //if not bla.key session
{
foreach (SessionProperties sesprop in m_sessionPropertyCache.Get(Session))
{
UserInformation sespropUInfo = sesprop.GetTrackedSingle<UserInformation>();
if (sespropUInfo.Username.Equals(user, StringComparison.CurrentCultureIgnoreCase))
{
// SessionProperties found
SessionProperties osesprop = new SessionProperties(Guid.NewGuid(), true);
PluginActivityInformation pluginInfo = new PluginActivityInformation();
osesprop.AddTrackedSingle<UserInformation>(sespropUInfo);
osesprop.AddTrackedSingle<PluginActivityInformation>(pluginInfo);
othersessionList.Add(osesprop);
m_logger.InfoFormat("add user:{0} into SessionProperties of session:{1} with GUID:{2} and set CREDUI to:{3}", sespropUInfo.Username, context.Key, osesprop.Id, osesprop.CREDUI);
cancopy = true;
m_sessionPropertyCache.Add(context.Key, othersessionList);// refresh the cache
break;
}
}
}
}
if (!cancopy)
{
m_logger.InfoFormat("unamble to track program running under user:{0} in session:{1}", user, context.Key);
}
}
}
}
/*
for (int y = 0; y < mysessionList.Count; y++)
{
UserInformation allmyuInfo = mysessionList[y].GetTrackedSingle<UserInformation>();
foreach (int Sessions in SessionsList)
{
if (session != Sessions) //if not my session
{
// there is a program running as user 'allmyuInfo.Username' in session 'Sessions'
// && this user 'allmyuInfo.Username' is not an interactive user
m_logger.InfoFormat("{0} '{1}' '{2}'", allmyuInfo.Username, String.Join(" ", othersessioncontext[Sessions]), String.Join(" ", InteractiveUserList));
if (othersessioncontext[Sessions].Any(s => s.Equals(allmyuInfo.Username, StringComparison.CurrentCultureIgnoreCase)) && !InteractiveUserList.Any(s => s.ToLower().Contains(Sessions + "\\" + allmyuInfo.Username.ToLower())))
{
bool hit = false;
List<SessionProperties> othersessionList = m_sessionPropertyCache.Get(Sessions); //sessionlist of Sessions (not mine)
for (int x = 1; x < othersessionList.Count; x++)
{
UserInformation ouserInfo = othersessionList[x].GetTrackedSingle<UserInformation>();
m_logger.InfoFormat("compare:'{0}' '{1}'", ouserInfo.Username, allmyuInfo.Username);
if (ouserInfo.Username.Equals(allmyuInfo.Username, StringComparison.CurrentCultureIgnoreCase))
{
// SessionProperties List of 'Sessions' contains the user 'allmyuInfo.Username'
hit = true;
}
}
if (!hit)
{
//this program was run by using runas or simmilar
//push it into the SessionProperties list of 'Sessions'
SessionProperties osesprop = new SessionProperties(Guid.NewGuid(), true);
PluginActivityInformation pluginInfo = new PluginActivityInformation();
osesprop.AddTrackedSingle<UserInformation>(allmyuInfo);
osesprop.AddTrackedSingle<PluginActivityInformation>(pluginInfo);
othersessionList.Add(osesprop);
m_logger.InfoFormat("ive found a program in session:{0} that runs in the context of {1}", Sessions, allmyuInfo.Username);
m_logger.InfoFormat("add user:{0} into SessionProperties of session:{1} with GUID:{2} and set CREDUI to:{3}", allmyuInfo.Username, Sessions, osesprop.Id, osesprop.CREDUI);
}
m_sessionPropertyCache.Add(Sessions, othersessionList);// refresh the cache
}
}
}
}
*/
foreach (SessionProperties s in m_sessionPropertyCache.Get(session))
{
m_logger.InfoFormat("info: username:{0} credui:{1} description:{2} session:{3}", s.GetTrackedSingle<UserInformation>().Username, s.CREDUI, s.GetTrackedSingle<UserInformation>().Description, session);
}
//set SessionProperties.CREDUI
for (int y = 0; y < mysessionList.Count; y++)
{
UserInformation allmyuInfo = mysessionList[y].GetTrackedSingle<UserInformation>();
foreach (int Sessions in SessionsList)
{
if (session != Sessions) //if not my session
{
List<SessionProperties> othersessionList = m_sessionPropertyCache.Get(Sessions); //sessionlist of Sessions (not mine)
for (int x = 0; x < othersessionList.Count; x++) //all entries
{
UserInformation ouserInfo = othersessionList[x].GetTrackedSingle<UserInformation>();
m_logger.InfoFormat("compare '{0}' '{1}'", ouserInfo.Username, allmyuInfo.Username);
if (ouserInfo.Username.Equals(allmyuInfo.Username, StringComparison.CurrentCultureIgnoreCase))
{
// there is an entry in the SessionProperties List of session 'Sessions'
// ill mark CREDUI of user 'allmyuInfo.Username' in my session 'session' as true
// a plugin should not remove or upload a credui user (its up to the plugin dev)
if (mysessionList[y].CREDUI != true)
{
mysessionList[y].CREDUI = true;
m_logger.InfoFormat("an entry in session:{0} was found from user {1}", Sessions, allmyuInfo.Username);
m_logger.InfoFormat("set CREDUI in SessionProperties of user:{0} in session:{1} to {2}", allmyuInfo.Username, session, mysessionList[y].CREDUI);
}
// ill mark CREDUI of user 'ouserInfo.Username' in session 'Sessions' as false
othersessionList[x].CREDUI = false;
m_logger.InfoFormat("set CREDUI in SessionProperties of user:{0} in session:{1} to {2}", ouserInfo.Username, Sessions, othersessionList[x].CREDUI);
}
}
/*
if (othersessioncontext[Sessions].Any(s => s.Equals(allmyuInfo.Username, StringComparison.CurrentCultureIgnoreCase)))
{
// there is a process running in a different session under the context this user
// ill mark the sessioninfo struct of my user as credui true
// a plugin should not remove or upload a credui user (its up to the plugin dev)
//mysessionList.First().CREDUI = true; //the first entry in the list is always an interactive login
mysessionList[y].CREDUI = true;
m_logger.InfoFormat("a program in session:{0} is running in the context of user {1}", Sessions, allmyuInfo.Username);
m_logger.InfoFormat("set CREDUI in SessionProperties of user:{0} in session:{1} to {2}", allmyuInfo.Username, session, mysessionList[y].CREDUI);
List<SessionProperties> othersessionList = m_sessionPropertyCache.Get(Sessions); //sessionlist of Sessions (not mine)
bool hit = false;
for (int x = 0; x < othersessionList.Count; x++)
{
//one user of this other sessions where a process runs under my user
UserInformation ouserInfo = othersessionList[x].GetTrackedSingle<UserInformation>();
m_logger.InfoFormat("compare:'{0}' '{1}'", ouserInfo.Username, allmyuInfo.Username);
if (ouserInfo.Username.Equals(allmyuInfo.Username, StringComparison.CurrentCultureIgnoreCase))
{
// this is the entry
hit = true;
if (x > 0)
{
// user is non interactive
if (userInfo.Username.Equals(ouserInfo.Username, StringComparison.CurrentCultureIgnoreCase))
{
othersessionList[x].CREDUI = false;
}
else
{
othersessionList[x].CREDUI = true;
}
m_logger.InfoFormat("set CREDUI in SessionProperties of user:{0} in session:{1} to {2}", ouserInfo.Username, Sessions, othersessionList[x].CREDUI);
}
}
}
if (!hit)
{
//this program was run by using runas or simmilar
//push it into the SessionProperties list of this session
SessionProperties osesprop = mysessionList[y];
osesprop.CREDUI = true;
osesprop.Id = new Guid(Guid.NewGuid().ToString());
othersessionList.Add(osesprop);
m_logger.InfoFormat("ive found a program in session:{0} that runs in the context of {1}", Sessions, allmyuInfo.Username);
m_logger.InfoFormat("add user:{0} into SessionProperties of session:{1} an set CREDUI to:{2}", allmyuInfo.Username, Sessions, osesprop.CREDUI);
}
m_sessionPropertyCache.Add(Sessions, othersessionList);// refresh the cache
}*/
}
}
}
m_sessionPropertyCache.Add(session, mysessionList);// refresh the cache
foreach (SessionProperties s in m_sessionPropertyCache.Get(session))
{
m_logger.InfoFormat("info: username:{0} credui:{1} description:{2} session:{3}", s.GetTrackedSingle<UserInformation>().Username, s.CREDUI, s.GetTrackedSingle<UserInformation>().Description, session);
}
/*
//shutdown/reboot case
if (mysessionList.First().CREDUI == false)
{
//this interactive user is logging out
foreach (int Sessions in SessionsList)
{
if (session != Sessions) //if not my session
{
List<SessionProperties> othersessionList = m_sessionPropertyCache.Get(Sessions); //sessionlist of Sessions (not mine)
for (int y = othersessionList.Count - 1; y > 0; y--) //only other credui users
{
if (userInfo.Username.Equals(othersessionList[y].GetTrackedSingle<UserInformation>().Username, StringComparison.CurrentCultureIgnoreCase))
{
//no process of my users should run anymore anywhere
//if so mysessionList.First().CREDUI would be true
m_logger.InfoFormat("no process is running in session:{0} under the context of user:{1} removing:{1} in session:{0}", Sessions, userInfo.Username);
othersessionList.RemoveAt(y);
}
}
m_sessionPropertyCache.Add(Sessions, othersessionList);// refresh the cache
}
}
}
*/
for (int x = mysessionList.Count - 1; x > 0; x--)
{
UserInformation myuserInfo = mysessionList[x].GetTrackedSingle<UserInformation>();
if (InteractiveUserList.Any(s => s.ToLower().Contains(myuserInfo.Username.ToLower())))
{
// a program in my session runs in a different context of an also interactive logged in user
// ill remove this SessionProperty from my SessionProperties List
mysessionList.RemoveAt(x);
m_logger.InfoFormat("user {0} is still interactively logged in", myuserInfo.Username);
m_logger.InfoFormat("removing SessionProperties entry of user:{0} from session:{1}", myuserInfo.Username, session);
}
}
/*
List<string> myCREDUIusernameList = new List<string>(); //my credui usersnames
for (int x = 1; x < mysessionList.Count; x++)
{
UserInformation myCREDUIusername = mysessionList[x].GetTrackedSingle<UserInformation>();
myCREDUIusernameList.Add(myCREDUIusername.Username);
}*/
for (int x = mysessionList.Count - 1; x > 0; x--) //only credui users
{
bool hit = false;
UserInformation myCREDUIusername = mysessionList[x].GetTrackedSingle<UserInformation>();
foreach (int Sessions in SessionsList)
{
if (session != Sessions) //if not my session
{
List<SessionProperties> othersessionList = m_sessionPropertyCache.Get(Sessions); //sessionlist of Sessions (not mine)
for (int y = othersessionList.Count - 1; y >= 0; y--) //all users
{
UserInformation oCREDUIusername = othersessionList[y].GetTrackedSingle<UserInformation>();
//m_logger.InfoFormat("'{0}' '{1}'", oCREDUIusername.Username, String.Join(" ", myCREDUIusernameList));
//if (myCREDUIusernameList.Any(s => s.Equals(oCREDUIusername.Username, StringComparison.CurrentCultureIgnoreCase)))
m_logger.InfoFormat("'{0}' '{1}'", myCREDUIusername.Username, oCREDUIusername.Username);
if (myCREDUIusername.Username.Equals(oCREDUIusername.Username, StringComparison.CurrentCultureIgnoreCase))
{
hit = true;
m_logger.InfoFormat("found SessionProperties entry in session:{0} that equals username {1} in my session:{2}", Sessions, oCREDUIusername.Username, session);
m_logger.InfoFormat("removing the SessionProperties entry from session:{0} of user:{1}", session, oCREDUIusername.Username);
mysessionList.RemoveAt(x);
break;
/*
//is the credui programm still running
m_logger.InfoFormat("'{0}' '{1}'", String.Join(" ", othersessioncontext[Sessions].ToArray()), oCREDUIusername.Username);
if (othersessioncontext[Sessions].Any(s => s.Equals(oCREDUIusername.Username, StringComparison.CurrentCultureIgnoreCase)))
{
//remove from my list
m_logger.InfoFormat("the program is still running, removing the SessionProperties entry from session:{0} of user:{1}", session, oCREDUIusername.Username);
mysessionList.RemoveAt(x);
}
else
{
//remove from other list, its not running anymore
m_logger.InfoFormat("the program has been closed, removing the SessionProperties entry from session:{0} of user:{1}", Sessions, oCREDUIusername.Username);
othersessionList.RemoveAt(y);
}*/
}
}
m_sessionPropertyCache.Add(Sessions, othersessionList);
if (hit)
{
break;
}
}
}
if (!hit)
{
//this credui user runs only in my session
m_logger.InfoFormat("the last program in context of {0} is running in session:{1} set CREDUI to false", mysessionList[x].GetTrackedSingle<UserInformation>().Username, session);
mysessionList[x].CREDUI = false;
}
}
// refresh the cache
m_sessionPropertyCache.Add(session, mysessionList);
}
private ChangePasswordResponseMessage HandleChangePasswordRequest(ChangePasswordRequestMessage msg)
{
try
{
m_logger.DebugFormat("Processing ChangePasswordRequest for: {0} domain: {1} session: {2}", msg.Username, msg.Domain, msg.Session);
msg = SplitDomainfromUsername(msg);
SessionProperties properties = m_sessionPropertyCache.Get(msg.Session).DefaultIfEmpty(new SessionProperties(Guid.Empty)).FirstOrDefault();
if (properties.Id == Guid.Empty)
{
m_logger.DebugFormat("no SessionProperties cached for user:{0}", msg.Username);
ChangePasswordResponseMessage message = new ChangePasswordResponseMessage();
string domainmember = Abstractions.WindowsApi.pInvokes.GetMachineDomainMembershipEX();
if (msg.Domain.Equals(Environment.MachineName, StringComparison.CurrentCultureIgnoreCase) || Abstractions.WindowsApi.pInvokes.DomainMember(msg.Domain))
{
m_logger.InfoFormat("DomainMember");
// pc is member of this domain provided by the username field
message.Message = Abstractions.WindowsApi.pInvokes.UserChangePassword(msg.Domain, msg.Username, msg.OldPassword, msg.NewPassword);
message.Result = (String.IsNullOrEmpty(message.Message)) ? true : false;
message.Domain = msg.Domain;
// abort
return message;
}
else if (!String.IsNullOrEmpty(domainmember))
{
m_logger.InfoFormat("GetMachineDomainMembership");
// pc is member of a domain
message.Message = Abstractions.WindowsApi.pInvokes.UserChangePassword(domainmember, msg.Username, msg.OldPassword, msg.NewPassword);
message.Domain = domainmember;
if (String.IsNullOrEmpty(message.Message))
{
message.Result = true;
return message;
}
else
{
message.Message = String.Format("Remote({0}) Error:{1}\n\n", domainmember, message.Message);
}
}
// local
string mess = Abstractions.WindowsApi.pInvokes.UserChangePassword(Environment.MachineName, msg.Username, msg.OldPassword, msg.NewPassword);
message.Result = (String.IsNullOrEmpty(mess)) ? true : false;
message.Domain = Environment.MachineName;
if (!message.Result)
{
message.Message += "Local Error:" + mess;
}
else
{
message.Message = mess;
}
return message;
}
UserInformation userinfo = properties.GetTrackedSingle<UserInformation>();
userinfo.oldPassword = <PASSWORD>; // <PASSWORD>;
userinfo.Password = <PASSWORD>;
properties.AddTrackedSingle<UserInformation>(userinfo);
ChangePasswordPluginActivityInfo pluginInfo = new ChangePasswordPluginActivityInfo();
pluginInfo.LoadedPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginChangePassword>();
BooleanResult Result = new BooleanResult();
// Once a failure is encountered a failure is returned
foreach ( IPluginChangePassword plug in PluginLoader.GetOrderedPluginsOfType<IPluginChangePassword>() )
{
// Execute the plugin
m_logger.DebugFormat("ChangePassword: executing {0}", plug.Uuid);
Result = plug.ChangePassword(properties, pluginInfo);
m_logger.DebugFormat("ChangePassword: result from {0} is {1} message: {2}", plug.Uuid, Result.Success, Result.Message);
if (!Result.Success)
{
userinfo.Password = <PASSWORD>;
properties.AddTrackedSingle<UserInformation>(userinfo);
break;
}
}
if (!Result.Success)
{
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), userinfo.Username, userinfo.Password, String.Format("pGina: Password change error for {0} from {1}", msg.Username, Environment.MachineName), Result.Message);
}
return new ChangePasswordResponseMessage()
{
Result = Result.Success,
Message = Result.Message,
Username = msg.Username,
Domain = msg.Domain
};
}
catch (Exception e)
{
m_logger.ErrorFormat("Internal error, unexpected exception while handling change password request: {0}", e);
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), "", "", String.Format("pGina: Password change error for {0} from {1}", msg.Username, Environment.MachineName), e.ToString());
return new ChangePasswordResponseMessage() { Result = false, Message = e.Message };
}
}
private ChangePasswordRequestMessage SplitDomainfromUsername(ChangePasswordRequestMessage msg)
{
ChangePasswordRequestMessage ret = msg;
Dictionary<string, string> split = SplitDomainfromUsername(msg.Username, msg.Domain);
ret.Username = split["username"];
ret.Domain = split["domain"];
return ret;
}
private LoginRequestMessage SplitDomainfromUsername(LoginRequestMessage msg)
{
LoginRequestMessage ret = msg;
Dictionary<string, string> split = SplitDomainfromUsername(msg.Username, msg.Domain);
ret.Username = split["username"];
ret.Domain = split["domain"];
return ret;
}
private Dictionary<string, string> SplitDomainfromUsername(string username, string domain)
{
Dictionary<string, string> ret = new Dictionary<string, string>()
{
{"username", username},
{"domain", domain}
};
if (username.Contains("\\"))
{
ret["username"] = username.Trim().Split('\\').DefaultIfEmpty("").LastOrDefault();
ret["domain"] = username.Trim().Split('\\').DefaultIfEmpty("").FirstOrDefault();
}
else if (username.Contains("@"))
{
ret["username"] = username.Trim().Split('@').DefaultIfEmpty("").FirstOrDefault();
ret["domain"] = username.Trim().Split('@').DefaultIfEmpty("").LastOrDefault();
}
else
{
if (String.IsNullOrEmpty(domain))
{
ret["username"] = username;
string domainmember = Abstractions.WindowsApi.pInvokes.GetMachineDomainMembershipEX();
if (string.IsNullOrEmpty(domainmember))
{
ret["domain"] = Environment.MachineName;
}
else
{
ret["domain"] = domainmember;
}
}
}
m_logger.InfoFormat("domain:{0}", ret["domain"]);
if (new List<string>() { ".", "localhost" }.Any(a => a.Equals(ret["domain"], StringComparison.CurrentCultureIgnoreCase)))
{
ret["domain"] = Environment.MachineName;
}
m_logger.InfoFormat("domain:{0}", ret["domain"]);
return ret;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using log4net;
namespace pGina.Plugin.MySQLAuth
{
enum PasswordHashAlgorithm
{
NONE, MD5, SHA1, SHA256, SHA384, SHA512, SMD5, SSHA1, SSHA256, SSHA384, SSHA512
}
class UserEntry
{
private ILog m_logger = LogManager.GetLogger("MySQLAuth.UserEntry");
private string m_hashedPass;
private PasswordHashAlgorithm m_hashAlg;
private string m_name;
private byte[] m_passBytes;
public string Name { get { return m_name; } }
public PasswordHashAlgorithm HashAlg { get { return m_hashAlg; } }
private string HashedPassword { get { return m_hashedPass; } }
public UserEntry(string uname, PasswordHashAlgorithm alg, string hashedPass)
{
m_name = uname;
m_hashAlg = alg;
m_hashedPass = hashedPass;
if (m_hashAlg != PasswordHashAlgorithm.NONE)
m_passBytes = this.Decode(m_hashedPass);
else
m_passBytes = null;
}
private byte[] Decode( string hash )
{
int encInt = Settings.Store.HashEncoding;
Settings.HashEncoding encoding = (Settings.HashEncoding)encInt;
if (encoding == Settings.HashEncoding.HEX)
return FromHexString(hash);
else if (encoding == Settings.HashEncoding.BASE_64)
return Convert.FromBase64String(hash);
else
{
m_logger.ErrorFormat("Unrecognized hash encoding! This shouldn't happen.");
throw new Exception("Unrecognized hash encoding.");
}
}
public bool VerifyPassword( string plainText )
{
if (plainText != null)
{
// If hash algorithm is NONE, just compare the strings
if (HashAlg == PasswordHashAlgorithm.NONE)
return plainText.Equals(HashedPassword);
// Is it a salted hash?
if (HashAlg == PasswordHashAlgorithm.SMD5 ||
HashAlg == PasswordHashAlgorithm.SSHA1 ||
HashAlg == PasswordHashAlgorithm.SSHA256 ||
HashAlg == PasswordHashAlgorithm.SSHA384 ||
HashAlg == PasswordHashAlgorithm.SSHA512)
{
return VerifySaltedPassword(plainText);
}
// If we're here, we have an unsalted hash to compare with, hash and compare
// the hashed bytes.
byte[] hashedPlainText = HashPlainText(plainText);
if (hashedPlainText != null)
return hashedPlainText.SequenceEqual(m_passBytes);
else
return false;
}
else
{
return false;
}
}
private bool VerifySaltedPassword(string plainText)
{
using (HashAlgorithm hasher = GetHasher())
{
if (hasher != null)
{
if (hasher.HashSize % 8 != 0)
m_logger.ErrorFormat("WARNING: hash size is not a multiple of 8. Hashes may not be evaluated correctly!");
int hashSizeBytes = hasher.HashSize / 8;
if( m_passBytes.Length > hashSizeBytes )
{
// Get the salt
byte[] salt = new byte[m_passBytes.Length - hashSizeBytes];
Array.Copy(m_passBytes, hashSizeBytes, salt, 0, salt.Length);
m_logger.DebugFormat("Found {1} byte salt: [{0}]", string.Join(",", salt), salt.Length);
// Get the hash
byte[] hashedPassAndSalt = new byte[hashSizeBytes];
Array.Copy(m_passBytes, 0, hashedPassAndSalt, 0, hashSizeBytes);
// Build an array with the plain text and the salt
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
byte[] plainTextAndSalt = new byte[salt.Length + plainTextBytes.Length];
plainTextBytes.CopyTo(plainTextAndSalt, 0);
salt.CopyTo(plainTextAndSalt, plainTextBytes.Length);
// Compare the byte arrays
byte[] hashedPlainTextAndSalt = hasher.ComputeHash(plainTextAndSalt);
return hashedPlainTextAndSalt.SequenceEqual(hashedPassAndSalt);
}
else
{
m_logger.ErrorFormat("Found hash of length {0}, expected at least {1} bytes.",
m_passBytes.Length, hashSizeBytes);
throw new Exception("Hash length is too short, no salt found.");
}
}
}
return false;
}
private byte[] HashPlainText( string plainText )
{
if (HashAlg == PasswordHashAlgorithm.NONE)
throw new Exception("Tried to hash a password when algorithm is NONE.");
byte[] bytes = Encoding.UTF8.GetBytes(plainText);
byte[] result = null;
using (HashAlgorithm hasher = GetHasher())
{
if( hasher != null )
result = hasher.ComputeHash(bytes);
}
return result;
}
private HashAlgorithm GetHasher()
{
switch (HashAlg)
{
case PasswordHashAlgorithm.NONE:
return null;
case PasswordHashAlgorithm.MD5:
case PasswordHashAlgorithm.SMD5:
return MD5.Create();
case PasswordHashAlgorithm.SHA1:
case PasswordHashAlgorithm.SSHA1:
return SHA1.Create();
case PasswordHashAlgorithm.SHA256:
case PasswordHashAlgorithm.SSHA256:
return SHA256.Create();
case PasswordHashAlgorithm.SHA512:
case PasswordHashAlgorithm.SSHA512:
return SHA512.Create();
case PasswordHashAlgorithm.SHA384:
case PasswordHashAlgorithm.SSHA384:
return SHA384.Create();
default:
m_logger.ErrorFormat("Unrecognized hash algorithm!");
return null;
}
}
private string ToHexString(byte[] bytes)
{
StringBuilder builder = new StringBuilder();
foreach( byte b in bytes )
{
builder.Append(b.ToString("x2"));
}
return builder.ToString();
}
private byte[] FromHexString(string hex)
{
byte[] bytes = null;
if (hex.Length % 2 != 0)
{
hex = hex + "0";
bytes = new byte[hex.Length + 1 / 2];
}
else
{
bytes = new byte[hex.Length / 2];
}
for (int i = 0; i < hex.Length / 2; i++ )
{
bytes[i] = Convert.ToByte(hex.Substring(i*2, 2), 16);
}
return bytes;
}
}
}
<file_sep>/*
Copyright (c) 2018, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.DirectoryServices.Protocols;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using pGina.Shared.Types;
namespace pGina.Plugin.Ldap
{
public class LdapServer : IDisposable
{
private log4net.ILog m_logger = log4net.LogManager.GetLogger("LdapServer");
/// <summary>
/// The connection object.
/// </summary>
private LdapConnection m_conn = null;
/// <summary>
/// The server identification (host,port)
/// </summary>
private LdapDirectoryIdentifier m_serverIdentifier;
/// <summary>
/// Whether or not to use SSL
/// </summary>
private bool m_useSsl;
/// <summary>
/// Whether or not to use SSL
/// </summary>
private bool m_useTls;
/// <summary>
/// Whether or not to verify the SSL certificate
/// </summary>
private bool m_verifyCert;
/// <summary>
/// Check the SSL certificate against a copy in local machine cert store
/// </summary>
private bool m_verifyCertMatch;
/// <summary>
/// The SSL certificate to verify against (if required)
/// </summary>
private X509Certificate2 m_cert;
/// <summary>
/// The SSL certificate to verify against (if required)
/// </summary>
private List<string> m_hostname;
private Dictionary<string, string> pGinaSettings = new Dictionary<string, string>();
/// <summary>
/// The number of seconds to wait for a connection before giving up.
/// </summary>
public int Timeout { get; set; }
public LdapServer()
{
m_conn = null;
m_cert = null;
Timeout = Settings.Store.LdapTimeout;
m_useSsl = Settings.Store.UseSsl;
m_useTls = Settings.Store.UseTls;
m_verifyCert = Settings.Store.RequireCert;
string certFile = Settings.Store.ServerCertFile;
if (certFile.Equals("MATCH"))
{
certFile = "";
m_verifyCertMatch = true;
}
if ((m_useSsl || m_useTls) && m_verifyCert)
{
if ( !string.IsNullOrEmpty(certFile) && File.Exists(certFile))
{
m_logger.DebugFormat("Loading server certificate: {0}", certFile);
m_cert = new X509Certificate2(certFile);
}
else
{
m_logger.DebugFormat("Certificate file not provided or not found, will validate against Windows store.", certFile);
}
}
string[] hosts = Settings.Store.LdapHost;
int port = Settings.Store.LdapPort;
m_serverIdentifier = new LdapDirectoryIdentifier(hosts, port, false, false);
m_hostname = hosts.ToList();
m_logger.DebugFormat("Initializing LdapServer host(s): [{0}], port: {1}, useSSL = {2}, useTLS = {3}, verifyCert = {4}",
string.Join(", ", hosts), port, m_useSsl, m_useTls, m_verifyCert);
pGinaSettings = pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" });
this.Connect();
}
private void Connect()
{
// Are we re-connecting? If so, close the previous connection.
if (m_conn != null)
{
this.Close();
}
m_conn = new LdapConnection(m_serverIdentifier);
m_conn.Timeout = new System.TimeSpan(0,0,Timeout);
m_logger.DebugFormat("Timeout set to {0} seconds.", Timeout);
m_conn.SessionOptions.ProtocolVersion = 3;
if ((m_useSsl || m_useTls) && m_verifyCert)
{
m_conn.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback(VerifyCert);
}
else
{
m_conn.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback((conn, cert) => true);
}
if (m_useTls)
{
try
{
m_conn.SessionOptions.StartTransportLayerSecurity(new DirectoryControlCollection());
}
catch (Exception e)
{
m_logger.ErrorFormat("Start TLS failed with {0}", e.Message);
m_conn = null;
}
}
if (m_useSsl)
{
m_conn.SessionOptions.SecureSocketLayer = m_useSsl;
}
}
/// <summary>
/// Check that certificate CN or SubjectAltName matches LDAP server name
/// </summary>
/// <param name="conn">The LDAP connection.</param>
/// <param name="cert">The server's certificate</param>
/// <returns>true if verification succeeds, false otherwise.</returns>
private bool VerifyCertName(LdapConnection conn, X509Certificate2 cert)
{
string certCN = "";
List<string> name = new List<string>() { conn.SessionOptions.HostName };
try
{
List<IPAddress> Ipaddr = new List<IPAddress>();
IPHostEntry hostFQDN = Dns.GetHostEntry(conn.SessionOptions.HostName);
Ipaddr = hostFQDN.AddressList.ToList();
foreach (string host in m_hostname)
{
hostFQDN = Dns.GetHostEntry(host.Trim());
if (hostFQDN.AddressList.ToList().Any(x => Ipaddr.Contains(x)))
{
name.Add(host.Trim());
}
}
}
catch (Exception ex)
{
m_logger.InfoFormat("Error in VerifyCertName() during GetHostEntry:{0}", ex);
}
m_logger.InfoFormat("Verify DNS name against:{0}", string.Join(" ", name));
string[] str = cert.SubjectName.Decode(X500DistinguishedNameFlags.DoNotUsePlusSign | X500DistinguishedNameFlags.DoNotUseQuotes | X500DistinguishedNameFlags.UseNewLines | X500DistinguishedNameFlags.UseUTF8Encoding).Trim('\r').Split('\n');
for (int x = 0; x < str.Length; x++)
{
if (str[x].StartsWith("CN="))
certCN = str[x].Replace("CN=", "").Trim();
}
certCN = certCN.Replace(".", @"\.").Replace("*", ".*");
if (name.Any(x => Regex.IsMatch(x, "^" + certCN)))
{
return true;
}
List<string> certSAN = new List<string>();
foreach (X509Extension extension in cert.Extensions)
{
AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);
string[] adata = asndata.Format(true).Trim('\r').Split('\n');
for (int x = 0; x < adata.Length; x++)
{
if (adata[x].StartsWith("DNS-Name="))
{
string SANregex = adata[x].Replace("DNS-Name=", "").Trim();
SANregex = SANregex.Replace(".", @"\.").Replace("*", ".*");
certSAN.Add(SANregex);
}
}
}
foreach (string csan in certSAN)
{
if (name.Any(x => Regex.IsMatch(x, "^" + csan)))
{
return true;
}
}
return false;
}
/// <summary>
/// This is the verify certificate callback method used when initially binding to the
/// LDAP server. This manages all certificate validation.
/// </summary>
/// <param name="conn">The LDAP connection.</param>
/// <param name="cert">The server's certificate</param>
/// <returns>true if verification succeeds, false otherwise.</returns>
private bool VerifyCert(LdapConnection conn, X509Certificate cert)
{
m_logger.Debug("VerifyCert(...)");
m_logger.DebugFormat("Verifying certificate from host: {0}", conn.SessionOptions.HostName);
// Convert to X509Certificate2
X509Certificate2 serverCert = new X509Certificate2(cert);
// If we don't need to verify the cert, the verification succeeds
if (!m_verifyCert)
{
m_logger.Debug("Server certificate accepted without verification.");
return true;
}
if (m_verifyCertMatch)
{
try
{
X509Store certStore = new X509Store(StoreLocation.LocalMachine);
certStore.Open(OpenFlags.ReadOnly);
if (certStore.Certificates.Contains(cert))
return true;
else
{
m_logger.ErrorFormat("Can't find server cert in Windows store. Place it in Local Computer cert store.");
return false;
}
}
catch (Exception e)
{
m_logger.ErrorFormat("Server certificate validation exception: {0}", e.Message);
}
return false;
}
// If the certificate is null, then we verify against the machine's/user's certificate store
if (m_cert == null)
{
m_logger.Debug("Verifying server cert with Windows store.");
try
{
if (!serverCert.Verify())
{
m_logger.Debug("Server certificate verification failed.");
return false;
}
// Check that certificate name match server name
if (!VerifyCertName(conn, serverCert))
{
m_logger.Debug("Server certificate does not match hostname.");
return false;
}
// If we get here, validation succeeded.
m_logger.Debug("Server certificate verification succeeded.");
return true;
}
catch (SecurityTokenValidationException e)
{
m_logger.ErrorFormat("Server certificate validation failed: {0}", e.Message);
return false;
}
catch (Exception e)
{
m_logger.ErrorFormat("Server certificate validation failed: {0}", e.Message);
return false;
}
}
else
{
m_logger.Debug("Validating server certificate with provided certificate.");
// Verify against the provided cert by comparing the thumbprint
bool result = m_cert.Thumbprint == serverCert.Thumbprint;
if (result) m_logger.Debug("Server certificate validated.");
else m_logger.Debug("Server certificate validation failed.");
return result;
}
}
/// <summary>
/// Tries to bind to the server anonymously. Throws LdapException if the
/// bind fails.
/// </summary>
public void Bind()
{
if (m_conn == null)
throw new LdapException("Bind attempted when server is not connected.");
m_logger.DebugFormat("Attempting anonymous bind", m_conn.SessionOptions.HostName);
m_conn.AuthType = AuthType.Anonymous;
m_conn.Credential = null;
try
{
m_conn.Bind();
m_logger.DebugFormat("Successful bind to {0}", m_conn.SessionOptions.HostName);
}
catch (LdapException e)
{
m_logger.ErrorFormat("LdapException: {0} {1} {2}", e.ErrorCode, e.Message, e.ServerErrorMessage);
throw e;
}
catch (InvalidOperationException e)
{
// This shouldn't happen, but log it and re-throw
m_logger.ErrorFormat("InvalidOperationException: {0}", e.Message);
throw e;
}
catch (Exception e)
{
// This shouldn't happen, but log it and re-throw
m_logger.ErrorFormat("Bind Exception: {0}", e.Message);
throw e;
}
}
public void BindForSearch()
{
string searchDn = Settings.Store.SearchDN;
string searchPw = Settings.Store.GetEncryptedSetting("SearchPW");
if (string.IsNullOrEmpty(searchDn))
// Bind anonymously
this.Bind();
else
// Bind with credentials
this.Bind(new NetworkCredential(searchDn, searchPw));
}
/// <summary>
/// Try to bind to the LDAP server with the given credentials. This uses
/// basic authentication. Throws LdapException if the bind fails.
/// </summary>
/// <param name="creds">The credentials to use when binding.</param>
public void Bind(NetworkCredential creds)
{
if (m_conn == null)
throw new LdapException("Bind attempted when server is not connected.");
m_logger.DebugFormat("Attempting bind as {0}", creds.UserName);
m_conn.AuthType = AuthType.Basic;
try
{
m_conn.Bind(creds);
m_logger.DebugFormat("Successful bind to {0} as {1}", m_conn.SessionOptions.HostName, creds.UserName);
}
catch (LdapException e)
{
m_logger.ErrorFormat("LdapException: {0} {1} {2}", e.ErrorCode, e.Message, e.ServerErrorMessage);
throw e;
}
catch (InvalidOperationException e)
{
// This shouldn't happen, but log it and re-throw
m_logger.ErrorFormat("InvalidOperationException: {0}", e.Message);
throw e;
}
catch (Exception e)
{
// This shouldn't happen, but log it and re-throw
m_logger.ErrorFormat("Bind Exception: {0}", e.Message);
throw e;
}
}
public void Close()
{
if (m_conn != null)
{
m_logger.DebugFormat("Closing LDAP connection to {0}.", m_conn.SessionOptions.HostName);
if (m_useTls)
m_conn.SessionOptions.StopTransportLayerSecurity();
m_conn.Dispose();
m_conn = null;
}
}
/// <summary>
/// Does a search in the subtree at searchBase, using the filter provided and
/// returns the DN of the first match.
/// </summary>
/// <param name="searchBase">The DN of the root of the subtree for the search (search context).</param>
/// <param name="filter">The search filter.</param>
/// <returns>The DN of the first match, or null if no matches are found.</returns>
public string FindFirstDN(string searchBase, string filter)
{
SearchRequest req = new SearchRequest(searchBase, filter, SearchScope.Subtree, null);
SearchResponse resp = (SearchResponse)m_conn.SendRequest(req);
if (resp.Entries.Count > 0)
{
return resp.Entries[0].DistinguishedName;
}
return null;
}
public bool MemberOfGroup(string user, string group)
{
string groupDn = Settings.Store.GroupDnPattern;
string groupAttribute = Settings.Store.GroupMemberAttrib;
if (string.IsNullOrEmpty(groupDn))
throw new Exception("Can't resolve group DN, group DN pattern missing.");
if (string.IsNullOrEmpty(groupAttribute))
throw new Exception("Can't resolve group membership, group attribute missing.");
groupDn = Regex.Replace(groupDn, @"\%g", group);
string target = user;
// If the group attribute is "uniqueMember" or "member" then the LDAP server
// is using groupOfUniqueNames or groupOfNames object class. The group
// list uses full DNs instead of just uids, so we need to expand the
// username to the full DN.
if (groupAttribute.Equals("uniqueMember", StringComparison.CurrentCultureIgnoreCase) ||
groupAttribute.Equals("member", StringComparison.CurrentCultureIgnoreCase))
{
// Try to generate the full DN for the user.
m_logger.DebugFormat("Attempting to generate DN for user {0}", user);
target = this.GetUserDN(user);
if (target == null)
{
m_logger.Error("Unable to generate DN for user, using username.");
target = user;
}
}
string filter = string.Format("({0}={1})", groupAttribute, target);
m_logger.DebugFormat("Searching for group membership, DN: {0} Filter: {1}", groupDn, filter);
try
{
SearchRequest req = new SearchRequest(groupDn, filter, SearchScope.Base, null);
SearchResponse resp = (SearchResponse)m_conn.SendRequest(req);
return resp.Entries.Count > 0;
}
catch (Exception e)
{
m_logger.ErrorFormat("Error when checking for group membership: {0}", e.Message);
return false;
}
}
public void Dispose()
{
this.Close();
}
/// <summary>
/// Attempt to authenticate the user by binding to the LDAP server.
/// </summary>
/// <returns></returns>
public BooleanResult Authenticate(string uname, string password, SessionProperties properties)
{
// Check for empty password. If configured to do so, we fail on
// empty passwords.
bool allowEmpty = Settings.Store.AllowEmptyPasswords;
if (!allowEmpty && string.IsNullOrEmpty(password))
{
m_logger.Info("Authentication failed due to empty password.");
return new BooleanResult { Success = false, Message = "Authentication failed due to empty password." };
}
// Get the user's DN
string userDN = "";
try
{
userDN = GetUserDN(uname);
}
catch (Exception ex)
{
return new BooleanResult { Success = false, Message = ex.Message };
}
// If we've got a userDN, attempt to authenticate the user
if (userDN != null)
{
// Attempt to bind with the user's LDAP credentials
m_logger.DebugFormat("Attempting to bind with DN {0}", userDN);
NetworkCredential ldapCredential = new NetworkCredential(userDN, password);
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
try
{
this.Bind(ldapCredential);
}
catch (LdapException e)
{
// 49 is invalid credentials
if (e.ErrorCode == 49)
{
if (PWDexpired(uname, password).Success)
{
m_logger.InfoFormat("Password expired");
userInfo.PasswordEXP = true;
properties.AddTrackedSingle<UserInformation>(userInfo);
return new BooleanResult { Message = "Password expired", Success = true };
}
m_logger.ErrorFormat("LDAP bind failed: invalid credentials.");
return new BooleanResult { Success = false, Message = "Authentication via LDAP failed. Invalid credentials." };
}
// Let caller handle other kinds of exceptions
throw;
}
catch (Exception e)
{
// IBM LDAP doesnt return error 49 so we analyze the exeption string
if (e.ToString().Contains("pGina.Plugin.Ldap.LdapServer.Bind"))
{
m_logger.ErrorFormat("The user name or password is incorrect: {0}", e.Message);
return new BooleanResult { Success = false, Message = "The user name or password is incorrect" };
}
m_logger.ErrorFormat("LDAP plugin failed {0}",e.Message);
return new BooleanResult { Success = false, Message = String.Format("LDAP plugin failed\n{0}",e.Message) };
}
// If we get here, the authentication was successful, we're done!
m_logger.DebugFormat("LDAP DN {0} successfully bound to server, return success", ldapCredential.UserName);
BooleanResultEx pwd = PWDexpired(uname, password);
if (pwd.Success) //samba ldap may not throw exception 49
{
m_logger.InfoFormat("Password expired");
userInfo.PasswordEXP = true;
properties.AddTrackedSingle<UserInformation>(userInfo);
return new BooleanResult { Message = "Password expired", Success = true };
}
else
{
userInfo.PasswordEXPcntr = new TimeSpan(pwd.Int64);
properties.AddTrackedSingle<UserInformation>(userInfo);
}
try
{
string[] AttribConv = Settings.Store.AttribConv;
Dictionary<string, string> Convert_attribs = new Dictionary<string, string>();
foreach (string str in AttribConv)
{
if (Regex.IsMatch(str, @"\w\t\w"))
{
// Convert_attribs.add("Email", "mail")
Convert_attribs.Add(str.Substring(0, str.IndexOf('\t')).Trim(), str.Substring(str.IndexOf('\t')).Trim());
}
}
if (Convert_attribs.Count > 0)
{
// search all values at once
Dictionary<string, List<string>> search = GetUserAttribValue(userDN, "(objectClass=*)", SearchScope.Subtree, Convert_attribs.Values.ToArray());
if (search.Count > 0)
{
foreach (KeyValuePair<string, List<string>> search_p in search)
{
foreach (KeyValuePair<string, string> Convert_attribs_p in Convert_attribs)
{
// Convert_attribs_p.add("Email", "mail")
// search_p.add("mail", "<EMAIL>")
// if Convert_attribs_p.value == search_p.key (if mail == mail)
if (Convert_attribs_p.Value.Equals(search_p.Key, StringComparison.CurrentCultureIgnoreCase))
{
// loop through all props of UserInformation
foreach (PropertyInfo prop in userInfo.GetType().GetProperties())
{
// if prop.name == Convert_attribs_p.key (if Email == Email)
if (prop.Name.Equals(Convert_attribs_p.Key, StringComparison.CurrentCultureIgnoreCase))
{
// set this value (userinfo.Email = "<EMAIL>")
try
{
object o = Convert.ChangeType(search_p.Value.First(), prop.PropertyType);
prop.SetValue(userInfo, o, null);
m_logger.DebugFormat("convert attrib:[{0}] to [{1}] value:[{2}]", search_p.Key, Convert_attribs_p.Key, search_p.Value.First());
}
catch (Exception ex)
{
m_logger.ErrorFormat("can't convert attrib:[{0}] to [{1}] Error:[{2}]", search_p.Key, Convert_attribs_p.Key, ex.Message);
}
}
}
}
}
}
}
}
}
catch (Exception e)
{
m_logger.ErrorFormat("can't convert ldap value", e.Message);
}
return new BooleanResult { Success = true };
} // end if(userDN != null)
else
{
m_logger.ErrorFormat("Unable to determine DN for: {0}", uname);
return new BooleanResult { Success = false, Message = "Unable to determine the user's LDAP DN for authentication." };
}
}
internal BooleanResultEx PWDexpired(string uname, string password)
{
//m_logger.InfoFormat("PWDexpired");
string userDN = GetUserDN(uname);
if (userDN == null)
{
return new BooleanResultEx { Success = false };
}
//m_logger.InfoFormat("userDN={0}", userDN);
List<string> ntps = m_serverIdentifier.Servers.ToList();
ntps.AddRange(pGinaSettings["ntpservers"].Split('\0').ToList());
m_logger.InfoFormat("ntplist:{0}", String.Join(" ", ntps));
Dictionary<string, List<string>> search = GetUserAttribValue(userDN, "(objectClass=*)", SearchScope.Base, new string[] { "shadowMax", "sambaPwdMustChange", "userAccountControl", "msDS-User-Account-Control-Computed", "msDS-UserPasswordExpiryTimeComputed", "pwdLastSet", "memberOf", "msDS-PSOApplied" });
#region samba
if (search.ContainsKey("shadowmax"))
{
//m_logger.InfoFormat("shadowmax found={0}", search["shadowmax"].First());
int shadowmax = -1;
try
{
shadowmax = Convert.ToInt32(search["shadowmax"].First());
}
catch (Exception e)
{
m_logger.FatalFormat("Unable to convert \"{0}\" return from GetUserAttribValue to int {1}", "shadowmax", e.Message);
}
if (shadowmax == -1 /*samba DONT_EXPIRE_PASSWD*/)
{
return new BooleanResultEx { Success = false };
}
try
{
shadowmax = Convert.ToInt32(new TimeSpan(shadowmax, 0, 0, 0).TotalSeconds);
}
catch (Exception e)
{
m_logger.FatalFormat("Unable to convert \"{0}\" to seconds {1}", "shadowmax", e.Message);
return new BooleanResultEx { Success = false };
}
//m_logger.InfoFormat("shadowmax={0}", shadowmax);
if (search.ContainsKey("sambapwdmustchange"))
{
//m_logger.InfoFormat("sambapwdmustchange found");
int sambapwdmustchange = 0;
try
{
sambapwdmustchange = Convert.ToInt32(search["sambapwdmustchange"].First());
}
catch (Exception e)
{
m_logger.FatalFormat("Unable to convert \"{0}\" return from GetUserAttribValue to int {1}", "sambapwdmustchange", e.Message);
}
if (sambapwdmustchange == 0)
{
return new BooleanResultEx { Success = false };
}
//m_logger.InfoFormat("sambapwdmustchange={0}", sambapwdmustchange);
int DateNowSec = 0;
DateTime NTPtime = DateTime.MaxValue;
try
{
DateTime time = Abstractions.Windows.Networking.GetNetworkTime(ntps.ToArray());
//m_logger.InfoFormat("NTP {0}", time);
if (time == DateTime.MinValue)
{
m_logger.InfoFormat("can't get time from {0}", String.Join(" ", ntps));
NTPtime = DateTime.MaxValue;
}
else
{
NTPtime = time;
DateNowSec = Convert.ToInt32((NTPtime - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
}
}
catch (Exception e)
{
m_logger.FatalFormat("Unable to convert NTP time to ticks {0}", e);
}
if (NTPtime != DateTime.MaxValue)
{
m_logger.InfoFormat("{0} > {1}", DateNowSec, sambapwdmustchange);
if (DateNowSec + 86400 /*one day in future*/ > sambapwdmustchange)
{
m_logger.InfoFormat("pwd expired");
return new BooleanResultEx { Success = true, Message = "Password expired" };
}
TimeSpan PWDlasts = new TimeSpan((long)(sambapwdmustchange - DateNowSec) * (long)10000000);
if (PWDlasts < new TimeSpan(5, 0, 0, 0))
{
m_logger.InfoFormat("password will expire in less than 5 days, to be exact:{0:c}", PWDlasts);
return new BooleanResultEx { Success = false, Int64 = PWDlasts.Ticks };
}
}
}
}
#endregion
#region AD
if (search.ContainsKey("msds-user-account-control-computed"))
{
//m_logger.InfoFormat("msds-user-account-control-computed found={0}", search["msds-user-account-control-computed"].First());
int msdsuseraccountcontrolcomputed = -1;
try
{
msdsuseraccountcontrolcomputed = Convert.ToInt32(search["msds-user-account-control-computed"].First());
}
catch (Exception e)
{
m_logger.FatalFormat("Unable to convert \"{0}\" return from GetUserAttribValue to int {1}", "msds-user-account-control-computed", e.Message);
}
if (((int)Abstractions.WindowsApi.pInvokes.structenums.UserFlags.UF_DONT_EXPIRE_PASSWD & msdsuseraccountcontrolcomputed) == (int)Abstractions.WindowsApi.pInvokes.structenums.UserFlags.UF_DONT_EXPIRE_PASSWD || ((int)Abstractions.WindowsApi.pInvokes.structenums.UserFlags.UF_PASSWD_CANT_CHANGE & msdsuseraccountcontrolcomputed) == (int)Abstractions.WindowsApi.pInvokes.structenums.UserFlags.UF_PASSWD_CANT_CHANGE)
{
m_logger.InfoFormat("userAccountControl contain UF_DONT_EXPIRE_PASSWD and or UF_PASSWD_CANT_CHANGE");
return new BooleanResultEx { Success = false };
}
if (((int)Abstractions.WindowsApi.pInvokes.structenums.UserFlags.UF_PASSWORD_EXPIRED & msdsuseraccountcontrolcomputed) == (int)Abstractions.WindowsApi.pInvokes.structenums.UserFlags.UF_PASSWORD_EXPIRED)
{
m_logger.InfoFormat("userAccountControl contain UF_PASSWORD_EXPIRED");
return new BooleanResultEx { Success = true, Message = "Password expired" };
}
DateTime msdsuserpasswordexpirytimecomputed = DateTime.MaxValue;
if (search.ContainsKey("msds-userpasswordexpirytimecomputed"))
{
//m_logger.InfoFormat("msds-userpasswordexpirytimecomputed={0}", search["msds-userpasswordexpirytimecomputed"].First());
try
{
msdsuserpasswordexpirytimecomputed = DateTime.FromFileTimeUtc(Convert.ToInt64(search["msds-userpasswordexpirytimecomputed"].First()));
}
catch (Exception e)
{
m_logger.FatalFormat("Unable to convert \"{0}\" return from GetUserAttribValue to int {1}", "msds-userpasswordexpirytimecomputed", e.Message);
return new BooleanResultEx { Success = false };
}
}
if (msdsuserpasswordexpirytimecomputed == DateTime.MaxValue)
{
return new BooleanResultEx { Success = false };
}
DateTime NTPtime = DateTime.MaxValue;
try
{
NTPtime = Abstractions.Windows.Networking.GetNetworkTime(ntps.ToArray());
//m_logger.InfoFormat("NTP {0:yyyy.MM.dd.HH:mm:ss}", NTPtime);
if (NTPtime == DateTime.MinValue)
{
m_logger.InfoFormat("can't get time from {0}", String.Join(" ", ntps));
NTPtime = DateTime.MaxValue;
}
}
catch (Exception e)
{
m_logger.FatalFormat("Unable to convert NTP time to ticks {0}", e);
}
if (NTPtime != DateTime.MaxValue)
{
m_logger.InfoFormat("{0:yyyy.MM.dd.HH:mm:ss}-{1:yyyy.MM.dd.HH:mm:ss}", msdsuserpasswordexpirytimecomputed, NTPtime);
TimeSpan PWDlasts = msdsuserpasswordexpirytimecomputed - NTPtime;
//m_logger.InfoFormat("PWDlasts:{0:c}", PWDlasts);
if (PWDlasts < new TimeSpan(1, 0, 0, 0))
{
return new BooleanResultEx { Success = true, Message = "Password expired" };
}
if (PWDlasts < new TimeSpan(5, 0, 0, 0))
{
m_logger.InfoFormat("password will expire in less than 5 days, to be exact:{0:c}", PWDlasts);
return new BooleanResultEx { Success = false, Int64 = PWDlasts.Ticks };
}
}
return new BooleanResultEx { Success = false };
}
#endregion
return new BooleanResultEx { Success = false };
}
public string GetUserDN(string uname)
{
bool doSearch = Settings.Store.DoSearch;
if (!doSearch)
{
return CreateUserDN(uname);
}
else
{
return FindUserDN(uname);
}
}
/// <summary>
/// Will search an attribute and return the corresponding values
/// <para>The DN where the search will start at</para>
/// <para>string array of attributes to search at</para>
/// <para>Searchscope</para>
/// <para>Filter</para>
/// return key ToLower()
/// </summary>
/// <returns></returns>
public Dictionary<string, List<string>> GetUserAttribValue(string path, string filter, SearchScope scope, string[] Attrib)
{
Dictionary<string, List<string>> ret = new Dictionary<string, List<string>>();
try
{
SearchRequest req = new SearchRequest(path, filter, scope, Attrib);
SearchResponse resp = (SearchResponse)m_conn.SendRequest(req);
foreach (SearchResultEntry entry in resp.Entries)
{
if (Attrib.All(element => element.Equals("dn", StringComparison.CurrentCultureIgnoreCase)))
{
ret.Add("dn",new List<string>(new string[] {entry.DistinguishedName}));
}
foreach (String name in entry.Attributes.AttributeNames)
{
List<string> values = new List<string>();
for (int x = 0; x < entry.Attributes[name].Count; x++)
{
object res = entry.Attributes[name][x];
if (res == null)
{
break;
}
string str = "";
if (res.GetType() == typeof(byte[]))
{
foreach (byte b in (byte[])res)
{
str += String.Format("{0:X2}", b);
}
}
else
{
str = res.ToString();
}
if (!String.IsNullOrEmpty(str))
{
values.Add(str);
}
}
if (values.Count > 0)
{
ret.Add(name.ToLower(),values);
}
}
}
}
catch (Exception e)
{
m_logger.FatalFormat("GetUserAttribValue Error:{0}",e.Message);
}
return ret;
}
/// <summary>
/// Attempts to find the DN for the user by searching a set of LDAP trees.
/// The base DN for each of the trees is retrieved from Settings.Store.SearchContexts.
/// The search filter is taken from Settings.Store.SearchFilter. If all
/// searches fail, this method returns null.
/// </summary>
/// <returns>The DN of the first object found, or null if searches fail.</returns>
private string FindUserDN(string uname)
{
// Attempt to bind in order to do the search
this.BindForSearch();
string filter = CreateSearchFilter(uname);
m_logger.DebugFormat("Searching for DN using filter {0}", filter);
string[] contexts = Settings.Store.SearchContexts;
foreach (string context in contexts)
{
m_logger.DebugFormat("Searching context {0}", context);
string dn = null;
try
{
dn = this.FindFirstDN(context, filter);
}
catch (DirectoryOperationException e)
{
m_logger.ErrorFormat("DirectoryOperationException: {0}", e.Message);
}
catch (Exception e)
{
m_logger.ErrorFormat("FindUserDN failed: {0}", e.Message);
return null;
}
if (dn != null)
{
m_logger.DebugFormat("Found DN: {0}", dn);
return dn;
}
}
m_logger.DebugFormat("No DN found in any of the contexts.");
return null;
}
/// <summary>
/// This generates the DN for the user assuming that a pattern has
/// been provided. This assumes that Settings.Store.DnPattern has
/// a valid DN pattern.
/// </summary>
/// <returns>A DN that can be used for binding with LDAP server.</returns>
private string CreateUserDN(string uname)
{
string result = Settings.Store.DnPattern;
// Replace the username
result = Regex.Replace(result, @"\%u", uname);
return result;
}
/// <summary>
/// This generates the search filter to be used when searching for the DN
/// </summary>
/// <returns>A search filter.</returns>
private string CreateSearchFilter(string uname)
{
string result = Settings.Store.SearchFilter;
// Replace the username
result = Regex.Replace(result, @"\%u", uname);
return result;
}
public bool SetUserAttribute(string uname, string attribute, string value)
{
string userDN = this.GetUserDN(uname);
try
{
DirectoryAttributeModification mod = new DirectoryAttributeModification
{
Name = attribute,
Operation = DirectoryAttributeOperation.Replace
};
mod.Add(value);
ModifyRequest req = new ModifyRequest(userDN);
req.Modifications.Add(mod);
m_conn.SendRequest(req);
}
catch (Exception e)
{
m_logger.FatalFormat("can't add attribute:{0} because of error:{1}", attribute, e.Message);
return false;
}
if (attribute.ToLower().Equals("sambapwdlastset"))
{
Dictionary<string, List<string>> SearchResult = GetUserAttribValue(userDN, "(objectClass=*)", SearchScope.Subtree, new string[] { "shadowMax", "sambaPwdMustChange" });
if (SearchResult.ContainsKey("shadowmax") && SearchResult.ContainsKey("sambapwdmustchange"))
{
int shadowMax = 0;
try
{
shadowMax = Convert.ToInt32(SearchResult["shadowmax"].First());
}
catch (Exception e)
{
m_logger.FatalFormat("SetUserAttribute: Unable to convert return from GetUserAttribValue to int {0}", e.Message);
return false;
}
if (shadowMax > 0)
{
TimeMethod time = TimeMethod.methods[Methods.Timestamps];
string t = time.time(new TimeSpan(shadowMax, 0, 0, 0));
if (!t.Equals("0"))
if (!SetUserAttribute(uname, "sambaPwdMustChange", t))
return false;
}
}
}
return true;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using log4net;
using pGina.Shared.Interfaces;
using pGina.Shared.Types;
using pGina.Shared.Settings;
namespace pGina.Plugin.SingleUser
{
public class PluginImpl : IPluginConfiguration, IPluginAuthenticationGateway
{
private ILog m_logger = LogManager.GetLogger("SingleUserPlugin");
public static Guid PluginUuid = new Guid("{81F8034E-E278-4754-B10C-7066656DE5B7}");
public PluginImpl()
{
using(Process me = Process.GetCurrentProcess())
{
Settings.Init();
m_logger.DebugFormat("Plugin initialized on {0} in PID: {1} Session: {2}", Environment.MachineName, me.Id, me.SessionId);
}
}
public string Name
{
get { return "Single User Login"; }
}
public string Description
{
get { return "Allow re-direction of all authenticated users to a single set of credentials"; }
}
public string Version
{
get
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public Guid Uuid
{
get { return PluginUuid; }
}
public void Configure()
{
Configuration conf = new Configuration();
conf.ShowDialog();
}
private bool DidPluginAuth(string uuid, SessionProperties properties)
{
try
{
Guid pluginUuid = new Guid(uuid);
PluginActivityInformation pluginInfo = properties.GetTrackedSingle<PluginActivityInformation>();
return pluginInfo.GetAuthenticationResult(pluginUuid).Success;
}
catch (Exception e)
{
m_logger.ErrorFormat("Unable to validate that {0} authenticated user: {1}", uuid, e);
return false;
}
}
public BooleanResult AuthenticatedUserGateway(SessionProperties properties)
{
m_logger.DebugFormat("AuthenticatedUserGateway[{0}]", properties.GetTrackedSingle<UserInformation>().Username);
string username = Settings.Store.Username;
string domain = Settings.Store.Domain;
string password = Settings.Store.GetEncryptedSetting("Password", null);
bool requirePlugins = Settings.Store.RequirePlugins;
bool requireAllPlugins = Settings.Store.RequireAllPlugins;
string[] pluginList = Settings.Store.RequiredPluginList;
// Do we have to check for a specific plugin(s)?
if (requirePlugins && pluginList.Length > 0)
{
//Requires all plugins
if (requireAllPlugins)
{
foreach (string pluginUuid in pluginList)
{
m_logger.DebugFormat("Checking whether {0} authenticated the user", pluginUuid);
if (!DidPluginAuth(pluginUuid, properties))
return new BooleanResult() { Success = true }; // Silent bypass
}
}
//Requires any plugin
else
{
bool matchFound = false;
foreach (string pluginUuid in pluginList)
{
matchFound = DidPluginAuth(pluginUuid, properties);
if (matchFound)
break;
}
if (!matchFound)
return new BooleanResult() { Success = true }; //Silent bypass
}
}
// Substitute
m_logger.DebugFormat("Re-writing user information to login with {0}\\{1}", domain, username);
properties.GetTrackedSingle<UserInformation>().Username = username;
properties.GetTrackedSingle<UserInformation>().Domain = domain;
properties.GetTrackedSingle<UserInformation>().Password = <PASSWORD>;
return new BooleanResult() { Success = true };
}
public void Starting() { }
public void Stopping() { }
}
}
<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <windows.h>
#include <credentialprovider.h>
#include <string>
// Define the fields and field states for our tiles. Heavily modified/borrowed from sample
// as their struct layout makes pretty good sense.
#pragma warning(push)
#pragma warning(disable : 4200) // Cannot generate copy-ctor or copy-assignment operator when UDT contains a zero-sized array
namespace pGina
{
namespace CredProv
{
// Where to get text for a text field/label
typedef enum PGINA_FIELD_DATA_SOURCE
{
SOURCE_NONE, // Use the built in text
SOURCE_DYNAMIC, // Call the service
SOURCE_CALLBACK, // Call a function
SOURCE_STATUS, // Service status text
};
typedef std::wstring (*LABEL_TEXT_CALLBACK_FUNC)(LPWSTR fieldName, int fieldId);
// The first value indicates when the tile is displayed (selected, not selected)
// the second indicates things like whether the field is enabled, whether it has key focus, etc.
struct FIELD_STATE_PAIR
{
CREDENTIAL_PROVIDER_FIELD_STATE fieldState;
CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE fieldInteractiveState;
};
// Describes the field overall, both its state pair and its field descriptor
// as well as a union representing the fields current value
struct UI_FIELD
{
FIELD_STATE_PAIR fieldStatePair;
CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR fieldDescriptor;
PGINA_FIELD_DATA_SOURCE fieldDataSource;
union
{
PWSTR wstr;
};
LABEL_TEXT_CALLBACK_FUNC labelCallback;
};
struct UI_FIELDS
{
DWORD fieldCount;
DWORD submitAdjacentTo;
DWORD usernameFieldIdx;
DWORD passwordFieldIdx;
DWORD statusFieldIdx;
UI_FIELD fields[]; // Note: Warning 4200 - compiler cannot generate copy ctor, no doing UI_FIELDS x = UI_FIELDS y!
};
}
}
#pragma warning(pop)
<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <Windows.h>
#include <string>
#include <vector>
namespace pGina
{
namespace Registry
{
// TBD: we should get settings from the service via named pipe, just use these for backup?
std::wstring GetString(const wchar_t * keyName, const wchar_t * defaultValue);
DWORD GetDword(const wchar_t * keyName, DWORD defaultValue);
bool GetBool(const wchar_t * keyName, bool defaultValue);
bool StringValueExistsAndIsNonZero( HKEY base, const wchar_t *subKeyName, const wchar_t *valueName );
std::wstring GetString( HKEY base, const wchar_t *subKeyName, const wchar_t *valueName );
std::vector<std::wstring> GetStringArray( const wchar_t *subKeyName );
std::vector<std::wstring> GetStringArray( HKEY base, const wchar_t *subKeyName, const wchar_t *valueName );
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace encryptsetting
{
class Program
{
private static dynamic m_settings = null;
static int Main(string[] args)
{
if (args.Length < 2)
{
Console.ForegroundColor = ConsoleColor.Yellow;
string assemblyname = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
Console.WriteLine("{0} <setting> <encryptthis> [GUID]", assemblyname);
Console.ResetColor();
Console.WriteLine(" {0} SearchPW \"my p@asswor&\" 0f52390b-c781-43ae-bd62-553c77fa4cf7", assemblyname);
Console.WriteLine(" add setting SearchPW and assign \"my p@asswor&\" to pluging 0f523...f7", assemblyname);
Console.WriteLine(" {0} SearchPW \"my p@asswor&\"", assemblyname);
Console.WriteLine(" add setting SearchPW and assign \"my p@asswor&\" to pgina config", assemblyname);
return 3;
}
if (args.Length > 2 && !String.IsNullOrEmpty(args[2]))
{
try
{
Guid GUID = Guid.Parse(args[2]);
}
catch (Exception ex)
{
Console.WriteLine("can't parse GUID:{0}", ex.Message);
return 4;
}
}
try
{
if (args.Length > 2 && !String.IsNullOrEmpty(args[2]))
m_settings = new pGina.Shared.Settings.pGinaDynamicSettings(Guid.Parse(args[2]));
else
m_settings = new pGina.Shared.Settings.pGinaDynamicSettings();
m_settings.SetEncryptedSetting(args[0], args[1]);
Abstractions.Settings.DynamicSettings setting = m_settings;
if (!setting.GetEncryptedSetting(args[0]).Equals(args[1]))
{
return 1;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception:{0}", ex.Message);
return 2;
}
return 0;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace pGina.CredentialProvider.Registration
{
public class DllUtils
{
public enum MachineType : ushort
{
IMAGE_FILE_MACHINE_UNKNOWN = 0x0,
IMAGE_FILE_MACHINE_AM33 = 0x1d3,
IMAGE_FILE_MACHINE_AMD64 = 0x8664,
IMAGE_FILE_MACHINE_ARM = 0x1c0,
IMAGE_FILE_MACHINE_EBC = 0xebc,
IMAGE_FILE_MACHINE_I386 = 0x14c,
IMAGE_FILE_MACHINE_IA64 = 0x200,
IMAGE_FILE_MACHINE_M32R = 0x9041,
IMAGE_FILE_MACHINE_MIPS16 = 0x266,
IMAGE_FILE_MACHINE_MIPSFPU = 0x366,
IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466,
IMAGE_FILE_MACHINE_POWERPC = 0x1f0,
IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1,
IMAGE_FILE_MACHINE_R4000 = 0x166,
IMAGE_FILE_MACHINE_SH3 = 0x1a2,
IMAGE_FILE_MACHINE_SH3DSP = 0x1a3,
IMAGE_FILE_MACHINE_SH4 = 0x1a6,
IMAGE_FILE_MACHINE_SH5 = 0x1a8,
IMAGE_FILE_MACHINE_THUMB = 0x1c2,
IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169,
}
public static bool Is64BitDll(string fullPath)
{
switch (GetDllMachineType(fullPath))
{
case MachineType.IMAGE_FILE_MACHINE_AMD64:
case MachineType.IMAGE_FILE_MACHINE_IA64:
return true;
}
return false;
}
private static MachineType GetDllMachineType(string fullPath)
{
FileStream fs = null;
BinaryReader br = null;
try
{
fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
fs.Seek(0x3c, SeekOrigin.Begin);
Int32 peOffset = br.ReadInt32();
fs.Seek(peOffset, SeekOrigin.Begin);
UInt32 peHead = br.ReadUInt32();
if (peHead != 0x00004550) // "PE00" little-endian
{
throw new Exception("Unable to find PE header in " + fullPath);
}
MachineType type = (MachineType)br.ReadUInt16();
return type;
}
finally
{
if (br != null) br.Close();
if (fs != null) fs.Close();
}
}
public static FileInfo Find64BitDll(string path, string baseName)
{
if (! baseName.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase))
baseName += ".dll";
// Check path directory
string fullPath = Path.Combine(path, baseName);
if (File.Exists(fullPath))
{
if (DllUtils.Is64BitDll(fullPath))
return new FileInfo(fullPath);
}
// Check x64 subdirectory
fullPath = Path.Combine(path, "x64", baseName);
if (File.Exists(fullPath))
{
if (DllUtils.Is64BitDll(fullPath))
return new FileInfo(fullPath);
}
return null;
}
public static FileInfo Find32BitDll(string path, string baseName)
{
if (!baseName.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase))
baseName += ".dll";
// Check path directory
string fullPath = Path.Combine(path, baseName);
if (File.Exists(fullPath))
{
if (!DllUtils.Is64BitDll(fullPath))
return new FileInfo(fullPath);
}
// Check Win32 subdirectory
fullPath = Path.Combine(path, "Win32", baseName);
if (File.Exists(fullPath))
{
if (!DllUtils.Is64BitDll(fullPath))
return new FileInfo(fullPath);
}
return null;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace pGina.Plugin.RADIUS
{
class Session
{
public string username { get; set; }
public Guid id { get; set; } //guid.toString()
public int? windowsSessionId { get; set; } //Windows session id
public bool active { get; set; }
public RADIUSClient client { get; set; }
//public DateTime loginTimestamp { get; set; }
public Packet.Acct_Terminate_Cause? terminate_cause { get; set; }
private int interim_update = 0;
private Timer interim_update_timer = null;
private int session_limit = 0;
private Timer session_limit_timer = null;
private DateTime session_terminate = DateTime.MaxValue;
private Timer session_terminate_timer = null;
public Session(Guid Id, string username, RADIUSClient client) //string username,
{
this.id = Id;
this.username = username;
this.client = client;
active = true;
}
public void SetInterimUpdate(int frequency, TimerCallback tcb){
this.interim_update = frequency;
this.interim_update_timer = new Timer(tcb, this, frequency * 1000, frequency * 1000);
}
public void SetSessionTimeout(int timeout, TimerCallback tcb)
{
this.session_limit = timeout;
//Create timer, signals logoff every 30 seconds after timeout is reached
this.session_limit_timer = new Timer(tcb, this, timeout*1000, 30000);
}
public void Set_Session_Terminate(DateTime time, TimerCallback tcb)
{
this.session_terminate = time;
int ms = (int)(time - DateTime.Now).TotalSeconds;
this.session_terminate_timer = new Timer(tcb, this, ms * 1000, 30000);
//Create timer
}
public void disableCallbacks()
{
if (interim_update_timer != null)
{
interim_update_timer.Change(Timeout.Infinite, Timeout.Infinite);
interim_update_timer.Dispose();
}
if (session_limit_timer != null)
{
session_limit_timer.Change(Timeout.Infinite, Timeout.Infinite);
session_limit_timer.Dispose();
}
if (session_terminate_timer != null)
{
session_terminate_timer.Change(Timeout.Infinite, Timeout.Infinite);
session_terminate_timer.Dispose();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using pGina.Shared.Settings;
namespace pGina.Plugin.RADIUS
{
public partial class Configuration : Form
{
dynamic m_settings = new pGinaDynamicSettings(RADIUSPlugin.SimpleUuid);
public Configuration()
{
InitializeComponent();
secretTB.UseSystemPasswordChar = true;
sendNasIdentifierCB.CheckedChanged += checkboxModifyInputs;
sendCalledStationCB.CheckedChanged += checkboxModifyInputs;
enableAuthCB.CheckedChanged += checkboxModifyInputs;
enableAcctCB.CheckedChanged += checkboxModifyInputs;
sendInterimUpdatesCB.CheckedChanged += checkboxModifyInputs;
load();
}
private bool save()
{
int authport = 0;
int acctport = 0;
int timeout = 0;
int retry = 0;
int interim_time = 0;
try
{
authport = Convert.ToInt32(authPortTB.Text.Trim());
acctport = Convert.ToInt32(acctPortTB.Text.Trim());
timeout = (int)(1000 * Convert.ToDouble(timeoutTB.Text.Trim()));
retry = Convert.ToInt32(retryTB.Text.Trim());
interim_time = Convert.ToInt32(forceInterimUpdTB.Text.Trim());
if (authport <= 0 || acctport <= 0 || timeout <= 0 || retry <= 0 || interim_time <= 0)
throw new FormatException("Ports, Retry, Timeout and interval values must be values greater than 0");
}
catch (FormatException)
{
MessageBox.Show("Port and Timeout values must be numbers greater than 0.");
return false;
}
if (enableAuthCB.Checked) //Settings only relevent to users with auth checked
{
if (!sendNasIpAddrCB.Checked && !sendNasIdentifierCB.Checked)
{
MessageBox.Show("Send NAS IP Address or Send NAS Identifier must be checked under Authentication Options");
return false;
}
if (sendNasIdentifierCB.Checked && String.IsNullOrEmpty(sendNasIdentifierTB.Text.Trim()))
{
MessageBox.Show("NAS Identifier can not be blank if the option is enabled.");
return false;
}
if (sendCalledStationCB.Checked && String.IsNullOrEmpty(sendCalledStationTB.Text.Trim()))
{
MessageBox.Show("Called-Station-ID can not be blank if the option is enabled.");
return false;
}
}
Settings.Store.EnableAuth = enableAuthCB.Checked;
Settings.Store.EnableAcct = enableAcctCB.Checked;
Settings.Store.Server = serverTB.Text.Trim();
Settings.Store.AuthPort = authport;
Settings.Store.AcctPort = acctport;
Settings.Store.SetEncryptedSetting("SharedSecret", secretTB.Text);
Settings.Store.Timeout = timeout;
Settings.Store.Retry = retry;
Settings.Store.SendNASIPAddress = sendNasIpAddrCB.Checked;
Settings.Store.SendNASIdentifier = sendNasIdentifierCB.Checked;
Settings.Store.NASIdentifier = sendNasIdentifierTB.Text.Trim();
Settings.Store.SendCalledStationID = sendCalledStationCB.Checked;
Settings.Store.CalledStationID = sendCalledStationTB.Text.Trim();
Settings.Store.AcctingForAllUsers = acctingForAllUsersCB.Checked;
Settings.Store.SendInterimUpdates = sendInterimUpdatesCB.Checked;
Settings.Store.ForceInterimUpdates = forceInterimUpdCB.Checked;
Settings.Store.InterimUpdateTime = interim_time;
Settings.Store.AllowSessionTimeout = sessionTimeoutCB.Checked;
Settings.Store.WisprSessionTerminate = wisprTimeoutCB.Checked;
Settings.Store.UseModifiedName = useModifiedNameCB.Checked;
Settings.Store.IPSuggestion = ipAddrSuggestionTB.Text.Trim();
return true;
}
private void load()
{
enableAuthCB.Checked = (bool)Settings.Store.EnableAuth;
enableAcctCB.Checked = (bool)Settings.Store.EnableAcct;
serverTB.Text = Settings.Store.Server;
authPortTB.Text = String.Format("{0}", (int)Settings.Store.AuthPort);
acctPortTB.Text = String.Format("{0}", (int)Settings.Store.AcctPort);
secretTB.Text = Settings.Store.GetEncryptedSetting("SharedSecret") ;
timeoutTB.Text = String.Format("{0:0.00}", ((int)Settings.Store.Timeout) / 1000.0 ); //2500ms
retryTB.Text = String.Format("{0}", (int)Settings.Store.Retry);
sendNasIpAddrCB.Checked = (bool)Settings.Store.SendNASIPAddress;
sendNasIdentifierCB.Checked = (bool)Settings.Store.SendNASIdentifier;
sendNasIdentifierTB.Text = Settings.Store.NASIdentifier;
sendCalledStationCB.Checked = (bool)Settings.Store.SendCalledStationID;
sendCalledStationTB.Text = Settings.Store.CalledStationID;
acctingForAllUsersCB.Checked = (bool)Settings.Store.AcctingForAllUsers;
sendInterimUpdatesCB.Checked = (bool)Settings.Store.SendInterimUpdates;
forceInterimUpdCB.Checked = (bool)Settings.Store.ForceInterimUpdates;
forceInterimUpdTB.Text = String.Format("{0}", (int)Settings.Store.InterimUpdateTime);
sessionTimeoutCB.Checked = (bool)Settings.Store.AllowSessionTimeout;
wisprTimeoutCB.Checked = (bool)Settings.Store.WisprSessionTerminate;
ipAddrSuggestionTB.Text = Settings.Store.IPSuggestion;
useModifiedNameCB.Checked = (bool)Settings.Store.UseModifiedName;
}
private void checkboxModifyInputs(object sender, EventArgs e)
{
//Server Settings
authPortTB.Enabled = enableAuthCB.Checked;
acctPortTB.Enabled = enableAcctCB.Checked;
//Authentication options:
authGB.Enabled = enableAuthCB.Checked;
sendNasIdentifierTB.Enabled = sendNasIdentifierCB.Checked;
sendCalledStationTB.Enabled = sendCalledStationCB.Checked;
//Accounting options
acctGB.Enabled = enableAcctCB.Checked;
forceInterimUpdCB.Enabled = sendInterimUpdatesCB.Checked;
forceInterimUpdTB.Enabled = forceInterimUpdCB.Enabled;
forceInterimUpdLbl.Enabled = forceInterimUpdCB.Enabled;
}
private void btnOk_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
if(save())
this.Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
private void showSecretChanged(object sender, EventArgs e)
{
secretTB.UseSystemPasswordChar = !showSecretCB.Checked;
}
private void Configuration_Load(object sender, EventArgs e)
{
}
private void Btn_help(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/radius.html");
}
//Converts value to int, or returns default value.
/*private int stoi(Object o, int def = 0)
{
try{ return (int)o; }
catch (InvalidCastException) {
return def; }
}*/
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using pGina.Shared.Settings;
using log4net;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace pGina.Plugin.HttpAuth
{
class Settings
{
private static dynamic m_settings = new pGinaDynamicSettings(PluginImpl.PluginUuid);
private static ILog m_logger = LogManager.GetLogger("HttpAuthSettings");
private static string DEFAULT_URL = "https://pginaloginserver/login";
static Settings()
{
try
{
m_settings.SetDefault("Loginserver", @DEFAULT_URL);
}
catch (Exception)
{
// do nothing
}
}
public static dynamic Store
{
get { return m_settings; }
}
public static string resolveSettings()
{
string loginServer = _urlByEnvVar();
if (loginServer == null)
{
// try to get URL from DNS
try
{
List<string> entries = _getTxtRecords("pginaloginserver");
if (entries.Count > 0)
{
loginServer = entries[0].ToString(); // gets the first item
m_logger.DebugFormat("Login server from DNS: {0}", loginServer);
_persist(loginServer);
}
else
{
loginServer = m_settings.Loginserver;
m_logger.DebugFormat("Login server from GinaSettings: {0}", loginServer);
}
}
catch (KeyNotFoundException)
{
loginServer = DEFAULT_URL;
m_logger.DebugFormat("default Login server url: {0}", loginServer);
}
catch (Exception dnsex)
{
m_logger.ErrorFormat("Response: {0}", dnsex.ToString());
loginServer = m_settings.Loginserver;
m_logger.DebugFormat("Login server from GinaSettings: {0}", loginServer);
}
}
else
{
m_logger.DebugFormat("Login server from ENVVar: {0}", loginServer);
_persist(loginServer);
}
return loginServer;
}
private static void _persist(string url) {
try
{
m_settings.SetSetting("Loginserver", url);
}
catch (Exception e)
{
m_logger.ErrorFormat("Cannot save settings: {0}", e.ToString());
}
}
/*
* returns PGINALOGINSERVER environment variable content if set, otherwise null.
* Setting by environment variable allows easy override of login endpoint address.
*/
private static string _urlByEnvVar()
{
try
{
return Environment.GetEnvironmentVariable("PGINALOGINSERVER");
}
catch (Exception)
{
return null;
}
}
/*
* Uses http://www.robertsindall.co.uk/blog/getting-dns-txt-record-using-c-sharp/
* because c# and whole M$osft is crap and has no tools to resolve TXT recs!!!
*/
private static List<string> _getTxtRecords(string hostname)
{
List<string> txtRecords = new List<string>();
string output;
var startInfo = new ProcessStartInfo("nslookup");
startInfo.Arguments = string.Format("-type=TXT {0}", hostname);
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
using (var cmd = Process.Start(startInfo))
{
output = cmd.StandardOutput.ReadToEnd();
}
MatchCollection matches = Regex.Matches(output, "\"([^\"]*)\"", RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
if (match.Success)
txtRecords.Add(match.Groups[1].Value);
}
return txtRecords;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ImagexEX
{
class Program
{
static int Main(string[] args)
{
List<string> exclude = new List<string>();
List<string> dontCompress = new List<string>();
string Imagex_cli = "";
string sourcePath = "";
string ini = String.Format("{0}\\{1}.ini", Path.GetTempPath(), DateTime.Now.Ticks);
string error = "";
for (int args_loop = 0; args_loop < args.Length; args_loop++)
{
if (args[args_loop].StartsWith("-x", StringComparison.CurrentCultureIgnoreCase))
{
exclude.Add(Masquerade(args[args_loop].Remove(0, 2)));
}
else if (args[args_loop].StartsWith("-ms", StringComparison.CurrentCultureIgnoreCase))
{
string[] ms = args[args_loop].Remove(0, 3).Split(';');
foreach (string extension in ms)
{
dontCompress.Add(String.Format(@"*.{0}", extension));
}
}
else
{
if (args[args_loop].Equals("/CAPTURE", StringComparison.CurrentCultureIgnoreCase))
{
sourcePath = args[args_loop+1];
}
if (args[args_loop].Equals("/CONFIG", StringComparison.CurrentCultureIgnoreCase))
{
ini = args[args_loop + 1];
}
Imagex_cli += " " + args[args_loop];
}
}
/*
foreach (string excl in exclude)
{
Console.WriteLine("{0}\n\n", excl);
}
Console.WriteLine("{0}\n\n", Imagex_cli);
Console.WriteLine("{0}\n\n", sourcePath);
*/
if (Imagex_cli.ToUpper().Contains("/CAPTURE"))
{
try { File.Delete(ini); }
catch { }
using (StreamWriter sw = File.CreateText(ini))
{
sw.WriteLine("[ExclusionList]");
foreach (string e in Exclude(sourcePath, exclude))
{
Console.WriteLine("exclude:{0}", e);
sw.WriteLine(e);
}
sw.WriteLine("[CompressionExclusionList]");
foreach (string e in dontCompress)
{
//Console.WriteLine("dont compress:{0}", e);
sw.WriteLine(e);
}
}
}
Console.WriteLine("Run:imagex.exe {0}", Imagex_cli);
int ret = RunWait(AppDomain.CurrentDomain.BaseDirectory + "\\imagex.exe", Imagex_cli, out error);
if (ret != 0)
{
Console.WriteLine(error);
}
/*
if (Imagex_cli.ToUpper().Contains("/CAPTURE"))
{
try { File.Delete(ini); }
catch { }
}*/
return ret;
}
private static string Masquerade(string input)
{
input = input.Replace(@"\", @"\\");
input = input.Replace(".", @"\.");
input = input.Replace("*", ".*");
input = input.Replace("?", ".");
return input;
}
private static List<string> Exclude(string d, List<string> excl)
{
List<string> dirs = new List<string>() { d };
dirs.AddRange(GetDirectories(d, excl));
List<int> remove = new List<int>();
List<string> ret = new List<string>();
for (int dirs_loop = 0; dirs_loop < dirs.Count; dirs_loop++)
{
foreach (string exc in excl)
{
if (exc.EndsWith(@"\") && Regex.IsMatch(dirs[dirs_loop], exc, RegexOptions.IgnoreCase))
{
if (!ret.Any(r => r.StartsWith(dirs[dirs_loop], StringComparison.CurrentCultureIgnoreCase)))
{
ret.Add(dirs[dirs_loop].TrimEnd(new char[] { '\\' }));
}
remove.Add(dirs_loop);
break;
}
}
}
remove.Reverse();
foreach (int rem in remove)
{
dirs.RemoveAt(rem);
}
remove.Clear();
List<string> files = GetFiles(dirs);
for (int files_loop = 0; files_loop < files.Count; files_loop++)
{
foreach (string exc in excl)
{
string regex = exc.Replace(@"\\", "/");
string file = files[files_loop].Replace(@"\", "/");
//Console.WriteLine("{0} {1}", regex, file);
if (!exc.EndsWith(@"/") && Regex.IsMatch(file, regex, RegexOptions.IgnoreCase))
{
string s = Regex.Match(regex, @"[^/]*$", RegexOptions.IgnoreCase).Value;
string f = Regex.Match(file, @"[^/]*$", RegexOptions.IgnoreCase).Value;
//Console.WriteLine("{0} {1} {2} {3}", regex, file, s, f);
if (Regex.IsMatch(f, s, RegexOptions.IgnoreCase))
{
ret.Add(files[files_loop]);
break;
}
}
}
}
return ret;
}
private static List<string> GetFiles(List<string> dirs)
{
List<string> ret = new List<string>();
try
{
foreach (string dir in dirs)
{
string[] files = Directory.GetFiles(dir, "*", System.IO.SearchOption.TopDirectoryOnly);
ret.AddRange(files.ToList());
}
}
catch (Exception ex)
{
Console.WriteLine("GetFiles() error:", ex.Message);
}
return ret;
}
private static List<string> GetDirectories(string d, List<string> exclude)
{
List<string> ret = new List<string>();
try
{
string[] dirs = Directory.GetDirectories(d, "*", System.IO.SearchOption.TopDirectoryOnly);
foreach (string dir in dirs)
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
if (!dirInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
ret.Add(dir + @"\");
if (!exclude.Any(e => e.EndsWith(@"\") && Regex.IsMatch(dir + @"\", e, RegexOptions.IgnoreCase)))
{
ret.AddRange(GetDirectories(dir, exclude));
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("GetDirectories() error:", ex.Message);
}
return ret;
}
private static int RunWait(string application, string arguments, out string stdmerge)
{
stdmerge = "";
string stdout = "";
string stderr = "";
int ret = -1;
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = application;
startInfo.Arguments = arguments;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
try
{
using (Process p = Process.Start(startInfo))
{
using (StreamReader streamReader = p.StandardOutput)
{
stdout = streamReader.ReadToEnd();
}
using (StreamReader streamReader = p.StandardError)
{
stderr = streamReader.ReadToEnd();
}
p.WaitForExit();
ret = p.ExitCode;
}
}
catch (Exception ex)
{
Console.WriteLine("RunWait failed error:{0}", ex.Message);
return -1;
}
stdmerge += String.Format("{0}\r\n{1}", stdout.TrimEnd(), stderr.TrimEnd()).TrimEnd();
return ret;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace Abstractions.Helpers
{
public class TimedCache<KeyType, ValueType> : ObjectCache<KeyType, ValueType>
{
protected class TimedCacheEntry : CacheEntry
{
public TimeSpan InsertionTime;
}
private TimeSpan m_entryTtl;
private Timer m_timer = null;
private Stopwatch m_stopwatch = new Stopwatch();
public TimedCache() : this(TimeSpan.FromMinutes(5))
{
}
public TimedCache(TimeSpan ttl) : base()
{
m_entryTtl = ttl;
InitTimer();
}
protected override CacheEntry WrapValue(KeyType key, ValueType value)
{
return (CacheEntry)(new TimedCacheEntry()
{
Key = key,
Value = value,
InsertionTime = m_stopwatch.Elapsed
});
}
public override ValueType Get(KeyType key)
{
return Get(key, false);
}
public ValueType Get(KeyType key, bool refreshTimer)
{
lock (m_cache)
{
if (refreshTimer)
{
TimedCacheEntry ce = m_cache[key] as TimedCacheEntry;
ce.InsertionTime = m_stopwatch.Elapsed;
return ce.Value;
}
return m_cache[key].Value;
}
}
private void InitTimer()
{
m_stopwatch.Start();
m_timer = new Timer(new TimerCallback(ExpireTime), null, m_entryTtl, TimeSpan.FromMilliseconds(-1));
}
private void ExpireTime(object timer)
{
lock (m_cache)
{
List<KeyType> expirations = new List<KeyType>();
foreach (KeyValuePair<KeyType, CacheEntry> kv in m_cache)
{
TimedCacheEntry ce = kv.Value as TimedCacheEntry;
if (m_stopwatch.Elapsed - ce.InsertionTime > m_entryTtl)
{
expirations.Add(kv.Key);
}
}
foreach (KeyType key in expirations)
{
CacheEntry ce = m_cache[key];
if (ce.Value is IDisposable)
{
IDisposable disposableValue = (IDisposable)ce.Value;
disposableValue.Dispose();
}
m_cache.Remove(key);
}
}
m_timer.Change(m_entryTtl, TimeSpan.FromMilliseconds(-1));
}
private void ExpireAll()
{
lock (m_cache)
{
List<KeyType> expirations = new List<KeyType>();
foreach (KeyValuePair<KeyType, CacheEntry> kv in m_cache)
{
CacheEntry ce = kv.Value;
if (ce.Value is IDisposable)
{
IDisposable disposableValue = (IDisposable)ce.Value;
disposableValue.Dispose();
}
}
m_cache.Clear();
}
m_timer.Change(m_entryTtl, TimeSpan.FromMilliseconds(-1));
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
ExpireAll();
}
base.Dispose(disposing);
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pGina.Shared.Types
{
public class PluginActivityInformation
{
private Dictionary<Guid, BooleanResult> m_authentication = new Dictionary<Guid, BooleanResult>();
private Dictionary<Guid, BooleanResult> m_authorization = new Dictionary<Guid, BooleanResult>();
private Dictionary<Guid, BooleanResult> m_gateway = new Dictionary<Guid, BooleanResult>();
private Dictionary<Guid, BooleanResult> m_notification = new Dictionary<Guid, BooleanResult>();
public List<Interfaces.IPluginAuthentication> LoadedAuthenticationPlugins { get; set; }
public List<Interfaces.IPluginAuthenticationGateway> LoadedAuthenticationGatewayPlugins { get; set; }
public List<Interfaces.IPluginAuthorization> LoadedAuthorizationPlugins { get; set; }
public List<Interfaces.IPluginEventNotifications> LoadedNotificationPlugins { get; set; }
public void AddAuthenticateResult(Guid pluginId, BooleanResult result)
{
lock (m_authentication)
{
if (m_authentication.ContainsKey(pluginId))
m_authentication[pluginId] = result;
else
m_authentication.Add(pluginId, result);
}
}
public void AddAuthorizationResult(Guid pluginId, BooleanResult result)
{
lock (m_authorization)
{
if (m_authorization.ContainsKey(pluginId))
m_authorization[pluginId] = result;
else
m_authorization.Add(pluginId, result);
}
}
public void AddGatewayResult(Guid pluginId, BooleanResult result)
{
lock (m_gateway)
{
if (m_gateway.ContainsKey(pluginId))
m_gateway[pluginId] = result;
else
m_gateway.Add(pluginId, result);
}
}
public void AddNotificationResult(Guid pluginId, BooleanResult result)
{
lock (m_notification)
{
if (m_notification.ContainsKey(pluginId))
m_notification[pluginId] = result;
else
m_notification.Add(pluginId, result);
}
}
public BooleanResult GetAuthenticationResult(Guid pluginGuid)
{
lock (m_authentication)
{
return m_authentication[pluginGuid];
}
}
public BooleanResult GetAuthorizationResult(Guid pluginGuid)
{
lock (m_authorization)
{
return m_authorization[pluginGuid];
}
}
public BooleanResult GetGatewayResult(Guid pluginGuid)
{
lock (m_authentication)
{
return m_gateway[pluginGuid];
}
}
public BooleanResult GetNotificationResult(Guid pluginGuid)
{
lock (m_notification)
{
return m_notification[pluginGuid];
}
}
public IEnumerable<Guid> GetAuthenticationPlugins()
{
lock (m_authentication)
{
foreach (KeyValuePair<Guid, BooleanResult> kv in m_authentication)
{
yield return kv.Key;
}
}
}
public IEnumerable<Guid> GetAuthorizationPlugins()
{
lock (m_authorization)
{
foreach (KeyValuePair<Guid, BooleanResult> kv in m_authorization)
{
yield return kv.Key;
}
}
}
public IEnumerable<Guid> GetGatewayPlugins()
{
lock (m_gateway)
{
foreach (KeyValuePair<Guid, BooleanResult> kv in m_gateway)
{
yield return kv.Key;
}
}
}
public IEnumerable<Guid> GetNotificationPlugins()
{
lock (m_notification)
{
foreach (KeyValuePair<Guid, BooleanResult> kv in m_notification)
{
yield return kv.Key;
}
}
}
public void DelAuthenticateResult(Guid pluginId)
{
lock (m_authentication)
{
if (m_authentication.ContainsKey(pluginId))
m_authentication.Remove(pluginId);
}
}
public void DelAuthorizationResult(Guid pluginId)
{
lock (m_authorization)
{
if (m_authorization.ContainsKey(pluginId))
m_authorization.Remove(pluginId);
}
}
public void DelGatewayResult(Guid pluginId)
{
lock (m_gateway)
{
if (m_gateway.ContainsKey(pluginId))
m_gateway.Remove(pluginId);
}
}
public void DelNotificationResult(Guid pluginId)
{
lock (m_notification)
{
if (m_notification.ContainsKey(pluginId))
m_notification.Remove(pluginId);
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using pGina.Shared.Interfaces;
using pGina.Shared.Types;
namespace pGina.Core
{
public class PluginDriver
{
private Guid m_sessionId = Guid.NewGuid();
private bool m_credui = false;
private SessionProperties m_properties = null;
private ILog m_logger = null;
public Guid SessionId
{
get { return m_sessionId; }
set
{
m_sessionId = value;
m_properties.Id = value;
m_properties.AddTrackedObject("SessionId", new Guid(m_sessionId.ToString()));
}
}
public bool CREDUI
{
get { return m_credui; }
set
{
m_credui = value;
m_properties.CREDUI = value;
m_properties.AddTrackedObject("CREDUI", m_credui.ToString());
}
}
public PluginDriver()
{
m_logger = LogManager.GetLogger(string.Format("PluginDriver:{0}", m_sessionId));
m_properties = new SessionProperties(m_sessionId);
// Add the user information object we'll be using for this session
UserInformation userInfo = new UserInformation();
m_properties.AddTrackedSingle<UserInformation>(userInfo);
// Add the plugin tracking object we'll be using for this session
PluginActivityInformation pluginInfo = new PluginActivityInformation();
pluginInfo.LoadedAuthenticationGatewayPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthenticationGateway>();
pluginInfo.LoadedAuthenticationPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthentication>();
pluginInfo.LoadedAuthorizationPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthorization>();
m_properties.AddTrackedSingle<PluginActivityInformation>(pluginInfo);
m_logger.DebugFormat("New PluginDriver created");
}
public UserInformation UserInformation
{
get { return m_properties.GetTrackedSingle<UserInformation>(); }
}
public List<GroupInformation> GroupInformation
{
get { return m_properties.GetTrackedSingle<UserInformation>().Groups; }
}
public SessionProperties SessionProperties
{
get { return m_properties; }
}
public static void Starting()
{
foreach (IPluginBase plugin in PluginLoader.AllPlugins)
plugin.Starting();
}
public static void Stopping()
{
foreach (IPluginBase plugin in PluginLoader.AllPlugins)
plugin.Stopping();
}
public BooleanResult PerformLoginProcess()
{
try
{
// Set the original username to the current username if not already set
UserInformation userInfo = m_properties.GetTrackedSingle<UserInformation>();
if (string.IsNullOrEmpty(userInfo.OriginalUsername))
{
userInfo.OriginalUsername = userInfo.Username;
userInfo.OriginalPassword = <PASSWORD>;
}
// Execute login
BeginChain();
BooleanResult result = ExecuteLoginChain();
EndChain();
return result;
}
catch (Exception e)
{
// We catch exceptions at a high level here and report failure in these cases,
// with the exception details as our message for now
m_logger.ErrorFormat("Exception during login process: {0}", e);
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), "", "", String.Format("pGina: PerformLoginProcess Exception {0}", Environment.MachineName), e.ToString());
return new BooleanResult() { Success = false, Message = string.Format("Unhandled exception during login: {0}", e) };
}
}
private BooleanResult ExecuteLoginChain()
{
m_logger.DebugFormat("Performing login process");
BooleanResult result = AuthenticateUser();
if (!result.Success)
return result;
result = AuthorizeUser();
if (!result.Success)
return result;
result = GatewayProcess();
return result;
}
public void BeginChain()
{
List<IStatefulPlugin> plugins = PluginLoader.GetEnabledStatefulPlugins();
m_logger.DebugFormat("Begin login chain, {0} stateful plugin(s).", plugins.Count);
foreach (IStatefulPlugin plugin in plugins)
{
plugin.BeginChain(m_properties);
}
}
public void EndChain()
{
List<IStatefulPlugin> plugins = PluginLoader.GetEnabledStatefulPlugins();
m_logger.DebugFormat("End login chain, {0} stateful plugin(s).", plugins.Count);
foreach (IStatefulPlugin plugin in plugins)
{
plugin.EndChain(m_properties);
}
}
public BooleanResult AuthenticateUser()
{
PluginActivityInformation pluginInfo = m_properties.GetTrackedSingle<PluginActivityInformation>();
List<IPluginAuthentication> plugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthentication>();
m_logger.DebugFormat("Authenticating user {0}, {1} plugins available", m_properties.GetTrackedSingle<UserInformation>().Username, plugins.Count);
// At least one must succeed
BooleanResult finalResult = new BooleanResult() { Message = "No plugin is set for Authentication", Success = false };
foreach (IPluginAuthentication plugin in plugins)
{
m_logger.DebugFormat("Calling {0}", plugin.Uuid);
BooleanResult pluginResult = new BooleanResult() { Message = null, Success = false };
try
{
pluginResult = plugin.AuthenticateUser(m_properties);
pluginInfo.AddAuthenticateResult(plugin.Uuid, pluginResult);
if (pluginResult.Success)
{
m_logger.DebugFormat("{0} Succeeded", plugin.Uuid);
finalResult.Success = true;
}
else
{
if (!string.IsNullOrEmpty(pluginResult.Message))
{
m_logger.WarnFormat("{0} Failed with Message: {1}", plugin.Uuid, pluginResult.Message);
finalResult.Message = pluginResult.Message;
}
else
{
m_logger.WarnFormat("{0} Failed without a message", plugin.Uuid);
finalResult.Message = String.Format("Failed to authenticate user: {0}", m_properties.GetTrackedSingle<UserInformation>().Username);
}
}
}
catch (Exception e)
{
m_logger.ErrorFormat("{0} Threw an unexpected exception, assuming failure: {1}", plugin.Uuid, e);
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), "", "", String.Format("pGina: Authenticate plugin Exception {0}", Environment.MachineName), e.ToString());
finalResult = new BooleanResult() { Message = e.Message, Success = false };
}
}
if (finalResult.Success)
{
// Clear any errors from plugins if we did succeed
finalResult.Message = null;
m_logger.InfoFormat("Successfully authenticated {0}", m_properties.GetTrackedSingle<UserInformation>().Username);
}
else
{
m_logger.ErrorFormat("Failed to authenticate {0}, Message: {1}", m_properties.GetTrackedSingle<UserInformation>().Username, finalResult.Message);
}
return finalResult;
}
public BooleanResult AuthorizeUser()
{
PluginActivityInformation pluginInfo = m_properties.GetTrackedSingle<PluginActivityInformation>();
List<IPluginAuthorization> plugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthorization>();
m_logger.DebugFormat("Authorizing user {0}, {1} plugins available", m_properties.GetTrackedSingle<UserInformation>().Username, plugins.Count);
// At least one must succeed
BooleanResult finalResult = new BooleanResult() { Message = null, Success = true };
foreach (IPluginAuthorization plugin in plugins)
{
m_logger.DebugFormat("Calling {0}", plugin.Uuid);
BooleanResult pluginResult = new BooleanResult() { Message = null, Success = false };
try
{
pluginResult = plugin.AuthorizeUser(m_properties);
pluginInfo.AddAuthorizationResult(plugin.Uuid, pluginResult);
if (pluginResult.Success)
{
m_logger.DebugFormat("{0} Succeeded", plugin.Uuid);
finalResult.Success = true;
}
else
{
finalResult.Success = false;
if (!string.IsNullOrEmpty(pluginResult.Message))
{
m_logger.WarnFormat("{0} Failed with Message: {1}", plugin.Uuid, pluginResult.Message);
finalResult.Message = pluginResult.Message;
}
else
{
m_logger.WarnFormat("{0} Failed without a message", plugin.Uuid);
}
break;
}
}
catch (Exception e)
{
m_logger.ErrorFormat("{0} Threw an unexpected exception, treating this as failure: {1}", plugin.Uuid, e);
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), "", "", String.Format("pGina: Authorize plugin Exception {0}", Environment.MachineName), e.ToString());
return new BooleanResult() { Message = e.Message, Success = false };
}
}
if (finalResult.Success)
{
// Clear any errors from plugins if we did succeed
finalResult.Message = null;
m_logger.InfoFormat("Successfully authorized {0}", m_properties.GetTrackedSingle<UserInformation>().Username);
}
else
{
m_logger.ErrorFormat("Failed to authorized {0}, Message: {1}", m_properties.GetTrackedSingle<UserInformation>().Username, finalResult.Message);
}
return finalResult;
}
public BooleanResult GatewayProcess()
{
PluginActivityInformation pluginInfo = m_properties.GetTrackedSingle<PluginActivityInformation>();
List<IPluginAuthenticationGateway> plugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthenticationGateway>();
m_logger.DebugFormat("Processing gateways for user {0}, {1} plugins available", m_properties.GetTrackedSingle<UserInformation>().Username, plugins.Count);
foreach (IPluginAuthenticationGateway plugin in plugins)
{
m_logger.DebugFormat("Calling {0}", plugin.Uuid);
BooleanResult pluginResult = new BooleanResult() { Message = null, Success = false };
try
{
pluginResult = plugin.AuthenticatedUserGateway(m_properties);
pluginInfo.AddGatewayResult(plugin.Uuid, pluginResult);
// All must succeed, fail = total fail
if (!pluginResult.Success)
{
m_logger.ErrorFormat("{0} Failed to process gateway for {1} message: {2}", plugin.Uuid, m_properties.GetTrackedSingle<UserInformation>().Username, pluginResult.Message);
return pluginResult;
}
}
catch (Exception e)
{
m_logger.ErrorFormat("{0} Threw an unexpected exception, treating this as failure: {1}", plugin.Uuid, e);
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), "", "", String.Format("pGina: Gateway plugin Exception {0}", Environment.MachineName), e.ToString());
return new BooleanResult() { Message = e.Message, Success = false };
}
}
m_logger.InfoFormat("Successfully processed gateways for {0}", m_properties.GetTrackedSingle<UserInformation>().Username);
return new BooleanResult() { Success = true };
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Security.Principal;
using log4net;
using pGina.Shared.Interfaces;
using pGina.Shared.Types;
using Abstractions.WindowsApi;
using Abstractions.Windows;
namespace pGina.Plugin.pgSMB2
{
public class PluginImpl : IPluginAuthenticationGateway, IPluginConfiguration, IPluginEventNotifications, IPluginLogoffRequestAddTime
{
private ILog m_logger = LogManager.GetLogger("pgSMB2");
private Dictionary<string, Boolean> RunningTasks = new Dictionary<string, Boolean>();
private ReaderWriterLockSlim Locker = new ReaderWriterLockSlim();
public static Boolean IsShuttingDown = false;
#region Init-plugin
public static Guid PluginUuid
{
get { return new Guid("{10C41590-07F9-4FF2-B77B-E51E7A51206F}"); }
}
public PluginImpl()
{
using (Process me = Process.GetCurrentProcess())
{
m_logger.DebugFormat("Plugin initialized on {0} in PID: {1} Session: {2}", Environment.MachineName, me.Id, me.SessionId);
}
}
public string Name
{
get { return "pgSMB2"; }
}
public string Description
{
get { return "a \"clone\" of the pGina 1.x pgFtp plugin"; }
}
public Guid Uuid
{
get { return PluginUuid; }
}
public string Version
{
get
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
#endregion
public void Starting() { }
public void Stopping() { }
public Boolean LogoffRequestAddTime()
{
IsShuttingDown = true;
try
{
Locker.TryEnterReadLock(-1);
if (RunningTasks.Values.Contains(true))
{
return true;
}
}
catch (Exception ex)
{
m_logger.InfoFormat("LogoffRequestAddTime() error {0}", ex.Message);
}
finally
{
Locker.ExitReadLock();
}
return false;
}
public Boolean LoginUserRequest(string username)
{
try
{
Locker.TryEnterReadLock(-1);
if (RunningTasks.Keys.Contains(username.ToLower()))
{
m_logger.InfoFormat("LoginUserRequest() logoff in process for {0}", username);
return true;
}
else
{
m_logger.InfoFormat("LoginUserRequest() {0} free to login", username);
return false;
}
}
catch (Exception ex)
{
m_logger.InfoFormat("LoginUserRequest() {0} error {1}", username, ex.Message);
}
finally
{
Locker.ExitReadLock();
}
return false;
}
private Dictionary<string, string> GetSettings(string username, UserInformation userInfo)
{
Dictionary<string,string> settings = new Dictionary<string,string>();
Abstractions.WindowsApi.pInvokes.structenums.OSVERSIONINFOW verinfo = Abstractions.WindowsApi.pInvokes.VersionsInfo();
if (verinfo.dwMajorVersion == 0)
{
m_logger.WarnFormat("GetSettings: VersionsInfo() failed. I'm unable to detect OS beyond Windows 8.0");
verinfo.dwBuildNumber = Environment.OSVersion.Version.Build;
verinfo.dwMajorVersion = Environment.OSVersion.Version.Major;
verinfo.dwMinorVersion = Environment.OSVersion.Version.Minor;
verinfo.dwPlatformId = Environment.OSVersion.Version.Build;
}
Dictionary<string,string> global_settings = pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "" });
string[,] array = new string[,]
{
{"TempComp", Settings.Store.TempComp.ToString()},
{"Filename", (!String.IsNullOrEmpty(userInfo.pgSMB_Filename)) ? userInfo.pgSMB_Filename : Settings.Store.Filename.ToString()},
{"SMBshare", (!String.IsNullOrEmpty(userInfo.pgSMB_SMBshare)) ? userInfo.pgSMB_SMBshare : Settings.Store.SMBshare.ToString()},
{"RoamingSource", (!String.IsNullOrEmpty(userInfo.usri4_profile)) ? userInfo.usri4_profile : Settings.Store.RoamingSource.ToString()},
{"ConnectRetry", Settings.Store.ConnectRetry.ToString()},
{"Compressor", Settings.Store.Compressor.ToString()},
{"UncompressCLI", Settings.Store.UncompressCLI.ToString()},
{"CompressCLI", Settings.Store.CompressCLI.ToString()},
{"MaxStore", (userInfo.usri4_max_storage > 0) ? userInfo.usri4_max_storage.ToString() : Settings.Store.MaxStore.ToString()},
{"ntp", (global_settings.ContainsKey("ntpservers")? global_settings["ntpservers"].Replace('\0',' ') : "")},
/*maybe emty*/
{"MaxStoreExclude", Settings.StoreGlobal.MaxStoreExclude.ToString()},
{"HomeDir", (!String.IsNullOrEmpty(userInfo.usri4_home_dir)) ? userInfo.usri4_home_dir : Settings.Store.HomeDir.ToString()},
{"HomeDirDrive", (!String.IsNullOrEmpty(userInfo.usri4_home_dir_drive)) ? userInfo.usri4_home_dir_drive : Settings.Store.HomeDirDrive.ToString()},
{"ScriptPath", (!String.IsNullOrEmpty(userInfo.LoginScript)) ? userInfo.LoginScript : Settings.Store.ScriptPath.ToString()},
};
for (uint x = 0; x <= array.GetUpperBound(0); x++ )
{
array[x, 1] = Environment.ExpandEnvironmentVariables(array[x, 1]).Replace("%u", username);
if (x > 2)
{
// mask the filename in the string to prevent a replacement
array[x, 1] = array[x, 1].Replace(array[2, 1],"??????????");
// replace the roaming folder (NT6 adds .V2)
array[x, 1] = array[x, 1].Replace(array[0, 1], array[1, 1]);
// unmask the filename
array[x, 1] = array[x, 1].Replace("??????????", array[2, 1]);
}
if (x < 11) // first 11 fields shouldnt be empty
{
if (String.IsNullOrEmpty(array[x, 1]))
{
settings.Add("ERROR", array[x, 0]);
}
}
settings.Add(array[x, 0], array[x, 1]);
}
List<string> keys = new List<string>(settings.Keys);
for (uint y = 1; y <= 4; y++)
{
foreach (string key in keys)
{
settings[key] = settings[key].Replace("%f", settings["Filename"]);
settings[key] = settings[key].Replace("%s", settings["SMBshare"]);
settings[key] = settings[key].Replace("%r", settings["RoamingSource"]);
settings[key] = settings[key].Replace("%d", settings["TempComp"]);
}
}
foreach (KeyValuePair<string, string> pair in settings)
{
m_logger.DebugFormat("GetSettings:\"{0}\" \"{1}\"",pair.Key,pair.Value);
}
return settings;
}
public BooleanResult AuthenticatedUserGateway(SessionProperties properties)
{
// get user info
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
BooleanResult RetBool = new BooleanResult();
// get the plugin settings
Dictionary<string,string> settings = GetSettings(userInfo.Username, userInfo);
if (settings.ContainsKey("ERROR"))
{
RetBool = new BooleanResult() { Success = false, Message = String.Format("Can't parse plugin settings ", settings["ERROR"]) };
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), userInfo.Username, userInfo.Password, String.Format("pGina: unable to Login {0} from {1}", userInfo.Username, Environment.MachineName), RetBool.Message);
return RetBool;
}
Roaming ro = new Roaming();
RetBool = ro.get(settings, userInfo.Username, userInfo.Password);
if (!RetBool.Success)
{
//Roaming.email(settings["email"], settings["smtp"], userInfo.Username, userInfo.Password, String.Format("pGina: unable to Login {0} from {1}", userInfo.Username, Environment.MachineName), RetBool.Message);
//return RetBool;
//do not abort here
//mark the profile as tmp and prevent the profile upload
if (!ro.userAdd(settings, userInfo.Username, userInfo.Password, "pGina created pgSMB2 tmp"))
{
ro.userDel(settings, userInfo.Username, userInfo.Password);
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), userInfo.Username, userInfo.Password, String.Format("pGina: tmp Login failed {0} from {1}", userInfo.Username, Environment.MachineName), "tmp login failed");
return RetBool;
}
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), userInfo.Username, userInfo.Password, String.Format("pGina: tmp Login {0} from {1}", userInfo.Username, Environment.MachineName), "failed to get the profile\nmarking as tmp");
}
pInvokes.structenums.USER_INFO_4 userinfo4 = new pInvokes.structenums.USER_INFO_4();
if (pInvokes.UserGet(userInfo.Username, ref userinfo4))
{
if (RetBool.Success)
{
userInfo.SID = new SecurityIdentifier(userinfo4.user_sid);
}
userInfo.Description = userinfo4.comment;
}
else // we should never go there
{
if (RetBool.Success)
{
userInfo.Description = "pGina created pgSMB2";
}
else
{
userInfo.Description = "pGina created pgSMB2 tmp";
}
}
properties.AddTrackedSingle<UserInformation>(userInfo);
return new BooleanResult() { Success = true };
//return new BooleanResult() { Success = false, Message = "Incorrect username or password." };
}
public void Configure()
{
Configuration dialog = new Configuration();
dialog.ShowDialog();
}
public void SessionChange(int SessionId, System.ServiceProcess.SessionChangeReason Reason, SessionProperties properties)
{
if (properties == null)
{
return;
}
if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogoff)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
m_logger.DebugFormat("{1} SessionChange SessionLogoff for ID:{0}", SessionId, userInfo.Username);
m_logger.InfoFormat("{3} {0} {1} {2}", userInfo.Description.Contains("pGina created pgSMB2"), userInfo.HasSID, properties.CREDUI, userInfo.Username);
if (userInfo.Description.Contains("pGina created pgSMB2") && userInfo.HasSID && !properties.CREDUI)
{
try
{
Locker.TryEnterWriteLock(-1);
RunningTasks.Add(userInfo.Username.ToLower(), true);
}
finally
{
Locker.ExitWriteLock();
}
// add this plugin into PluginActivityInformation
m_logger.DebugFormat("{1} properties.id:{0}", properties.Id, userInfo.Username);
PluginActivityInformation notification = properties.GetTrackedSingle<PluginActivityInformation>();
foreach (Guid gui in notification.GetNotificationPlugins())
{
m_logger.DebugFormat("{1} PluginActivityInformation Guid:{0}", gui, userInfo.Username);
}
m_logger.DebugFormat("{1} PluginActivityInformation add guid:{0}", PluginUuid, userInfo.Username);
notification.AddNotificationResult(PluginUuid, new BooleanResult { Message = "", Success = false });
properties.AddTrackedSingle<PluginActivityInformation>(notification);
foreach (Guid gui in notification.GetNotificationPlugins())
{
m_logger.DebugFormat("{1} PluginActivityInformation Guid:{0}", gui, userInfo.Username);
}
Thread rem_smb = new Thread(() => cleanup(userInfo, SessionId, properties));
rem_smb.Start();
}
else
{
m_logger.InfoFormat("{0} {1}. I'm not executing Notification stage", userInfo.Username, (properties.CREDUI) ? "has a program running in his context" : "is'nt a pGina created pgSMB2 user");
}
}
if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogon)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
if (!userInfo.HasSID)
{
m_logger.InfoFormat("{1} SessionLogon Event denied for ID:{0}", SessionId, userInfo.Username);
return;
}
m_logger.DebugFormat("{1} SessionChange SessionLogon for ID:{0}", SessionId, userInfo.Username);
if (userInfo.Description.Contains("pGina created pgSMB2"))
{
Dictionary<string, string> settings = GetSettings(userInfo.Username, userInfo);
if (!String.IsNullOrEmpty(settings["ScriptPath"]))
{
if (!Abstractions.WindowsApi.pInvokes.StartUserProcessInSession(SessionId, settings["ScriptPath"]))
{
m_logger.ErrorFormat("Can't run application {0}", settings["ScriptPath"]);
Abstractions.WindowsApi.pInvokes.SendMessageToUser(SessionId, "Can't run application", String.Format("I'm unable to run your LoginScript\n{0}", settings["ScriptPath"]));
}
}
IntPtr hToken = Abstractions.WindowsApi.pInvokes.GetUserToken(userInfo.Username, null, userInfo.Password);
if (hToken != IntPtr.Zero)
{
string uprofile = Abstractions.WindowsApi.pInvokes.GetUserProfilePath(hToken);
if (String.IsNullOrEmpty(uprofile))
{
uprofile = Abstractions.WindowsApi.pInvokes.GetUserProfileDir(hToken);
}
Abstractions.WindowsApi.pInvokes.CloseHandle(hToken);
m_logger.InfoFormat("add LocalProfilePath:[{0}]", uprofile);
// the profile realy exists there, instead of assuming it will be created or changed during a login (temp profile[win error reading profile])
userInfo.LocalProfilePath = uprofile;
properties.AddTrackedSingle<UserInformation>(userInfo);
if ((uprofile.Contains(@"\TEMP") && !userInfo.Username.StartsWith("temp", StringComparison.CurrentCultureIgnoreCase)) || Abstractions.Windows.User.IsProfileTemp(userInfo.SID.ToString()) == true)
{
m_logger.InfoFormat("TEMP profile detected");
string userInfo_old_Description = userInfo.Description;
userInfo.Description = "pGina created pgSMB2 tmp";
properties.AddTrackedSingle<UserInformation>(userInfo);
pInvokes.structenums.USER_INFO_4 userinfo4 = new pInvokes.structenums.USER_INFO_4();
if (pInvokes.UserGet(userInfo.Username, ref userinfo4))
{
userinfo4.logon_hours = IntPtr.Zero;
userinfo4.comment = userInfo.Description;
if (!pInvokes.UserMod(userInfo.Username, userinfo4))
{
m_logger.ErrorFormat("Can't modify userinformation {0}", userInfo.Username);
}
}
else
{
m_logger.ErrorFormat("Can't get userinformation {0}", userInfo.Username);
}
if (userInfo_old_Description.EndsWith("pGina created pgSMB2"))
{
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), userInfo.Username, userInfo.Password, String.Format("pGina: Windows tmp Login {0} from {1}", userInfo.Username, Environment.MachineName), "Windows was unable to load the profile");
}
}
}
if (userInfo.Description.EndsWith("pGina created pgSMB2"))
{
try
{
if (!EventLog.SourceExists("proquota"))
EventLog.CreateEventSource("proquota", "Application");
}
catch
{
EventLog.CreateEventSource("proquota", "Application");
}
Abstractions.Windows.User.SetQuota(pInvokes.structenums.RegistryLocation.HKEY_USERS, userInfo.SID.ToString(), 0);
string proquotaPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "proquota.exe");
try
{
using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows Defender\Exclusions\Processes", true))
{
if (key != null)
{
bool proquota_exclude_found = false;
foreach (string ValueName in key.GetValueNames())
{
if (ValueName.Equals(proquotaPath, StringComparison.CurrentCultureIgnoreCase))
{
proquota_exclude_found = true;
}
}
if (!proquota_exclude_found)
{
key.SetValue(proquotaPath, 0, Microsoft.Win32.RegistryValueKind.DWord);
}
}
}
}
catch { }
m_logger.InfoFormat("start session:{0} prog:{1}", SessionId, proquotaPath);
if (!Abstractions.WindowsApi.pInvokes.StartUserProcessInSession(SessionId, proquotaPath + " \"" + userInfo.LocalProfilePath + "\" " + settings["MaxStore"]))
{
m_logger.ErrorFormat("{0} Can't run application {1}", userInfo.Username, "proquota.exe");
}
}
}
else
{
m_logger.InfoFormat("{0} is'nt a pGina pgSMB2 plugin created user. I'm not executing Notification stage", userInfo.Username);
}
}
}
private void cleanup(UserInformation userInfo, int sessionID, SessionProperties properties)
{
Dictionary<string, string> settings = GetSettings(userInfo.Username, userInfo);
try
{
while (true)
{
// logoff detection is quite a problem under NT6
// a disconnectEvent is only triggered during a logoff
// but not during a shutdown/reboot
// and the SessionLogoffEvent is only saying that the user is logging of
// So, there is no event that is fired during a user-logoff/reboot/shutdown
// that indicates that the user has logged of
if (Abstractions.WindowsApi.pInvokes.IsSessionLoggedOFF(sessionID) || IsShuttingDown)
{
break;
}
else
{
Thread.Sleep(1000);
}
}
while (true)
{
// if no other notification plugin is working on this user
// if the first entry from GetNotificationPlugins is equal to this plugin UID
IEnumerable<Guid> guids = properties.GetTrackedSingle<PluginActivityInformation>().GetNotificationPlugins();
/*foreach(Guid gui in guids)
{
m_logger.DebugFormat("{1} PluginActivityInformation guid:{0}", gui, userInfo.Username);
}*/
if (guids.DefaultIfEmpty(Guid.Empty).FirstOrDefault().Equals(PluginUuid) || guids.ToList().Count == 0)
{
break;
}
Thread.Sleep(1000);
}
Roaming ro = new Roaming();
if (!userInfo.Description.EndsWith(" tmp")) //its a tmp profile do not upload
{
BooleanResult RetBool = ro.put(settings, userInfo.Username, userInfo.Password, userInfo.LocalProfilePath, userInfo.SID);
if (!RetBool.Success)
{
m_logger.ErrorFormat("unable to Logoff {0} Error:{1}", userInfo.Username, RetBool.Message);
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), userInfo.Username, userInfo.Password, String.Format("pGina: unable to Logoff {0} from {1}", userInfo.Username, Environment.MachineName), RetBool.Message);
}
}
m_logger.InfoFormat("{0} cleanup done", userInfo.Username);
}
catch (Exception ex)
{
m_logger.FatalFormat("{0} Error during Logoff of {1}", userInfo.Username, ex.Message);
Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), userInfo.Username, userInfo.Password, String.Format("pGina: Logoff Exception {0} from {1}", userInfo.Username, Environment.MachineName), "Logoff Exception\n" + ex.Message);
}
try
{
Locker.TryEnterWriteLock(-1);
RunningTasks.Remove(userInfo.Username.ToLower());
PluginActivityInformation notification = properties.GetTrackedSingle<PluginActivityInformation>();
notification.DelNotificationResult(PluginUuid);
m_logger.InfoFormat("{1} PluginActivityInformation del Guid:{0}", PluginUuid, userInfo.Username);
properties.AddTrackedSingle<PluginActivityInformation>(notification);
foreach (Guid guid in properties.GetTrackedSingle<PluginActivityInformation>().GetNotificationPlugins())
{
m_logger.InfoFormat("{1} PluginActivityInformation Guid:{0}", guid, userInfo.Username);
}
}
finally
{
Locker.ExitWriteLock();
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Security;
using System.Security.Cryptography;
using Microsoft.Win32;
namespace Abstractions.Settings
{
public class DynamicSettings : DynamicObject
{
public static readonly string ROOT_KEY = @"SOFTWARE\pGina3.fork";
protected string m_rootKey = ROOT_KEY;
public DynamicSettings()
{
}
public DynamicSettings(string root)
{
m_rootKey = root;
}
public DynamicSettings(Guid pluginGuid)
{
m_rootKey = String.Format(@"{0}\Plugins\{1}", ROOT_KEY, pluginGuid.ToString());
}
public DynamicSettings(Guid pluginGuid, string subkey)
{
m_rootKey = String.Format(@"{0}\Plugins\{1}\{2}", ROOT_KEY, pluginGuid.ToString(), subkey);
}
/// <summary>
/// Sets the default value for a setting. Checks to see if the setting
/// is already defined in the registry. If so, the method does nothing.
/// Otherwise the setting is initialized to value.
/// </summary>
/// <param name="name">The name of the setting</param>
/// <param name="value">The default value for the setting</param>
public void SetDefault(string name, object value)
{
try
{
GetSetting(name);
}
catch (KeyNotFoundException)
{
SetSetting(name, value);
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(m_rootKey, true))
{
if (m_rootKey.EndsWith(@"\global", StringComparison.CurrentCultureIgnoreCase))
{
System.Security.AccessControl.RegistrySecurity acc = key.GetAccessControl(System.Security.AccessControl.AccessControlSections.All);
System.Security.AccessControl.RegistryAccessRule authenticated = new System.Security.AccessControl.RegistryAccessRule(
new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.AuthenticatedUserSid, null),
System.Security.AccessControl.RegistryRights.ReadKey,
System.Security.AccessControl.InheritanceFlags.None,
System.Security.AccessControl.PropagationFlags.None,
System.Security.AccessControl.AccessControlType.Allow);
acc.AddAccessRule(authenticated);
key.SetAccessControl(acc);
}
}
}
}
public void SetSetting(string name, object value)
{
using (RegistryKey key = Registry.LocalMachine.CreateSubKey(m_rootKey))
{
key.SetValue(name, value);
}
}
public void SetDefaultEncryptedSetting(string name, string value)
{
this.SetDefaultEncryptedSetting(name, value, null);
}
public void SetDefaultEncryptedSetting(string name, string value, byte[] optionalEntropy)
{
try
{
GetEncryptedSetting(name, optionalEntropy);
}
catch (KeyNotFoundException)
{
SetEncryptedSetting(name, value, optionalEntropy);
}
}
public void SetEncryptedSetting(string name, string value)
{
this.SetEncryptedSetting(name, value, null);
}
public void SetEncryptedSetting(string name, string value, byte[] optionalEntropy)
{
byte[] valueBytes = UnicodeEncoding.Default.GetBytes(value);
byte[] protectedBytes = ProtectedData.Protect(valueBytes, optionalEntropy, DataProtectionScope.LocalMachine);
string base64 = Convert.ToBase64String(protectedBytes);
SetSetting(name, base64);
}
public string GetEncryptedSetting(string name)
{
return GetEncryptedSetting(name, null);
}
public string GetEncryptedSetting(string name, byte[] optionalEntropy)
{
string base64 = (string) GetSettingFromRegistry(name);
byte[] protectedBytes = Convert.FromBase64String(base64);
byte[] valueBytes = ProtectedData.Unprotect(protectedBytes, optionalEntropy, DataProtectionScope.LocalMachine);
return UnicodeEncoding.Default.GetString(valueBytes);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
SetSetting(binder.Name, value);
return true;
}
//still dangerous, Exception not catched by calling function
//FIXME: return null and handle that by calling functions instead of an exception
private object GetSettingFromRegistry(string name)
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(m_rootKey, RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl))
{
if (key != null)
{
// Make sure key exists before requesting it
foreach (string valueName in key.GetValueNames())
{
if (String.Compare(valueName, name, true) == 0)
{
return key.GetValue(name);
}
}
throw new KeyNotFoundException(string.Format("Unable to find value for: {0}", name));
}
else
{
throw new KeyNotFoundException(string.Format("Unable to open registry key"));
}
}
}
/// <summary>
/// Get a dictionary containing all values of the pgina registry
/// key. The Dictionary key is the sub-key name, the value is a pGinaDynamicSettings object
/// corresponding to the sub-key.
/// </summary>
/// <returns></returns>
public Dictionary<string, string> GetSettings(string[] encypted)
{
Dictionary<string, string> result = new Dictionary<string, string>();
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(m_rootKey, false))
{
if (key != null)
{
string[] names = key.GetValueNames();
foreach (string n in names)
{
object type = key.GetValue(n);
string value = "";
switch (key.GetValueKind(n))
{
case RegistryValueKind.String:
case RegistryValueKind.ExpandString:
value += type;
break;
case RegistryValueKind.Binary:
foreach (byte b in (byte[])type)
{
value += b;
}
Console.WriteLine();
break;
case RegistryValueKind.DWord:
value += Convert.ToString((Int32)type);
break;
case RegistryValueKind.QWord:
value += Convert.ToString((Int64)type);
break;
case RegistryValueKind.MultiString:
foreach (string s in (string[])type)
{
value += String.Format("{0}\0", s);
}
value = value.TrimEnd();
break;
default:
break;
}
if (encypted.Any(s => s.Equals(n, StringComparison.CurrentCultureIgnoreCase)))
{
value = GetEncryptedSetting(n);
}
result.Add(n, value);
}
}
}
}
catch (Exception ex)
{
Abstractions.Logging.LibraryLogging.Error("GetSettings({0}, {{1}}) failed:{2}", m_rootKey, String.Join(", ", encypted), ex.Message);
}
return result;
}
public DynamicSetting GetSetting(string name)
{
return new DynamicSetting(name, GetSettingFromRegistry(name));
}
public DynamicSetting GetSetting(string name, object def)
{
try
{
return GetSetting(name);
}
catch (KeyNotFoundException)
{
return new DynamicSetting(name, def);
}
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = GetSetting(binder.Name);
return true;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Diagnostics;
using System.Security.AccessControl;
using System.Security.Principal;
using Abstractions.Logging;
namespace Abstractions.Pipes
{
public class PipeServer : Pipe
{
public int MaxClients { get; private set; }
private Thread[] m_serverThreads = null;
private bool m_running = false;
private bool Running
{
get { lock (this) { return m_running; } }
set { lock (this) { m_running = value; } }
}
public PipeServer(string name, int maxClients, Func<BinaryReader, BinaryWriter, bool> action)
: base(name, action)
{
MaxClients = maxClients;
}
public PipeServer(string name, int maxClients, Func<IDictionary<string, object>, IDictionary<string, object>> action)
: base(name, action)
{
MaxClients = maxClients;
}
public void Start()
{
StartServerThreads();
}
public void Stop()
{
StopServerThreads();
}
private void StartServerThreads()
{
if (Running)
return;
lock (this)
{
Running = true;
m_serverThreads = new Thread[MaxClients];
for (int x = 0; x < MaxClients; x++)
{
m_serverThreads[x] = new Thread(new ThreadStart(ServerThread));
m_serverThreads[x].Start();
}
}
}
private void StopServerThreads()
{
if (!Running)
return;
Running = false;
// Some or all of our threads may be blocked waiting for connections,
// this is a bit nasty, but since I can't seem to get the async
// wait working, we do this - poke em!
for (int x = 0; x < MaxClients; x++)
{
FakeClientToWakeEmAndShakem();
}
for (int x = 0; x < MaxClients; x++)
{
m_serverThreads[x].Join();
}
m_serverThreads = null;
}
private void ServerThread()
{
PipeSecurity security = new PipeSecurity();
using (WindowsIdentity myself = WindowsIdentity.GetCurrent())
{
try
{
// Anyone can talk to us
LibraryLogging.Debug("Setting PipeAccess R/W for world: {0}", Abstractions.Windows.Security.GetWellknownSID(WellKnownSidType.WorldSid));
security.AddAccessRule(new PipeAccessRule(Abstractions.Windows.Security.GetWellknownSID(WellKnownSidType.WorldSid), PipeAccessRights.ReadWrite, AccessControlType.Allow));
// But only we have full control (including the 'create' right, which allows us to be the server side of this equation)
LibraryLogging.Debug("Setting PipeAccess FullControl for myself: {0}", WindowsIdentity.GetCurrent().Name);
security.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, AccessControlType.Allow));
}
catch (Exception e)
{
LibraryLogging.Error("Unable to set all pipe access rules, the security of the pGina service pipe is in an unknown state!: {0}", e);
}
}
while (Running)
{
try
{
using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(Name, PipeDirection.InOut, MaxClients,
PipeTransmissionMode.Byte, PipeOptions.WriteThrough, 0, 0, security, HandleInheritability.None))
{
try
{
pipeServer.WaitForConnection();
}
catch (Exception e)
{
LibraryLogging.Error("Error in server connection handler: {0}", e);
continue;
}
// Handle this connection, note that we always expect client to initiate the
// flow of messages, so we do not include an initial message
using (BinaryReader reader = new BinaryReader(pipeServer, Encoding.Unicode/*, true*/))
{
using (BinaryWriter writer = new BinaryWriter(pipeServer, Encoding.Unicode/*, true*/))
{
HandlePipeConnection(reader, writer, null);
}
}
}
}
catch (Exception e)
{
LibraryLogging.Error("Error while trying to open pipe server: {0}", e);
if (Running)
{
dynamic s_settings = new Abstractions.Settings.DynamicSettings();
Abstractions.Windows.Networking.sendMail(s_settings.GetSettings(new string[] { "notify_pass" }), "", "", String.Format("pGina: PipeServer error {0}", Environment.MachineName), e.ToString());
}
}
}
}
private void FakeClientToWakeEmAndShakem()
{
try
{
PipeClient client = new PipeClient(Name);
client.Start(((r, w) => { return false; }), null, 100);
}
catch { /* intentionally ignored */ }
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace pGina.Plugin.pgSMB2
{
public partial class Configuration : Form
{
public Configuration()
{
InitializeComponent();
SettingsToUi();
}
public class MaxStoreText
{
public string Name { get; set; }
public string Value { get; set; }
}
private void SettingsToUi()
{
string SMBshare_str = Settings.Store.SMBshare;
string RoamingSource = Settings.Store.RoamingSource;
string Filename = Settings.Store.Filename;
string TempComp = Settings.Store.TempComp;
int ConnectRetry = Settings.Store.ConnectRetry;
string Compressor = Settings.Store.Compressor;
string UncompressCLI = Settings.Store.UncompressCLI;
string CompressCLI = Settings.Store.CompressCLI;
string HomeDir = Settings.Store.HomeDir;
string HomeDirDrive = Settings.Store.HomeDirDrive;
string ScriptPath = Settings.Store.ScriptPath;
int MaxStore = Settings.Store.MaxStore;
string MaxStoreExclude = Settings.StoreGlobal.MaxStoreExclude;
string[] MaxStoreText = Settings.StoreGlobal.MaxStoreText;
Dictionary<string, string> ntps = pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "" });
if (!ntps.ContainsKey("ntpservers") || String.IsNullOrEmpty(ntps["ntpservers"]))
{
MessageBox.Show(this, "Setup at least one Ntp server in the global configuration", "Global Ntp Server missing");
}
this.SMBshare.Text = SMBshare_str;
this.RoamingSource.Text = RoamingSource;
this.Filename.Text = Filename;
this.TempComp.Text = TempComp;
this.ConnectRetry.Value = (uint)ConnectRetry;
this.Compressor.Text = Compressor;
this.UncompressCLI.Text = UncompressCLI;
this.CompressCLI.Text = CompressCLI;
this.HomeDir.Text = HomeDir;
this.HomeDirDrive.Text = HomeDirDrive;
this.ScriptPath.Text = ScriptPath;
this.MaxStore.Value = (uint)MaxStore;
this.MaxStore_calc.Text = ((uint)MaxStore / 1024).ToString("F") + " MByte";
this.MaxStore_exclude.Text = MaxStoreExclude;
List<MaxStoreText> dataSource = new List<MaxStoreText>();
foreach (string text in MaxStoreText)
{
dataSource.Add(new MaxStoreText()
{
Name = text.Split(new char[] { '\t' }, 2).First(),
Value = text.Split(new char[] { '\t' }, 2).Last()
});
}
this.MaxStore_proquota_comboBox.DataSource = dataSource;
this.MaxStore_proquota_comboBox.DisplayMember = "Name";
this.MaxStore_proquota_comboBox.ValueMember = "Value";
//MessageBox.Show(Environment.CurrentDirectory.ToString());
//MessageBox.Show(Environment.ExpandEnvironmentVariables(TempComp));
}
private void Form_Load(object sender, EventArgs e)
{
ToolTip toolTip1 = new ToolTip();
toolTip1.AutoPopDelay = 10000;
toolTip1.InitialDelay = 0;
toolTip1.ReshowDelay = 0;
toolTip1.ShowAlways = true;
toolTip1.SetToolTip(this.SMBshare, "The UNC name of the share to connect");
toolTip1.SetToolTip(this.RoamingSource, "Where to store the compressed profile");
toolTip1.SetToolTip(this.Filename, "The name of the compressed profile");
toolTip1.SetToolTip(this.TempComp, "A local temporarily storage for the compressed Profile");
toolTip1.SetToolTip(this.ConnectRetry, "How often to retry to connect to the share\n(un)compress the profile");
toolTip1.SetToolTip(this.Compressor, "The Program to (un)compress the user profile");
toolTip1.SetToolTip(this.UncompressCLI, "The command to uncompress the profile");
toolTip1.SetToolTip(this.CompressCLI, "The Commandline to compress the user profile");
toolTip1.SetToolTip(this.HomeDir, "The user home directory");
toolTip1.SetToolTip(this.HomeDirDrive, "The user home drive");
toolTip1.SetToolTip(this.ScriptPath, "The full path to your login script (Runonce regkey!)");
toolTip1.SetToolTip(this.MaxStore, "Maximum profile size in kbytes\nless or equal 10MB == all space");
toolTip1.SetToolTip(this.MaxStore_exclude, "Exclude Directories from user profile storage quota\nRegular-Expressions!");
toolTip1.SetToolTip(this.MaxStore_proquota_comboBox, "Text for proquota");
}
private void UiToSettings()
{
Settings.Store.SMBshare = this.SMBshare.Text.Trim();
Settings.Store.RoamingSource = this.RoamingSource.Text.Trim();
Settings.Store.Filename = this.Filename.Text.Trim();
Settings.Store.TempComp = this.TempComp.Text.Trim();
Settings.Store.ConnectRetry = Convert.ToInt32(this.ConnectRetry.Value);
Settings.Store.Compressor = this.Compressor.Text.Trim();
Settings.Store.UncompressCLI = this.UncompressCLI.Text.Trim();
Settings.Store.CompressCLI = this.CompressCLI.Text.Trim();
Settings.Store.MaxStore = Convert.ToInt32(this.MaxStore.Value);
Settings.Store.HomeDir = this.HomeDir.Text.Trim();
Settings.Store.HomeDirDrive = this.HomeDirDrive.Text.Trim();
Settings.Store.ScriptPath = this.ScriptPath.Text.Trim();
try
{
Regex.IsMatch("foobar", this.MaxStore_exclude.Text.Trim());
Settings.StoreGlobal.MaxStoreExclude = this.MaxStore_exclude.Text.Trim();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "A regular expression parsing error occurred");
}
List<MaxStoreText> proquota_text = this.MaxStore_proquota_comboBox.DataSource as List<MaxStoreText>;
List<string> proquota = new List<string>();
foreach (MaxStoreText d in proquota_text)
{
proquota.Add(String.Format("{0}\t{1}\n", d.Name, d.Value));
}
Settings.StoreGlobal.MaxStoreText = proquota.ToArray();
Dictionary<string, string> ntps = pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "" });
if (!ntps.ContainsKey("ntpservers") || String.IsNullOrEmpty(ntps["ntpservers"]))
{
MessageBox.Show(this, "No ntp server given!\nSet at least one NTP server in the global configuration!", "Warning NTP server needed");
}
}
private void MaxStore_MB(object sender, EventArgs e)
{
this.MaxStore_calc.Text = (this.MaxStore.Value/1024).ToString("F")+" MByte";
}
private void Btn_save(object sender, EventArgs e)
{
this.UiToSettings();
this.Close();
}
private void Btn_close(object sender, EventArgs e)
{
this.Close();
}
private void Btn_help(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/pgsmb2.html");
}
private void MaxStore_proquota_comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
MaxStoreText data = this.MaxStore_proquota_comboBox.SelectedItem as MaxStoreText;
this.MaxStore_proquota_richTextBox.Text = data.Value;
}
private void MaxStore_proquota_richTextBox_TextChanged(object sender, EventArgs e)
{
MaxStoreText selected = this.MaxStore_proquota_comboBox.SelectedItem as MaxStoreText;
List<MaxStoreText> data = this.MaxStore_proquota_comboBox.DataSource as List<MaxStoreText>;
for (int x = 0; x < data.Count;x++ )
{
if (data[x].Name == selected.Name)
{
data[x].Value = this.MaxStore_proquota_richTextBox.Text;
}
}
this.MaxStore_proquota_comboBox.DataSource = data;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace pGina.Plugin.MySQLAuth
{
class MySqlUserDataSource : IDisposable
{
private MySqlConnection m_conn = null;
private ILog m_logger;
public MySqlUserDataSource()
{
m_logger = LogManager.GetLogger("MySqlUserDataSource");
MySqlConnectionStringBuilder bldr = new MySqlConnectionStringBuilder();
bldr.Server = Settings.Store.Host;
int port = Settings.Store.Port;
bldr.Port = Convert.ToUInt32(port);
bldr.UserID = Settings.Store.User;
bldr.Database = Settings.Store.Database;
bldr.Password = Settings.Store.GetEncryptedSetting("Password");
bool useSsl = Settings.Store.UseSsl;
if (useSsl)
bldr.SslMode = MySqlSslMode.Required;
m_conn = new MySqlConnection(bldr.GetConnectionString(true));
if( m_conn != null ) m_conn.Open();
else throw new Exception("Unable to create connection to database.");
}
public void Dispose()
{
if (m_conn != null)
{
m_logger.DebugFormat("Closing connection.");
m_conn.Close();
}
}
public UserEntry GetUserEntry(string userName)
{
string tableName = Settings.Store.Table;
string unameCol = Settings.Store.UsernameColumn;
string hashMethodCol = Settings.Store.HashMethodColumn;
string passwdCol = Settings.Store.PasswordColumn;
string query = string.Format("SELECT {1}, {2}, {3} " +
"FROM {0} WHERE {1}=@user", tableName, unameCol, hashMethodCol, passwdCol);
MySqlCommand cmd = new MySqlCommand(query, m_conn);
cmd.Parameters.AddWithValue("@user", userName);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
rdr.Read();
PasswordHashAlgorithm hashAlg;
string uname = rdr[0].ToString();
string hash = rdr[2].ToString();
switch (rdr[1].ToString())
{
case "NONE":
hashAlg = PasswordHashAlgorithm.NONE;
break;
case "MD5":
hashAlg = PasswordHashAlgorithm.MD5;
break;
case "SMD5":
hashAlg = PasswordHashAlgorithm.SMD5;
break;
case "SHA1":
hashAlg = PasswordHashAlgorithm.SHA1;
break;
case "SSHA1":
hashAlg = PasswordHashAlgorithm.SSHA1;
break;
case "SHA256":
hashAlg = PasswordHashAlgorithm.SHA256;
break;
case "SSHA256":
hashAlg = PasswordHashAlgorithm.SSHA256;
break;
case "SHA512":
hashAlg = PasswordHashAlgorithm.SHA512;
break;
case "SSHA512":
hashAlg = PasswordHashAlgorithm.SSHA512;
break;
case "SHA384":
hashAlg = PasswordHashAlgorithm.SHA384;
break;
case "SSHA384":
hashAlg = PasswordHashAlgorithm.SSHA384;
break;
default:
m_logger.ErrorFormat("Unrecognized hash algorithm: {0}", rdr[1].ToString());
return null;
}
rdr.Close();
return new UserEntry(uname, hashAlg, hash);
}
return null;
}
public bool IsMemberOfGroup(string userName, string groupName)
{
string userTableName = Settings.Store.Table;
string unameCol = Settings.Store.UsernameColumn;
string userPK = Settings.Store.UserTablePrimaryKeyColumn;
string user_id = null;
// Get the user ID (the primary key for the user)
string query = string.Format("SELECT {1}, {2} " +
"FROM {0} WHERE {1}=@user", userTableName, unameCol, userPK);
MySqlCommand cmd = new MySqlCommand(query, m_conn);
cmd.Parameters.AddWithValue("@user", userName);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
rdr.Read(); // Read first row
user_id = rdr[1].ToString();
}
rdr.Close();
if (user_id == null)
{
m_logger.ErrorFormat("Unable to find entry in DB for {0}", userName);
return false;
}
// Get all groups for the user, and check membership
string userGroupTableName = Settings.Store.UserGroupTableName;
string groupTableName = Settings.Store.GroupTableName;
string groupFKCol = Settings.Store.GroupForeignKeyColumn;
string userFKCol = Settings.Store.UserForeignKeyColumn;
string groupPKCol = Settings.Store.GroupTablePrimaryKeyColumn;
string groupNameCol = Settings.Store.GroupNameColumn;
query = string.Format("SELECT {0}.{5} FROM {0},{1} " +
"WHERE {0}.{4} = {1}.{3} AND {1}.{2} = @user_id",
groupTableName, userGroupTableName, userFKCol, groupFKCol, groupPKCol, groupNameCol);
cmd = new MySqlCommand(query, m_conn);
cmd.Parameters.AddWithValue("@user_id", user_id);
try
{
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string group = rdr[0].ToString();
if (group.Equals(groupName, StringComparison.CurrentCultureIgnoreCase))
return true;
}
}
catch (Exception e)
{
m_logger.ErrorFormat("Exception: {0}", e);
throw;
}
finally
{
if (rdr != null) rdr.Close();
}
return false;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace pGina.Plugin.LocalMachine
{
public partial class Configuration : Form
{
public Configuration()
{
InitializeComponent();
SettingsToUi();
}
public void SettingsToUi()
{
bool AlwaysAuthenticate = Settings.Store.AlwaysAuthenticate;
bool AuthzLocalAdminsOnly = Settings.Store.AuthzLocalAdminsOnly;
bool AuthzLocalGroupsOnly = Settings.Store.AuthzLocalGroupsOnly;
string[] AuthzLocalGroups = Settings.Store.AuthzLocalGroups;
bool AuthzApplyToAllUsers = Settings.Store.AuthzApplyToAllUsers;
bool MirrorGroupsForAuthdUsers = Settings.Store.MirrorGroupsForAuthdUsers;
bool GroupCreateFailIsFail = Settings.Store.GroupCreateFailIsFail;
string[] MandatoryGroups = Settings.Store.MandatoryGroups;
bool ScramblePasswords = Settings.Store.ScramblePasswords;
bool RemoveProfiles = Settings.Store.RemoveProfiles;
bool scrWhenLMFail = Settings.Store.ScramblePasswordsWhenLMAuthFails;
string[] scrambleExceptions = Settings.Store.ScramblePasswordsExceptions;
m_chkAlwaysAuth.Checked = AlwaysAuthenticate;
m_chkAuthzLocalAdmin.Checked = AuthzLocalAdminsOnly;
m_chkAuthzRequireLocal.Checked = AuthzLocalGroupsOnly;
m_chkScramble.Checked = ScramblePasswords;
m_chkRemoveProfile.Checked = RemoveProfiles;
m_chkScrambleWhenLMFails.Checked = scrWhenLMFail;
foreach (string group in AuthzLocalGroups)
{
m_localGroupDgv.Rows.Add(new string[] { group });
}
m_chkAuthzAll.Checked = AuthzApplyToAllUsers;
m_chkMirror.Checked = MirrorGroupsForAuthdUsers;
m_chkGroupFailIsFAIL.Checked = GroupCreateFailIsFail;
foreach (string group in MandatoryGroups)
{
m_groupsDgv.Rows.Add(new string[] { group });
}
foreach (string user in scrambleExceptions)
{
m_scrambleAllExceptDGV.Rows.Add(new string[] { user });
}
MaskAuthzUi();
MaskGatewayUi();
}
private void Form_Load(object sender, EventArgs e)
{
ToolTip toolTip1 = new ToolTip();
toolTip1.AutoPopDelay = 10000;
toolTip1.InitialDelay = 0;
toolTip1.ReshowDelay = 0;
toolTip1.ShowAlways = true;
toolTip1.SetToolTip(this.m_chkAlwaysAuth, "When this is checked, the plugin will always attempt to authenticate the user against a local account. If this is not checked, the plugin will only attempt to authenticate when the user has not already been authenticated by a plugin that has executed earlier within the authentication stage.");
toolTip1.SetToolTip(this.m_chkMirror, "Load all groups from the local account into the pGina user information store so that the LocalMachine's Gateway stage (and other subsequent plugins) will see that the user should be a member of those groups.");
toolTip1.SetToolTip(this.m_chkAuthzAll, "When this is checked, the plugin will attempt to authorize all users. Otherwise, the plugin will only authorize users that were authenticated successfully by this plugin.");
toolTip1.SetToolTip(this.m_chkAuthzLocalAdmin, "Only authorize users that are members of the Administrators group.");
toolTip1.SetToolTip(this.m_chkAuthzRequireLocal, "Only authorize users that are members of one of the groups listed below this checkbox");
toolTip1.SetToolTip(this.m_chkGroupFailIsFAIL, "hen this is checked, the plugin will register failure if it is unable to create or join the local groups that are requested.");
toolTip1.SetToolTip(this.m_groupsDgv, "The local account is added to these local groups if not already a member");
toolTip1.SetToolTip(this.m_chkRemoveProfile, "When this is selected, the plugin will attempt to remove the account and its profile after logout when the account did not exist prior to logon.");
toolTip1.SetToolTip(this.m_chkScramble, "When this is checked, the plugin will attempt to scramble the password of the local account after logout");
}
public void UiToSettings()
{
Settings.Store.AlwaysAuthenticate = m_chkAlwaysAuth.Checked;
Settings.Store.AuthzLocalAdminsOnly = m_chkAuthzLocalAdmin.Checked;
Settings.Store.AuthzLocalGroupsOnly = m_chkAuthzRequireLocal.Checked;
Settings.Store.ScramblePasswords = m_chkScramble.Checked;
Settings.Store.RemoveProfiles = m_chkRemoveProfile.Checked;
Settings.Store.ScramblePasswordsWhenLMAuthFails = m_chkScrambleWhenLMFails.Checked;
List<string> localGroups = new List<string>();
foreach (DataGridViewRow row in m_localGroupDgv.Rows)
{
if(row.Cells[0].Value != null)
localGroups.Add((string) row.Cells[0].Value);
}
if (localGroups.Count > 0)
Settings.Store.AuthzLocalGroups = localGroups.ToArray();
else
Settings.Store.AuthzLocalGroups = new string[] { };
Settings.Store.AuthzApplyToAllUsers = m_chkAuthzAll.Checked;
Settings.Store.MirrorGroupsForAuthdUsers = m_chkMirror.Checked;
Settings.Store.GroupCreateFailIsFail = m_chkGroupFailIsFAIL.Checked;
List<string> mandatory = new List<string>();
foreach (DataGridViewRow row in m_groupsDgv.Rows)
{
if (row.Cells[0].Value != null)
mandatory.Add((string)row.Cells[0].Value);
}
if (mandatory.Count > 0)
Settings.Store.MandatoryGroups = mandatory.ToArray();
else
Settings.Store.MandatoryGroups = new string[] { };
// Gather the exceptions list and store
List<string> exceptions = new List<string>();
foreach (DataGridViewRow row in m_scrambleAllExceptDGV.Rows)
{
if (row.Cells[0].Value != null)
exceptions.Add((string)row.Cells[0].Value);
}
if (exceptions.Count > 0)
Settings.Store.ScramblePasswordsExceptions = exceptions.ToArray();
else
Settings.Store.ScramblePasswordsExceptions = new string[] { };
}
public void MaskAuthzUi()
{
m_localGroupDgv.Enabled = m_chkAuthzRequireLocal.Checked;
}
public void MaskGatewayUi()
{
if (m_chkScramble.Checked)
{
m_chkScrambleWhenLMFails.Enabled = true;
m_scrambleAllExceptDGV.Enabled = true;
}
else
{
m_chkScrambleWhenLMFails.Enabled = false;
m_scrambleAllExceptDGV.Enabled = false;
}
}
private void m_chkAuthzRequireLocal_CheckedChanged(object sender, EventArgs e)
{
MaskAuthzUi();
}
private void m_btnSave_Click(object sender, EventArgs e)
{
UiToSettings();
this.Close();
}
private void m_btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void m_chkScramble_CheckedChanged(object sender, EventArgs e)
{
MaskGatewayUi();
}
private void m_chkRemoveProfile_CheckedChanged(object sender, EventArgs e)
{
}
private void m_Help_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/local_machine.html");
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <Windows.h>
#include <string>
#include <pGinaNativeLib.h>
#include <Macros.h>
#include "GinaChain.h"
#include "GinaWrapper.h"
#include "WinlogonRouter.h"
#include "DialogLoggedOutSAS.h"
#include "HookedLoggedOutSAS.h"
// Dialog ID's for MSGINA's WlxLoggedOutSAS Dialog
#define IDD_WLXLOGGEDOUTSAS_DIALOG 1500
namespace pGina
{
namespace GINA
{
GinaChain::GinaChain(WinlogonInterface *pWinLogonIface) :
Gina(pWinLogonIface), WinlogonProxy(pWinLogonIface), m_passthru(false)
{
// Are we in passthru mode?
m_passthru = pGina::Registry::GetBool(L"GinaPassthru", false);
// When we use the winlogon router table, we want it to
// direct all winlogon calls to us (via our WinlogonProxy
// implementation). We sit between winlogon and a real
// GINA, so our Gina interface let's us have first shot
// at Winlogon->Gina direction calls, and WinlogonRouter+
// WinlogonProxy let's us have first shot at Gina->Winlogon
// direction traffic.
WinlogonRouter::Interface(this);
// Init and load our chained/wrapped gina
std::wstring ginaName = pGina::Registry::GetString(L"ChainedGinaPath", L"MSGINA.DLL");
pDEBUG(L"Wrapping gina: %s", ginaName.c_str());
m_wrappedGina = new GinaWrapper(ginaName.c_str());
if(!m_wrappedGina->Load())
{
pERROR(L"Failed to load wrapped gina: 0x%08x", GetLastError());
return;
}
// Now negotiate and initialize our wrapped gina
if(!m_wrappedGina->Negotiate(WinlogonInterface::Version()))
{
pERROR(L"Failed to negotiate with wrapped gina using version: %d (0x%08x)", WinlogonInterface::Version(), WinlogonInterface::Version());
return;
}
if(!m_wrappedGina->Initialize(L"Winsta0", WinlogonRouter::Interface(), NULL, WinlogonRouter::DispatchTable()))
{
pERROR(L"Failed to initialize wrapped gina");
return;
}
}
GinaChain::~GinaChain()
{
if(m_wrappedGina)
{
delete m_wrappedGina;
m_wrappedGina = NULL;
}
}
// Queries from winlogon
bool GinaChain::IsLockOk()
{
return m_wrappedGina->IsLockOk();
}
bool GinaChain::IsLogoffOk()
{
return m_wrappedGina->IsLogoffOk();
}
bool GinaChain::GetConsoleSwitchCredentials(PVOID pCredInfo)
{
bool retval = m_wrappedGina->GetConsoleSwitchCredentials(pCredInfo);
PWLX_CONSOLESWITCH_CREDENTIALS_INFO_V1_0 pInfo = (PWLX_CONSOLESWITCH_CREDENTIALS_INFO_V1_0) pCredInfo;
pDEBUG(L"GetConsoleSwitchCredentials: CredInfo=%p PrivateDataLen: 0x%08x PrivateData: %p", pCredInfo, pInfo->PrivateDataLen, pInfo->PrivateData);
return retval;
}
// Notifications from winlogon
void GinaChain::ReconnectNotify()
{
m_wrappedGina->ReconnectNotify();
}
void GinaChain::DisconnectNotify()
{
m_wrappedGina->DisconnectNotify();
}
void GinaChain::Logoff()
{
m_wrappedGina->Logoff();
}
bool GinaChain::ScreenSaverNotify(BOOL * pSecure)
{
return m_wrappedGina->ScreenSaverNotify(pSecure);
}
void GinaChain::Shutdown(DWORD ShutdownType)
{
m_wrappedGina->Shutdown(ShutdownType);
}
// Notices/Status messages
void GinaChain::DisplaySASNotice()
{
m_wrappedGina->DisplaySASNotice();
}
void GinaChain::DisplayLockedNotice()
{
m_wrappedGina->DisplayLockedNotice();
}
bool GinaChain::DisplayStatusMessage(HDESK hDesktop, DWORD dwOptions, PWSTR pTitle, PWSTR pMessage)
{
return m_wrappedGina->DisplayStatusMessage(hDesktop, dwOptions, pTitle, pMessage);
}
bool GinaChain::GetStatusMessage(DWORD * pdwOptions, PWSTR pMessage, DWORD dwBufferSize)
{
return m_wrappedGina->GetStatusMessage(pdwOptions, pMessage, dwBufferSize);
}
bool GinaChain::RemoveStatusMessage()
{
return m_wrappedGina->RemoveStatusMessage();
}
// SAS handling
int GinaChain::LoggedOutSAS(DWORD dwSasType, PLUID pAuthenticationId, PSID pLogonSid, PDWORD pdwOptions,
PHANDLE phToken, PWLX_MPR_NOTIFY_INFO pMprNotifyInfo, PVOID *pProfile)
{
// If configured to pass through to MS GINA, or auto-logon is enabled, we
// pass through, and let the MS GINA handle the logon.
if(m_passthru || IsAutoLogonEnabled())
{
return m_wrappedGina->LoggedOutSAS(dwSasType, pAuthenticationId, pLogonSid, pdwOptions, phToken, pMprNotifyInfo, pProfile);
}
// We auth'd in another session - this session is the real one though, need to tell the service to add!
if(dwSasType == WLX_SAS_TYPE_AUTHENTICATED)
{
// We could do this, but we don't get password (without additional wrapping of our own in WlxGetConsoleSwitchCredentials
// So instead we grab it post SAS processing via msgina.
WLX_CONSOLESWITCH_CREDENTIALS_INFO_V1_0 credInfo;
if(m_winlogon->WlxQueryConsoleSwitchCredentials(&credInfo))
{
pDEBUG(L"LoggedOutSAS: CredInfo=%p PrivateDataLen: 0x%08x PrivateData: %p", &credInfo, credInfo.PrivateDataLen, credInfo.PrivateData);
}
int msresult = m_wrappedGina->LoggedOutSAS(dwSasType, pAuthenticationId, pLogonSid, pdwOptions, phToken, pMprNotifyInfo, pProfile);
//pGina::Transactions::LoginInfo::Add(pMprNotifyInfo->pszUserName, pMprNotifyInfo->pszDomain, pMprNotifyInfo->pszPassword);
return msresult;
}
// Gather username/password from user. If remote, we get it from rdp client if provided,
// otherwise show the logged out sas dialog to get it.
std::wstring username;
std::wstring password;
std::wstring domain;
bool showDialog = true;
if(pGina::Helpers::UserIsRemote())
{
WLX_CLIENT_CREDENTIALS_INFO_V2_0 creds;
creds.dwType = WLX_CREDENTIAL_TYPE_V2_0;
if(m_winlogon->WlxQueryTsLogonCredentials(&creds))
{
if(creds.pszUserName) username = creds.pszUserName;
if(creds.pszPassword) password = <PASSWORD>;
if(creds.pszDomain) domain = creds.pszDomain;
if(!creds.fPromptForPassword) showDialog = false;
pDEBUG(L"fPromptForPassword: %s", creds.fPromptForPassword ? L"TRUE" : L"FALSE");
pDEBUG(L"fDisconnectOnLogonFailure: %s", creds.fDisconnectOnLogonFailure ? L"TRUE" : L"FALSE");
}
}
if(showDialog)
{
DialogLoggedOutSAS dialog(m_winlogon);
dialog.Username(username);
dialog.Password(<PASSWORD>);
int dialogResult = dialog.ShowDialog();
if(dialogResult == DialogLoggedOutSAS::SAS_ACTION_LOGON)
{
// Harvest u/p for passing along to msgina
username = dialog.Username();
password = dialog.Password();
}
else if(dialogResult >= DialogLoggedOutSAS::SAS_ACTION_MIN && dialogResult <= DialogLoggedOutSAS::SAS_ACTION_MAX)
{
// Just do as told
return dialogResult;
}
else
{
// Unknown ret value, default to no action
return DialogLoggedOutSAS::SAS_ACTION_NONE;
}
}
// We now have the login info, let's give it a shot!
pDEBUG(L"GinaChain::LoggedOutSAS: Processing login for %s", username.c_str());
pGina::Transactions::User::LoginResult result = pGina::Transactions::User::ProcessLoginForUser(username.c_str(), NULL, password.c_str(), pGina::Protocol::LoginRequestMessage::Login);
if(!result.Result())
{
std::wstring failureMsg = result.Message();
pERROR(L"GinaChain::LoggedOutSAS: %s", failureMsg.c_str());
m_winlogon->WlxMessageBox(NULL, const_cast<wchar_t *>(failureMsg.c_str()), L"Login Failure", MB_ICONEXCLAMATION | MB_OK);
return WLX_SAS_ACTION_NONE;
}
pDEBUG(L"inaChain::LoggedOutSAS: Successful, resulting username: %s", result.Username().c_str());
// Invoke the msgina logged out sas dialog, intercept it, set username/password, and hit ok!
HookedLoggedOutSAS::Enabled(true);
HookedLoggedOutSAS::SetLoginInfo(result);
int msresult = m_wrappedGina->LoggedOutSAS(dwSasType, pAuthenticationId, pLogonSid, pdwOptions, phToken, pMprNotifyInfo, pProfile);
HookedLoggedOutSAS::Enabled(false);
return msresult;
}
int GinaChain::LoggedOnSAS(DWORD dwSasType, PVOID pReserved)
{
return m_wrappedGina->LoggedOnSAS(dwSasType, pReserved);
}
int GinaChain::WkstaLockedSAS(DWORD dwSasType)
{
return m_wrappedGina->WkstaLockedSAS(dwSasType);
}
// Things to do when winlogon says to...
bool GinaChain::ActivateUserShell(PWSTR pszDesktopName, PWSTR pszMprLogonScript, PVOID pEnvironment)
{
return m_wrappedGina->ActivateUserShell(pszDesktopName, pszMprLogonScript, pEnvironment);
}
bool GinaChain::StartApplication(PWSTR pszDesktopName, PVOID pEnvironment, PWSTR pszCmdLine)
{
return m_wrappedGina->StartApplication(pszDesktopName, pEnvironment, pszCmdLine);
}
bool GinaChain::NetworkProviderLoad(PWLX_MPR_NOTIFY_INFO pNprNotifyInfo)
{
return m_wrappedGina->NetworkProviderLoad(pNprNotifyInfo);
}
// Winlogon calls from MSGINA that we hook
int GinaChain::WlxDialogBoxParam(HANDLE hInst, LPWSTR lpszTemplate, HWND hwndOwner, DLGPROC dlgprc, LPARAM dwInitParam)
{
// Is it a dialog id (integer)?
if (!HIWORD(lpszTemplate))
{
// Make sure we only hook the dialogs we want
switch ((DWORD) lpszTemplate)
{
case IDD_WLXLOGGEDOUTSAS_DIALOG:
// Thank god gina is single threaded... I think...
HookedLoggedOutSAS::SetHookedDlgProc(dlgprc);
return WinlogonProxy::WlxDialogBoxParam(hInst, lpszTemplate, hwndOwner, HookedLoggedOutSAS::GetDlgHookProc(), dwInitParam);
break;
}
}
// Everyone else falls through
return WinlogonProxy::WlxDialogBoxParam(hInst, lpszTemplate, hwndOwner, dlgprc, dwInitParam);
}
// Check to see if the auto-logon registry settings are there.
bool GinaChain::IsAutoLogonEnabled()
{
std::wstring subKeyName = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon";
// We look for the values "AutoAdminLogon" and "ForceAutoLogon". If either of them exist
// and are non-zero, we return true.
if( pGina::Registry::StringValueExistsAndIsNonZero(HKEY_LOCAL_MACHINE, subKeyName.c_str(), L"AutoAdminLogon") ||
pGina::Registry::StringValueExistsAndIsNonZero(HKEY_LOCAL_MACHINE, subKeyName.c_str(), L"ForceAutoLogon") )
return true;
return false;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using pGina.Shared.Settings;
namespace pGina.Plugin.Kerberos
{
class Settings
{
private static dynamic m_settings = new pGinaDynamicSettings(PluginImpl.PluginUuid);
static Settings()
{
m_settings.SetDefault("Realm", "");
}
public static dynamic Store
{
get { return m_settings; }
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using pGina.Shared.Settings;
namespace pGina.Plugin.pgSMB2
{
class Settings
{
private static dynamic m_settings = new pGinaDynamicSettings(PluginImpl.PluginUuid);
private static dynamic m_settings_global = new pGinaDynamicSettings(PluginImpl.PluginUuid, "global");
static Settings()
{
m_settings.SetDefault("SMBshare", @"\\server.my.domain.com\%u");
m_settings.SetDefault("RoamingSource", @"%s\profile" );
m_settings.SetDefault("Filename", @"%u.wim" );
m_settings.SetDefault("TempComp", @"%PUBLIC%" );
m_settings.SetDefault("ConnectRetry", 3);
m_settings.SetDefault("Compressor", @"imagexEX.exe" );
m_settings.SetDefault("CompressCLI", @"/CHECK /VERIFY /COMPRESS maximum /CONFIG ""%d\%u.ini"" /CAPTURE ""%z"" ""%d\%f"" 1 -xntuser.dat.log* -xntuser.dat{* -x\AppData\Local\ -x\AppData\LocalLow\ -x\AppData\Roaming\Macromedia\ -x""\AppData\Roaming\Adobe\Flash Player\\"" -x\AppData\Roaming\Mozilla\Firefox\Profiles\*.default\extensions.log -x\AppData\Roaming\Mozilla\Firefox\Profiles\*.default\sessionstore-*.js -ms7z;rar;ace;cab;zip;bz2;wim;avi;mp4;mkv;ogm;qtm;ts;mpeg;ogg;ac3;ape;wmv;mp3;jpg;gif;png");
m_settings.SetDefault("UncompressCLI", @"/CHECK /VERIFY /APPLY ""%r\%f"" 1 ""%z""");
m_settings.SetDefault("HomeDir", @"\\server.my.domain.com\%u" );
m_settings.SetDefault("HomeDirDrive", @"O:" );
m_settings.SetDefault("ScriptPath", @"\\server.my.domain.com\%u\script\login.cmd");
m_settings.SetDefault("MaxStore", 0);
m_settings_global.SetDefault("MaxStoreExclude", @"(?i).*(\\AppData\\)(Local|LocalLow)$");
m_settings_global.SetDefault("MaxStoreText", new string[] {
"MaxStoreUserprofile\tProfile storage space",
"MaxStorefree\tfree",
"MaxStoreExceeded\texceeded",
"MaxStoreWarningTitle\tProfile storage space limit soon reached",
"MaxStoreErrorTitle\tProfile storage space limit exceeded",
"MaxStoreErrorText\tYou have exceeded your profile storage space.\nBefore you can log off, you need to move some items from your profile to network or local storage.",
"MaxStoreCalculateText\tcalculate"
});
m_settings_global.SetDefault("ACE", "this has to be set by pgina to adapt the user access to this key");
}
public static dynamic Store
{
get { return m_settings; }
}
public static dynamic StoreGlobal
{
get { return m_settings_global; }
}
}
}
<file_sep>//Copyright (c) 2009 <NAME> <EMAIL>
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace pGina.Plugin.Ldap
{
class LMhash
{
private static readonly byte[] plainText = { 0x4B, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25 };
public static byte[] ComputeHalf(byte[] Half)
{
// Sidestep 'Specified key is a known weak key' exception and
// speed things up
if (Half.Length == 0)
return new byte[] { 0xAA, 0xD3, 0xB4, 0x35, 0xB5, 0x14, 0x04, 0xEE };
else if (Half.Length > 7)
throw new NotSupportedException("Password halves greater than 7 " +
"characters are not supported");
Array.Resize(ref Half, 7);
string[] binary = new string[7]
{
Convert.ToString(Half[0], 2),
Convert.ToString(Half[1], 2),
Convert.ToString(Half[2], 2),
Convert.ToString(Half[3], 2),
Convert.ToString(Half[4], 2),
Convert.ToString(Half[5], 2),
Convert.ToString(Half[6], 2),
};
string binaryString =
new string('0', 8 - binary[0].Length) + binary[0] +
new string('0', 8 - binary[1].Length) + binary[1] +
new string('0', 8 - binary[2].Length) + binary[2] +
new string('0', 8 - binary[3].Length) + binary[3] +
new string('0', 8 - binary[4].Length) + binary[4] +
new string('0', 8 - binary[5].Length) + binary[5] +
new string('0', 8 - binary[6].Length) + binary[6];
DESCryptoServiceProvider des = new DESCryptoServiceProvider()
{
IV = new byte[8],
Key = new byte[8]
{
(byte)((binaryString[0] == '1' ? 128 : 0) +
(binaryString[1] == '1' ? 64 : 0) +
(binaryString[2] == '1' ? 32 : 0) +
(binaryString[3] == '1' ? 16 : 0) +
(binaryString[4] == '1' ? 8 : 0) +
(binaryString[5] == '1' ? 4 : 0) +
(binaryString[6] == '1' ? 2 : 0)),
(byte)((binaryString[7] == '1' ? 128 : 0) +
(binaryString[8] == '1' ? 64 : 0) +
(binaryString[9] == '1' ? 32 : 0) +
(binaryString[10] == '1' ? 16 : 0) +
(binaryString[11] == '1' ? 8 : 0) +
(binaryString[12] == '1' ? 4 : 0) +
(binaryString[13] == '1' ? 2 : 0)),
(byte)((binaryString[14] == '1' ? 128 : 0) +
(binaryString[15] == '1' ? 64 : 0) +
(binaryString[16] == '1' ? 32 : 0) +
(binaryString[17] == '1' ? 16 : 0) +
(binaryString[18] == '1' ? 8 : 0) +
(binaryString[19] == '1' ? 4 : 0) +
(binaryString[20] == '1' ? 2 : 0)),
(byte)((binaryString[21] == '1' ? 128 : 0) +
(binaryString[22] == '1' ? 64 : 0) +
(binaryString[23] == '1' ? 32 : 0) +
(binaryString[24] == '1' ? 16 : 0) +
(binaryString[25] == '1' ? 8 : 0) +
(binaryString[26] == '1' ? 4 : 0) +
(binaryString[27] == '1' ? 2 : 0)),
(byte)((binaryString[28] == '1' ? 128 : 0) +
(binaryString[29] == '1' ? 64 : 0) +
(binaryString[30] == '1' ? 32 : 0) +
(binaryString[31] == '1' ? 16 : 0) +
(binaryString[32] == '1' ? 8 : 0) +
(binaryString[33] == '1' ? 4 : 0) +
(binaryString[34] == '1' ? 2 : 0)),
(byte)((binaryString[35] == '1' ? 128 : 0) +
(binaryString[36] == '1' ? 64 : 0) +
(binaryString[37] == '1' ? 32 : 0) +
(binaryString[38] == '1' ? 16 : 0) +
(binaryString[39] == '1' ? 8 : 0) +
(binaryString[40] == '1' ? 4 : 0) +
(binaryString[41] == '1' ? 2 : 0)),
(byte)((binaryString[42] == '1' ? 128 : 0) +
(binaryString[43] == '1' ? 64 : 0) +
(binaryString[44] == '1' ? 32 : 0) +
(binaryString[45] == '1' ? 16 : 0) +
(binaryString[46] == '1' ? 8 : 0) +
(binaryString[47] == '1' ? 4 : 0) +
(binaryString[48] == '1' ? 2 : 0)),
(byte)((binaryString[49] == '1' ? 128 : 0) +
(binaryString[50] == '1' ? 64 : 0) +
(binaryString[51] == '1' ? 32 : 0) +
(binaryString[52] == '1' ? 16 : 0) +
(binaryString[53] == '1' ? 8 : 0) +
(binaryString[54] == '1' ? 4 : 0) +
(binaryString[55] == '1' ? 2 : 0)),
}
};
ICryptoTransform transform = des.CreateEncryptor();
byte[] b = transform.TransformFinalBlock(plainText, 0, 8);
return new byte[8] { b[0], b[1], b[2], b[3], b[4], b[5],
b[6], b[7] };
}
public static byte[] Compute(string Password)
{
if (Password.Length > 14)
throw new NotSupportedException("Passwords greater than 14 " +
"characters are not supported");
byte[] passBytes = Encoding.ASCII.GetBytes(Password.ToUpper());
byte[][] passHalves = new byte[2][];
if (passBytes.Length > 7)
{
int len = passBytes.Length - 7;
passHalves[0] = new byte[7];
passHalves[1] = new byte[len];
Array.Copy(passBytes, passHalves[0], 7);
Array.Copy(passBytes, 7, passHalves[1], 0, len);
}
else
{
passHalves[0] = passBytes;
passHalves[1] = new byte[0];
}
for (int x = 0; x < 2; x++)
passHalves[x] = ComputeHalf(passHalves[x]);
byte[] hash = new byte[16];
Array.Copy(passHalves[0], hash, 8);
Array.Copy(passHalves[1], 0, hash, 8, 8);
return hash;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using Microsoft.Win32;
namespace pGina.Shared.Settings
{
public class pGinaDynamicSettings : Abstractions.Settings.DynamicSettings
{
public static string pGinaRoot = Abstractions.Settings.DynamicSettings.ROOT_KEY;
public pGinaDynamicSettings() :
base(pGinaRoot)
{
}
public pGinaDynamicSettings(Guid pluginGuid) :
base(string.Format(@"{0}\Plugins\{1}", pGinaRoot, pluginGuid.ToString()))
{
}
public pGinaDynamicSettings(Guid pluginGuid, string subKey) :
base(string.Format(@"{0}\Plugins\{1}\{2}", pGinaRoot, pluginGuid.ToString(), subKey))
{
}
/// <summary>
/// Get a dictionary containing all sub-keys of the plugin's registry
/// key. The Dictionary key is the sub-key name, the value is a pGinaDynamicSettings object
/// corresponding to the sub-key.
/// </summary>
/// <param name="pluginGuid">The plugin Guid.</param>
/// <returns></returns>
public static Dictionary<string, dynamic> GetSubSettings(Guid pluginGuid)
{
Dictionary<string, dynamic> result = new Dictionary<string, dynamic>();
string subKey = string.Format(@"{0}\Plugins\{1}", pGinaRoot, pluginGuid.ToString());
using( RegistryKey key = Registry.LocalMachine.OpenSubKey(subKey, false) )
{
if (key != null)
{
string[] names = key.GetSubKeyNames();
foreach (string n in names)
{
result.Add(n, new pGinaDynamicSettings(pluginGuid, n));
}
}
}
return result;
}
/// <summary>
/// Remove all sub-keys that are NOT in the provided list.
/// </summary>
/// <param name="pluginGuid">The plugin's Guid.</param>
/// <param name="toKeep">The list of sub-keys to keep, all others are deleted.</param>
public static void CleanSubSettings(Guid pluginGuid, List<string> toKeep)
{
string subKey = string.Format(@"{0}\Plugins\{1}", pGinaRoot, pluginGuid.ToString());
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(subKey, true))
{
if (key != null)
{
string[] names = key.GetSubKeyNames();
foreach (string n in names)
{
if (! toKeep.Contains(n))
{
key.DeleteSubKey(n, false);
}
}
}
}
}
/// <summary>
/// Get a dictionary containing all values of the pgina registry
/// key. The Dictionary key is the sub-key name, the value is a pGinaDynamicSettings object
/// corresponding to the sub-key.
/// </summary>
/// <returns></returns>
public static Dictionary<string, string> GetSettings(string subKey, string[] encypted)
{
dynamic s_settings = new Abstractions.Settings.DynamicSettings(subKey);
return s_settings.GetSettings(encypted);
}
/// <summary>
/// Get a string containing a value of the pgina registry
/// key.
/// </summary>
/// <returns></returns>
public static string GetSetting(string subKey, string value, string[] encypted)
{
Dictionary<string, string> keys = GetSettings(subKey, encypted);
foreach (KeyValuePair<string, string> pair in keys)
{
if (pair.Value.Equals(value, StringComparison.CurrentCultureIgnoreCase))
{
return pair.Value;
}
}
return "";
}
/// <summary>
/// Get an encryted string containing a value of the pgina registry
/// key.
/// </summary>
/// <returns></returns>
public static string DecryptSetting(string subKey, string name)
{
try
{
dynamic s_settings = new Abstractions.Settings.DynamicSettings(subKey);
return s_settings.GetEncryptedSetting(name);
}
catch (Exception ex)
{
Abstractions.Logging.LibraryLogging.Error("DecryptSetting({0}, {1}) failed:{2}", subKey, name, ex.Message);
}
return null;
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using pGina.Shared.Settings;
namespace pGina.Plugin.Ldap
{
class Settings
{
public static dynamic Store
{
get { return m_settings; }
}
private static dynamic m_settings;
static Settings()
{
m_settings = new pGinaDynamicSettings(LdapPlugin.LdapUuid);
// Set default values for settings (if not already set)
m_settings.SetDefault("LdapHost", new string[] { "ldap.example.com" });
m_settings.SetDefault("LdapPort", 389);
m_settings.SetDefault("LdapTimeout", 10);
m_settings.SetDefault("UseSsl", false);
m_settings.SetDefault("UseTls", false);
m_settings.SetDefault("RequireCert", false);
m_settings.SetDefault("ServerCertFile", "");
m_settings.SetDefault("UseAuthBindForAuthzAndGateway", false);
m_settings.SetDefault("SearchDN", "");
m_settings.SetDefaultEncryptedSetting("SearchPW", "");
//m_settings.SetDefault("GroupDnPattern", "cn=%g,ou=Group,dc=example,dc=com");
//m_settings.SetDefault("GroupMemberAttrib", "memberUid");
m_settings.SetDefault("AttribConv", new string[] { });
// Authentication
m_settings.SetDefault("AllowEmptyPasswords", false);
m_settings.SetDefault("DnPattern", "uid=%u,dc=example,dc=com");
m_settings.SetDefault("DoSearch", false);
m_settings.SetDefault("SearchFilter", "");
m_settings.SetDefault("SearchContexts", new string[] { });
// Authorization
//m_settings.SetDefault("GroupAuthzRules", new string[] { (new GroupAuthzRule(true)).ToRegString() });
m_settings.SetDefault("GroupAuthzRules", new string[] { });
m_settings.SetDefault("AuthzRequireAuth", false);
m_settings.SetDefault("AuthzAllowOnError", true);
m_settings.SetDefault("AuthzDefault", true);
// Gateway
m_settings.SetDefault("GroupGatewayRules", new string[] { });
// Change password
m_settings.SetDefault("ChangePasswordAttributes", new string[] { });
}
}
}
<file_sep>/*
Written by <NAME>.
Distributed under the pGina License.
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Timers;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.IO;
using log4net;
using pGina.Shared.Interfaces;
using pGina.Shared.Types;
using pGina.Shared.Settings;
namespace pGina.Plugin.Email
{
public class EmailAuthPlugin : IPluginConfiguration, IPluginAuthentication
{
private ILog m_logger = LogManager.GetLogger("EmailAuthPlugin");
public static Guid SimpleUuid = new Guid("{EC3221A6-621F-44CE-B77B-E074298D6B4E}");
private string m_defaultDescription = "A plugin that authenticates against a POP or IMAP server.";
private dynamic m_settings = null;
public EmailAuthPlugin()
{
using(Process me = Process.GetCurrentProcess())
{
m_settings = new pGinaDynamicSettings(SimpleUuid);
m_settings.SetDefault("ShowDescription", true);
m_settings.SetDefault("Description", m_defaultDescription);
m_logger.DebugFormat("Plugin initialized on {0} in PID: {1} Session: {2}", Environment.MachineName, me.Id, me.SessionId);
}
}
public string Name
{
get { return "Email Authentication"; }
}
public string Description
{
get { return m_settings.Description; }
}
public string Version
{
get
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public Guid Uuid
{
get { return SimpleUuid; }
}
BooleanResult IPluginAuthentication.AuthenticateUser(SessionProperties properties)
{
try
{
m_logger.DebugFormat("AuthenticateUser({0})", properties.Id.ToString());
// Get user info, append domain if needed
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
bool appendDomain = (bool) Settings.Store.AppendDomain;
string username;
if ((bool)Settings.Store.AppendDomain)
username = string.Format("{0}@{1}", userInfo.Username, (string)Settings.Store.Domain);
else
username = userInfo.Username;
// Place credentials into a NetworkCredentials object
NetworkCredential creds = new NetworkCredential(username, userInfo.Password);
string server = Settings.Store.Server;
int port = Convert.ToInt32((string)Settings.Store.Port);
bool useSsl = Settings.Store.UseSsl;
string protocol = Settings.Store.Protocol;
//Connect to server
Stream stream = getNetworkStream(server, port, useSsl);
bool authenticated;
m_logger.DebugFormat("Have network stream...");
//Authenticate based on protocol
if (protocol == "POP3")
authenticated = authPop3(stream, creds);
else
authenticated = authImap(stream, creds);
if (authenticated)
return new BooleanResult() { Success = true };
return new BooleanResult() { Success = false, Message = "Invalid username/password." };
}
catch (FormatException e)
{ //Likely thrown if the port number can not be converted to an integer
m_logger.ErrorFormat("Port number is not valid. Format exception: {0}", e);
return new BooleanResult() { Success = false, Message = "Port number is not valid." };
}
catch (EMailAuthException e)
{
if (e.InnerException != null)
m_logger.ErrorFormat("Error: \"{0}\" caught because \"{1}\"", e.Message, e.InnerException.Message);
else
m_logger.ErrorFormat("Error: {0}", e.Message);
return new BooleanResult() { Success = false, Message = e.Message };
}
catch (Exception e)
{
m_logger.ErrorFormat("Error: {0}", e);
return new BooleanResult { Success = false, Message = "Unspecified Error occurred. " + e.Message };
}
}
public void Configure()
{
Configuration conf = new Configuration();
conf.ShowDialog();
}
public void Starting() { }
public void Stopping() { }
/// <summary>
/// Attempts to open a network stream to the specified server.
/// </summary>
/// <param name="server">Server address</param>
/// <param name="port">Port number of server</param>
/// <param name="ssl">Whether SSL is enabled</param>
/// <returns>An open stream to the server.</returns>
private Stream getNetworkStream(string server, int port, bool ssl)
{ //Sets up network connection and returns the stream
m_logger.DebugFormat("Connecting to {0}:{1}, {2} SSL", server, port, ssl ? "using" : "not using");
TcpClient socket = new TcpClient(server, port);
NetworkStream ns = socket.GetStream();
ns.ReadTimeout = Settings.Store.NetworkTimeout;
ns.WriteTimeout = Settings.Store.NetworkTimeout;
if (ssl)
{
SslStream sns = new SslStream(ns, true);
sns.AuthenticateAsClient(server);
return sns;
}
return ns;
}
/// <summary>
/// Authenticates against a POP3 server.
/// If a timestamp is sent in the initial response, it assumes APOP is supported.
/// </summary>
/// <param name="stream">Opened stream to POP3 server</param>
/// <param name="creds">Username/password</param>
/// <returns>True on success, false on failure</returns>
private bool authPop3(System.IO.Stream stream, NetworkCredential creds)
{
try
{
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
System.IO.StreamWriter writer = new System.IO.StreamWriter(stream);
String resp = getResponse(reader);
m_logger.DebugFormat("Initially connected: {0}", resp);
if (!resp.StartsWith("+OK"))
throw new EMailAuthException("Invalid response from server.");
//Check the server welcome message for a timestamp to indicate APOP support
string apopHash = apopPass(resp, creds.Password);
if (apopHash != null)
{
writer.WriteLine(string.Format("APOP {0} {1}", creds.UserName, apopHash));
writer.Flush();
resp = getResponse(reader);
m_logger.DebugFormat("APOP response: {0}", resp);
}
//No timestamp = no APOP support, sending plaintext
else
{
writer.WriteLine("USER {0}", creds.UserName);
writer.Flush();
resp = getResponse(reader);
m_logger.DebugFormat("USER resp: {0}", resp);
writer.WriteLine("PASS {0}", creds.Password);
writer.Flush();
resp = getResponse(reader);
m_logger.DebugFormat("PASS resp: {0}", resp);
}
//Say goodbye to server
writer.WriteLine("QUIT");
writer.Flush();
return resp.StartsWith("+OK");
}
catch (EMailAuthException){ throw; }
catch (Exception e)
{
throw new EMailAuthException("Error communicating with POP server.", e);
}
}
/// <summary>
/// Authenticates against an IMAP server.
/// Presently only supports plain text login.
/// The use of AUTHENTICATE is not yet supported, so SSL is advised.
/// </summary>
/// <param name="stream"></param>
/// <param name="creds"></param>
/// <returns></returns>
private bool authImap(System.IO.Stream stream, NetworkCredential creds)
{ //Sends username/password to IMAP server and verifies successful login.
try
{
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
System.IO.StreamWriter writer = new System.IO.StreamWriter(stream);
String resp = getResponse(reader);
m_logger.DebugFormat("IMAP server: {0}", resp);
writer.WriteLine("li01 LOGIN {{{0}}}", creds.UserName.Length);
writer.Flush();
resp = getResponse(reader);
m_logger.DebugFormat("IMAP Server: {0}", resp);
if (!resp.StartsWith("+"))
throw new EMailAuthException(string.Format("Unexpected response from server: {0}", resp));
writer.WriteLine("{0} {{{1}}}", creds.UserName, creds.Password.Length);
writer.Flush();
resp = getResponse(reader);
m_logger.DebugFormat("IMAP Server: {0}", resp);
if (!resp.StartsWith("+"))
throw new EMailAuthException(string.Format("Unexpected response from server: {0}", resp));
writer.WriteLine(creds.Password);
writer.Flush();
do
{
resp = getResponse(reader);
m_logger.DebugFormat("IMAP Server: {0}", resp);
} while (!resp.StartsWith("li01"));
//Tell server we're disconnecting
writer.WriteLine("lo01 LOGOUT");
writer.Flush();
return resp.StartsWith("li01 OK");
}
catch (EMailAuthException){ throw; }
catch (Exception e)
{
throw new EMailAuthException("Error communicating with IMAP server.", e);
}
}
/// <summary>
/// Determines if the POP3 server supports APOP, and returns the authentication
/// hash if so.
/// </summary>
/// <param name="resp">Initial response from the POP3 server</param>
/// <param name="password">Login password</param>
/// <returns>MD5 password if APOP is supported, null otherwise.</returns>
private string apopPass(string resp, string password)
{
//Determine if timestamp is present in the response
int bIndex = resp.LastIndexOf('<');
int eIndex = resp.LastIndexOf('>');
if (bIndex < 0 || eIndex < 0 || eIndex < bIndex)
return null;
string timestamp = resp.Substring(bIndex, eIndex - bIndex + 1);
MD5 md5 = MD5.Create();
byte[] passbytes = System.Text.Encoding.UTF8.GetBytes(timestamp + password);
byte[] hash = md5.ComputeHash(passbytes);
//Convert byte[] to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("x").PadLeft(2, '0'));
}
return sb.ToString();
}
/// <summary>
/// Attempts to grab a response from the server.
/// </summary>
/// <param name="reader"></param>
/// <returns>Response from the server</returns>
private string getResponse(System.IO.StreamReader reader)
{
try
{
string output = null;
output = reader.ReadLine();
return output;
}
catch (IOException)
{
throw new EMailAuthException("IOException when reading response from server, possible timeout");
}
catch (Exception e)
{
throw new EMailAuthException("Error reading from server.", e);
}
}
}
public class EMailAuthException : Exception
{
public EMailAuthException(string message) : base(message) { }
public EMailAuthException(string message, Exception inner) : base(message, inner) { }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using pGina.Shared.Settings;
namespace pGina.Plugin.RADIUS
{
class Settings
{
public static dynamic Store
{
get { return m_settings; }
}
private static dynamic m_settings;
static Settings()
{
m_settings = new pGinaDynamicSettings(RADIUSPlugin.SimpleUuid);
// Set default values for settings (if not already set)
m_settings.SetDefault("EnableAuth", true);
m_settings.SetDefault("EnableAcct", false);
m_settings.SetDefault("Server", "");
m_settings.SetDefault("AuthPort", 1812); //Authentication port
m_settings.SetDefault("AcctPort", 1813); //Authorization port
m_settings.SetDefaultEncryptedSetting("SharedSecret", "");
m_settings.SetDefault("Timeout", 2500); //in ms
m_settings.SetDefault("Retry", 3);
m_settings.SetDefault("SendNASIPAddress", true);
m_settings.SetDefault("SendNASIdentifier", true);
m_settings.SetDefault("NASIdentifier", "%computername");
m_settings.SetDefault("SendCalledStationID", false);
m_settings.SetDefault("CalledStationID", "%macaddr");
m_settings.SetDefault("AcctingForAllUsers", false);
m_settings.SetDefault("SendInterimUpdates", false);
m_settings.SetDefault("ForceInterimUpdates", false);
m_settings.SetDefault("InterimUpdateTime", 900); //900sec = 15 min
m_settings.SetDefault("AllowSessionTimeout", false);
m_settings.SetDefault("WisprSessionTerminate", false);
m_settings.SetDefault("UseModifiedName", false);
m_settings.SetDefault("IPSuggestion", "");
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pGina.Shared.Types
{
public class SessionProperties
{
private Dictionary<string, object> m_sessionDictionary = new Dictionary<string, object>();
private Guid m_sessionId = Guid.Empty;
public Guid Id
{
get { return m_sessionId; }
set { m_sessionId = value; }
}
private bool m_credui = false;
public bool CREDUI
{
get { return m_credui; }
set { m_credui = value; }
}
public SessionProperties(Guid sessionId, bool credui)
{
m_sessionId = sessionId;
m_credui = credui;
AddTrackedObject("SessionId", new Guid(m_sessionId.ToString()));
AddTrackedObject("CREDUI", m_credui.ToString());
}
public SessionProperties(Guid sessionId)
{
m_sessionId = sessionId;
m_credui = false;
AddTrackedObject("SessionId", new Guid(m_sessionId.ToString()));
AddTrackedObject("CREDUI", m_credui.ToString());
}
public void AddTracked<T>(string name, T value)
{
AddTrackedObject(name, value);
}
public void AddTrackedSingle<T>(T value)
{
AddTrackedObject(typeof(T).ToString(), value);
}
public void AddTrackedObject(string name, object value)
{
lock(this)
{
if (!m_sessionDictionary.ContainsKey(name))
m_sessionDictionary.Add(name, value);
else
m_sessionDictionary[name] = value;
}
}
internal T GetTracked<T>(string name)
{
return (T)GetTrackedObject(name);
}
public T GetTrackedSingle<T>()
{
object ret = GetTracked<T>(typeof(T).ToString());
if (ret == null)
return (T)Activator.CreateInstance(typeof(T));
return (T)ret;
}
public object GetTrackedObject(string name)
{
lock(this)
{
if(!m_sessionDictionary.ContainsKey(name))
return null;
return m_sessionDictionary[name];
}
}
}
}
<file_sep># HTTP auth plugin
This plugin grabs user credentials and send http(s) request to login endpoint (LP).
What is it good for? Well, you can let all logon implementation details to a http(s) server.
It does not absolutely matter if the server is written in java, .net (fffufuu:) or python or node.js.
Everything it shall do is to decide if a pair of username and password can be logged in.
The request shall be application/json encoded POST request.
Response (HR) to such request have status:
- 200 and contains all info about given user. For details see [UInfo.cs](HttpAuth/UInfo.cs)
- 400 <Error message usefully (for non programmers, please :) explaining why error occured>
If response contains groups that exists locally (e.g. 'administrators'),
logged user will be added to that groups.
Example of successful login response body (note the first blank line indicating there is no obstacle to logon):
```
gandalf
<NAME>
<EMAIL>
administrators;lecturers;wizards
```
Will login gandalf that will then be among local admins
(and lecturers and wizards if they exists as local groups).
## implementation details
The HR is cached in auth stage for processing within following stages.
Configuration of LP URL can be done with (in this order):
- setting environment variable PGINALOGINSERVER with desired URL (overrides all)
- setup DNS server to give TXT record named 'pginaloginserver' containing the LP
- pgina settings app with DEFAULT value 'http://pginaloginserver/login'.
The default value scenario can be i.e.: let DNS point the 'pginaloginserver' to nginx server that is able to redirect the request to an app that will handle the HR on /login route.
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using log4net;
using pGina.Shared.Interfaces;
using pGina.Shared.Types;
using pGina.Shared.Settings;
using pGina.Plugin.UsernameMod.Rules;
namespace pGina.Plugin.UsernameMod
{
public class UsernameModPlugin : IPluginConfiguration, IPluginAuthentication, IPluginAuthorization, IPluginAuthenticationGateway
{
private ILog m_logger = LogManager.GetLogger("UsernameModPlugin");
public static Guid SimpleUuid = new Guid("{98477B3A-830D-4BEE-B270-2D7435275F9C}");
private string m_defaultDescription = "Modify the username at various stages of the login process";
private dynamic m_settings = null;
//private ListOfRules rules;
public UsernameModPlugin()
{
using(Process me = Process.GetCurrentProcess())
{
m_settings = new pGinaDynamicSettings(SimpleUuid);
m_settings.SetDefault("ShowDescription", true);
m_settings.SetDefault("Description", m_defaultDescription);
m_logger.DebugFormat("Plugin initialized on {0} in PID: {1} Session: {2}", Environment.MachineName, me.Id, me.SessionId);
}
}
public string Name
{
get { return "Modify Username Plugin"; }
}
public string Description
{
get { return m_settings.Description; }
}
public string Version
{
get
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public Guid Uuid
{
get { return SimpleUuid; }
}
/// <summary>
/// Runs the rules against the username, modifying it for future plugins.
/// If a IMatchRule is present and matches, it will allow a login for that
/// user regardless of an entered password.
/// </summary>
/// <param name="properties"></param>
/// <returns></returns>
BooleanResult IPluginAuthentication.AuthenticateUser(SessionProperties properties)
{
try
{
m_logger.DebugFormat("AuthenticateUser({0})", properties.Id.ToString());
ListOfRules rules = new ListOfRules();
rules.Load();
// Get user info
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
bool authenticated = false; //By default, we don't authenticate
string username = userInfo.Username;
m_logger.DebugFormat("Start of Authentication, username: {0}", username);
foreach (IUsernameRule rule in rules.list)
{
if(rule.stage == Stage.Authentication){
m_logger.DebugFormat("[Authentication] Running rule: {0}", rule.ToString());
if (rule is IModifyRule)
{
IModifyRule mRule = (IModifyRule)rule;
username = mRule.modify(username);
m_logger.DebugFormat("Username modified: {0}", username);
} else if(rule is IMatchRule){
authenticated = ((IMatchRule)rule).match(username) ? true : authenticated;
m_logger.DebugFormat("Authenticated? {0}", authenticated);
}
}
}
//Set the changes to the username
userInfo.Username = username;
return new BooleanResult() { Success = authenticated };
}
catch (Exception e)
{
m_logger.ErrorFormat("Error running rules. {0}", e.Message);
return new BooleanResult() { Success = false, Message = "Unable to modify username during authentication stage." };
}
}
/// <summary>
/// Runs the rules against the username, modifying it for future plugins.
/// If an IMatchRule is present, AuthorizeUser will only return true if
/// the username matches the rule.
/// </summary>
/// <param name="properties"></param>
/// <returns></returns>
BooleanResult IPluginAuthorization.AuthorizeUser(SessionProperties properties)
{
try
{
m_logger.DebugFormat("AuthorizeUser({0})", properties.Id.ToString());
ListOfRules rules = new ListOfRules();
rules.Load();
// Get user info
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
bool authorized = true; //By default, we don't authenticate
string username = userInfo.Username;
m_logger.DebugFormat("Start of Authorization, username: {0}", username);
foreach (IUsernameRule rule in rules.list)
{
if (rule.stage == Stage.Authorization)
{
m_logger.DebugFormat("[Authorization] Checking rule: {0}", rule.ToString());
if (rule is IModifyRule)
{
IModifyRule mRule = (IModifyRule)rule;
username = mRule.modify(username);
m_logger.DebugFormat("Username modified: {0}", username);
}
else if (rule is IMatchRule)
{
//If the match rule fails, do not authorize
authorized = ((IMatchRule)rule).match(username) ? authorized : false;
m_logger.DebugFormat("Authorized? {0}", authorized);
}
}
}
//Set the changes to the username
userInfo.Username = username;
return new BooleanResult() { Success = authorized };
}
catch (Exception e)
{
m_logger.ErrorFormat("Error running rules. {0}", e.Message);
return new BooleanResult() { Success = false, Message = "Unable to modify username during authorization stage." };
}
}
/// <summary>
/// Runs the rules against the username, modifying it for future plugins.
/// If an IMatchRule is present, AuthenticatedUserGateway will only return true if
/// the username matches the rule.
/// </summary>
/// <param name="properties"></param>
/// <returns></returns>
BooleanResult IPluginAuthenticationGateway.AuthenticatedUserGateway(SessionProperties properties)
{
try
{
m_logger.DebugFormat("GatewayUser({0})", properties.Id.ToString());
ListOfRules rules = new ListOfRules();
rules.Load();
// Get user info
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
bool authGateway = true; //By default, we don't authenticate
string username = userInfo.Username;
m_logger.DebugFormat("Start of Gateway, username: {0}", username);
foreach (IUsernameRule rule in rules.list)
{
if (rule.stage == Stage.Gateway)
{
m_logger.DebugFormat("[Gateway] Checking rule: {0}", rule.ToString());
if (rule is IModifyRule)
{
IModifyRule mRule = (IModifyRule)rule;
username = mRule.modify(username);
m_logger.DebugFormat("Username modified: {0}", username);
}
else if (rule is IMatchRule)
{
//If the match rule fails, do not authorize
authGateway = ((IMatchRule)rule).match(username) ? authGateway : false;
m_logger.DebugFormat("Auth'd Gateway? {0}", authGateway);
}
}
}
//Set the changes to the username
userInfo.Username = username;
return new BooleanResult() { Success = authGateway };
}
catch (Exception e)
{
m_logger.ErrorFormat("Error running rules. {0}", e.Message);
return new BooleanResult() { Success = false, Message = "Unable to modify username during gateway stage." };
}
}
public void Configure()
{
Configuration conf = new Configuration();
conf.ShowDialog();
}
public void Starting() { }
public void Stopping() { }
}
class UsernameModPluginException : Exception
{
public UsernameModPluginException(string message)
: base(message)
{
}
public UsernameModPluginException(string message, Exception inner)
: base(message)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace pGina.Plugin.RADIUS
{
//Assumes 8 bits = 1 byte
class Packet
{
public string sharedKey { get; set; }
public Code code { get; private set; }
public byte identifier { get; set; }
public short length
{
get
{
return (short)(20 + avp.toByteArray().Length);
}
}
//authenticator changes based on the type of packet (authorization = random 16 octets, accounting = md5 of packet contents+sharedkey)
public byte[] authenticator { get; private set; }
//Attribute Value Pair, list of (AttributeType, byte[]) values
private static Random r = new Random();
private AVP avp;
public Packet(Code code, string sharedKey) : this(code, (byte)r.Next((int)Byte.MaxValue + 1), sharedKey) { }
public Packet(Code code, byte identifier, string sharedKey)
{
this.code = code;
this.identifier = identifier;
this.sharedKey = sharedKey;
this.authenticator = new byte[16];
this.avp = new AVP();
//Access-Requests use a random authentication code
if (this.code == Code.Access_Request)
{
//Generate secure bytes for authenticator
RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
rngCsp.GetBytes(this.authenticator);
}
}
public Packet(Code code, byte identifier, byte[] auth)
{
this.code = code;
this.identifier = identifier;
this.authenticator = auth;
}
public Packet(byte[] data)
{
this.avp = new AVP();
code = (Code)data[0];
identifier = data[1];
//length = BitConverter.ToInt16(data, 2);
authenticator = new byte[16];
System.Buffer.BlockCopy(data, 4, authenticator, 0, 16);
//AVP Values
int index = 20; //First 20 bytes belong to the header above
while (index < data.Length)
{
AttributeType atype = (AttributeType)data[index++];
byte length = data[index++]; //length includes the type and length byte
byte[] value = new byte[length - 2];
System.Buffer.BlockCopy(data, index, value, 0, value.Length);
avp.addAttribute(atype, value);
index += value.Length;
}
}
//Adds the specified attribute type and corresponding string data to AVP list
public void addAttribute(AttributeType type, string value)
{
if (String.IsNullOrEmpty(value))
throw new ArgumentException("Value can not be empty");
addAttribute(type, Encoding.UTF8.GetBytes(value));
}
//Adds the specified attribute type and corresponding int data to AVP list
//Note that an int is 4 bytes. Single byte values should be sure to be passed as a byte
public void addAttribute(AttributeType type, int value)
{
byte[] arr = BitConverter.GetBytes(value);
Array.Reverse(arr); //Endian issues?
avp.addAttribute(type, arr);
}
public void addAttribute(AttributeType type, byte value)
{
byte[] arr = { value };
avp.addAttribute(type, arr);
}
public void addAttribute(AttributeType type, byte[] value)
{
//If it's a User_Password, we need to encrypt it
if (type == AttributeType.User_Password)
avp.addAttribute(type, PAPPassword(value));
else
avp.addAttribute(type, value);
}
public bool containsAttribute(AttributeType type)
{
return avp.containsAttribute(type);
}
public string getFirstStringAttribute(AttributeType type)
{
return Encoding.UTF8.GetString(avp.getFirstRawAttribute(type));
}
public int getFirstIntAttribute(AttributeType type)
{
byte[] val = avp.getFirstRawAttribute(type);
Array.Reverse(val); //big-endian to little-endian
return BitConverter.ToInt32(val, 0);
}
public byte[] getFirstByteArrayAttribute(AttributeType type)
{
return avp.getFirstRawAttribute(type);
}
public IEnumerable<byte[]> getByteArrayAttributes(AttributeType type, byte[] vsa = null)
{
return avp.getByteArrayAttributes(type, vsa);
}
public IEnumerable<string> getStringAttributes(AttributeType type, byte[] vsa = null)
{
foreach (byte[] val in avp.getByteArrayAttributes(type, vsa))
{
yield return Encoding.UTF8.GetString(val);
}
}
public IEnumerable<int> getIntAttributes(AttributeType type, byte[] vsa = null)
{
foreach(byte[] val in avp.getByteArrayAttributes(type, vsa))
{
Array.Reverse(val); //Big endian to little endian
yield return BitConverter.ToInt32(val, 0);
}
}
//Verifies the response authenticator comes from a legitimate source
public bool verifyResponseAuthenticator(byte[] requestAuthenticator, string sharedKey)
{
//Accounting MD5(respcode+id+length+reqauth+respattr+sharedkey)
//this.authenticator == MD5(Code+ID+Length+RequestAuth+Attributes+Secret)
byte[] secretKeyBytes = Encoding.UTF8.GetBytes(sharedKey);
byte[] verificationBytes = new byte[this.length + secretKeyBytes.Length];
//Copy this packet to the buffer
System.Buffer.BlockCopy(this.toBytes(), 0, verificationBytes, 0, this.length);
//Copy secret key bytes to end of buffer
System.Buffer.BlockCopy(secretKeyBytes, 0, verificationBytes, this.length, secretKeyBytes.Length);
//Replace response authenticator with request authenticator (auth begins at byte 4)
System.Buffer.BlockCopy(requestAuthenticator, 0, verificationBytes, 4, requestAuthenticator.Length);
MD5 md5 = MD5.Create();
byte[] hashedRespCode = md5.ComputeHash(verificationBytes);
return equalByteArrays(hashedRespCode, this.authenticator);
}
//Returns a byte array representing this packet, generating a new authenticator value for accounting requests
public byte[] toBytes()
{
if (this.code == Code.Accounting_Request)
{
//Clear out authenticator
this.authenticator = new byte[16];
//Create array consisting of packet data + shared key
byte[] hashedPacket = new byte[this.length + sharedKey.Length];
byte[] skey = Encoding.UTF8.GetBytes(sharedKey);
System.Buffer.BlockCopy(this.convertToBytes(), 0, hashedPacket, 0, this.length);
System.Buffer.BlockCopy(skey, 0, hashedPacket, this.length, skey.Length);
//Set authenticator to MD5 of packet data + shared key
this.authenticator = MD5.Create().ComputeHash(hashedPacket);
}
return convertToBytes();
}
//Returns a byte array representing this packet
private byte[] convertToBytes()
{
//1 byte for code, 1 byte for identifier, 2 bytes for length, 16 bytes for auth + AVP
byte[] avpBytes = avp.toByteArray();
byte[] packetBytes = new byte[20 + avpBytes.Length];
byte[] lengthBytes = BitConverter.GetBytes(length);
packetBytes[0] = (byte)code;
packetBytes[1] = identifier;
packetBytes[2] = lengthBytes[1]; //Endian stupidness
packetBytes[3] = lengthBytes[0];
System.Buffer.BlockCopy(authenticator, 0, packetBytes, 4, authenticator.Length);
System.Buffer.BlockCopy(avpBytes, 0, packetBytes, 20, avpBytes.Length);
return packetBytes;
}
//Compares two byte arrays for equality, true if equal
private bool equalByteArrays(byte[] arr1, byte[] arr2)
{
if (arr1.Length != arr2.Length)
return false;
for (int k = 0; k < arr1.Length; k++)
if (arr1[k] != arr2[k])
return false;
return true;
}
public override string ToString()
{
string init = String.Format("Code: {0}\tID: {1}\tLength: {2}\nRequest Authenticator: {3}\n", code, identifier, length, authenticator);
StringBuilder builder = new StringBuilder(init);
if (avp.AttributeCount > 0)
{
builder.Append("Attributes:\n");
foreach (Tuple<AttributeType, byte[]> kvp in avp.allAttributes())
{
if (kvp.Item1 == AttributeType.NAS_IP_Address)
builder.AppendFormat("\t{0} : Length: {1}\t{2}.{3}.{4}.{5}\n", kvp.Item1, kvp.Item2.Length + 2, kvp.Item2[0], kvp.Item2[1], kvp.Item2[2], kvp.Item2[3]);
else if (kvp.Item1 == AttributeType.User_Password)
builder.AppendFormat("\t{0} : Length: {1} \tEncrypted to {2} bytes.\n", kvp.Item1, kvp.Item2.Length + 2, kvp.Item2.Length);
else
builder.AppendFormat("\t{0}: Length: {1} \t{2}\n", kvp.Item1, kvp.Item2.Length + 2, String.Join("-", kvp.Item2));
}
}
else
{
builder.Append("No attributes.");
}
return builder.ToString();
}
//Encrypts the User-Password value
private byte[] PAPPassword(byte[] password)
{
/* This implementation could be slightly more efficient.
Call the shared secret S and the pseudo-random 128-bit Request
Authenticator RA. Break the password into 16-octet chunks p1, p2,
etc. with the last one padded at the end with nulls to a 16-octet
boundary. Call the ciphertext blocks c(1), c(2), etc. We'll need
intermediate values b1, b2, etc.
b1 = MD5(S + RA) c(1) = p1 xor b1
b2 = MD5(S + c(1)) c(2) = p2 xor b2
. .
. .
. .
bi = MD5(S + c(i-1)) c(i) = pi xor bi
The String will contain c(1)+c(2)+...+c(i) where + denotes
concatenation.
*/
byte[] secretKeyBytes = Encoding.UTF8.GetBytes(sharedKey); //Secret key as bytes
//Password should be broken into 16 octet chunks, with \0 terminating the additional bytes
int passwordChunks = (password.Length / 16);
if (password.Length % 16 != 0)
passwordChunks += 1;
byte[] extendedPassword = new byte[16 * passwordChunks];
//Fill the last 16 bytes with \0
for (int k = 16 * (passwordChunks - 1); k < extendedPassword.Length; k++)
extendedPassword[k] = (byte)'\0';
//Copy password over
System.Buffer.BlockCopy(password, 0, extendedPassword, 0, password.Length);
MD5 md5 = MD5.Create();
byte[] c = new byte[extendedPassword.Length];
//Create S+RA
byte[] sra = new byte[secretKeyBytes.Length + authenticator.Length];
System.Buffer.BlockCopy(secretKeyBytes, 0, sra, 0, secretKeyBytes.Length);
System.Buffer.BlockCopy(authenticator, 0, sra, secretKeyBytes.Length, authenticator.Length);
//b1
byte[] bx = md5.ComputeHash(sra);
//Cycle through each chunk
for (int k = 0; k < passwordChunks; k++)
{
//Compute Cx ^ bx
for (int j = 0; j < 16; j++)
c[16 * k + j] = (byte)(extendedPassword[16 * k + j] ^ bx[j]);
//S+Cx
byte[] scx = new byte[secretKeyBytes.Length + 16];
System.Buffer.BlockCopy(secretKeyBytes, 0, scx, 0, secretKeyBytes.Length); //S
System.Buffer.BlockCopy(c, 16 * k, scx, secretKeyBytes.Length, 16); //S+Cx
//bx = MD5(S+Cx)
bx = md5.ComputeHash(scx);
}
return c;
}
public enum Code
{
Access_Request = (byte)1, Access_Accept, Access_Reject, Accounting_Request, Accounting_Response
};
public enum AttributeType
{
User_Name = (byte)1, User_Password, CHAP_Password, NAS_IP_Address, NAS_Port,
Service_Type, Framed_Protocol, Framed_IP_Address, Framed_IP_Netmask, Framed_Routing, //10
Filter_Id, Framed_MTU, Framed_Compression, Login_IP_Host, Login_Service,
Login_TCP_Port, UNASSIGNED_17, Reply_Message, Callback_Number, Callback_Id, //20
UNASSIGNED_21, Framed_Route, Framed_IPX_Network, State, Class,
Vendor_Specific, Session_Timeout, Idle_Timeout, Termination_Action, Called_Station_Id, //30
Calling_Station_Id, NAS_Identifier, Proxy_State, Login_LAT_Service, Login_LAT_Node,
Login_LAT_Group, Framed_AppleTalk_Link, Framed_AppleTalk_Network, Framed_AppletTalk_Zone, Acct_Status_Type, //40
Acct_Delay_Time, Acct_Input_Octets, Acct_Output_Octets, Acct_Session_Id, Acct_Authentic,
Acct_Session_Time, Acct_Input_Packets, Acct_Output_Packets, Acct_Terminate_Cause, Acct_Multi_Session_Id, //50
Acct_Link_Count, UNASSIGNED_52, UNASSIGNED_53, UNASSIGNED_54, UNASSIGNED_55,
UNASSIGNED_56, UNASSIGNED_57, UNASSIGNED_58, UNASSIGNED_59, CHAP_Challenge, //60
NAS_Port_Type, Port_Limit, Login_LAT_Port, //Skipping a few accounting types
Acct_Interim_Interval = (byte)84
};
public enum Acct_Authentic { Not_Specified = 0, RADIUS, Local, Remote }
public enum Acct_Status_Type { Start = 1, Stop, Interim_Update }
public enum Acct_Terminate_Cause { User_Request = 1, Idle_Timeout = 4, Session_Timeout = 5}
public enum VSA_WISPr { Vendor_ID = 14122, WISPr_Session_Terminate_Time = 9 }
private class AVP
{
private List<Tuple<AttributeType, byte[]>> list;
private Dictionary<AttributeType, byte> attributeCounter;
public int AttributeCount { get { return list.Count; } }
private byte[] _bytes;
public AVP()
{
list = new List<Tuple<AttributeType, byte[]>>();
attributeCounter = new Dictionary<AttributeType, byte>();
}
//Adds the specified attribute type and corresponding byte array data to AVP list
public void addAttribute(AttributeType type, byte[] value)
{
list.Add(Tuple.Create(type, value));
addTypeToDict(type);
_bytes = null; //Reset cached byte value
}
//Returns the number of entries for the specified AttributeType
public byte AttributeTypeCount(AttributeType type)
{
if (attributeCounter.Keys.Contains(type))
return attributeCounter[type];
return 0;
}
//Returns true if their is at least one instance of the specified attribute type
public bool containsAttribute(AttributeType type)
{
return AttributeTypeCount(type) > 0;
}
//Returns the byte[] value of the first instance of AttributeType found.
public byte[] getFirstRawAttribute(AttributeType type)
{
foreach (Tuple<AttributeType, byte[]> val in list)
{
if (val.Item1 == type)
return val.Item2;
}
throw new ArgumentException(String.Format("No attributes of type {0} found.", type));
}
public IEnumerable<Tuple<AttributeType, byte[]>> allAttributes()
{
foreach (var tuple in list)
yield return tuple;
}
//Returns the string value of the specified AttributeType
public IEnumerable<byte[]> getByteArrayAttributes(AttributeType type, byte[] vsa = null, byte vsaType = 0)
{
/*foreach (byte[] val in lookup[type])
{
yield return Encoding.UTF8.GetString(val);
}*/
foreach (Tuple<AttributeType, byte[]> val in list)
{
if (val.Item1 != type)/* ||
!(type == AttributeType.Vendor_Specific && val.Item2[0] == vsa[0] &&
val.Item2[1] == vsa[1] && val.Item2[2] == vsa[2] && val.Item2[3] == vsaType))*/
continue;
yield return val.Item2;
}
}
//Returns a byte array representing the AVP
public byte[] toByteArray()
{
if (this._bytes != null)
return _bytes;
//Figure out total length of data
int avpLength = 0;
foreach (Tuple<AttributeType, byte[]> data in list)
{
avpLength += data.Item2.Length;
}
//Total size is 2 bytes per entry + the length of all the data
byte[] bytes = new byte[2 * list.Count() + avpLength];
//Copy data in kvp to array as bytes
int pos = 0;
foreach (Tuple<AttributeType, byte[]> kvp in list)
{
//First byte = type, secondbyte = length of data, than data
bytes[pos++] = (byte)kvp.Item1;
bytes[pos++] = (byte)(kvp.Item2.Length + 2); //+2 for the type and length bytes
System.Buffer.BlockCopy(kvp.Item2, 0, bytes, pos, kvp.Item2.Length);
pos += kvp.Item2.Length;
}
this._bytes = bytes;
return bytes;
}
//Increases the attribute counter dictionary value by 1 (or sets it to 1 if not present)
private void addTypeToDict(AttributeType type){
if (attributeCounter.Keys.Contains(type))
attributeCounter[type] += 1;
else
attributeCounter[type] = 1;
}
}
//Static methods for Vendor Specific Attribrutes
//Bytes 0-3 = vendor-id
//Byte 4 = vendor-type
//Byte 5 = vendor-length
//Bytes 6+ = data
public static int VSA_vendorID(byte[] val)
{
//Need to take into account change in endianness
byte[] vid = new byte[4];
Array.Copy(val, vid, 4);
Array.Reverse(vid);
return BitConverter.ToInt32(vid, 0);
}
public static byte VSA_VendorType(byte[] val)
{
return val[4];
}
public static string VSA_valueAsString(byte[] val)
{
return Encoding.UTF8.GetString(val, 6, val.Length - 6);
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include "Registry.h"
#include <WinReg.h>
namespace pGina
{
namespace Registry
{
std::wstring GetString(const wchar_t * keyName, const wchar_t * defaultValue)
{
std::wstring result = GetString(HKEY_LOCAL_MACHINE, L"SOFTWARE\\pGina3.fork", keyName);
if( result.length() == 0 ) result = defaultValue;
return result;
}
DWORD GetDword(const wchar_t * keyName, DWORD defaultValue)
{
DWORD result = defaultValue;
DWORD tmpResult = defaultValue;
HKEY hKey = NULL;
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\pGina3.fork", 0, KEY_READ, &hKey) == ERROR_SUCCESS)
{
DWORD dataLength = sizeof(tmpResult);
if(RegQueryValueEx(hKey, keyName, 0, NULL, (LPBYTE) &tmpResult, &dataLength) == ERROR_SUCCESS)
{
result = tmpResult;
}
RegCloseKey(hKey);
}
return result;
}
bool GetBool(const wchar_t * keyName, bool defaultValue)
{
std::wstring v = defaultValue ? L"True" : L"False";
v = GetString(keyName, v.c_str());
if(_wcsicmp(v.c_str(), L"True") == 0)
return true;
if(_wcsicmp(v.c_str(), L"False") == 0)
return false;
return defaultValue;
}
// Returns true if the value exists and is set to something other than L"0".
// Note that a zero length string is treated as a non-existent value (returns false)
// Assumes the type is REG_SZ
bool StringValueExistsAndIsNonZero( HKEY base, const wchar_t *subKeyName, const wchar_t *valueName )
{
std::wstring result = GetString(base, subKeyName, valueName);
if( result.length() == 0 ) return false; // empty implies that the value does not exist
return wcscmp(L"0", result.c_str()) != 0;
}
// Returns empty (zero-length) string if the value does not exist (assumes REG_SZ)
std::wstring GetString( HKEY base, const wchar_t * subKeyName, const wchar_t *valueName )
{
std::wstring result = L""; // Do not assign NULL!
HKEY hKey = NULL;
if(RegOpenKeyEx(base, subKeyName, 0, KEY_READ, &hKey) == ERROR_SUCCESS)
{
DWORD dataLength = 0;
if(RegQueryValueEx(hKey, valueName, 0, NULL, NULL, &dataLength) == ERROR_SUCCESS)
{
int bufferSize = dataLength + sizeof(wchar_t);
wchar_t * buffer = (wchar_t *) malloc(bufferSize);
memset(buffer, 0, bufferSize);
if(RegQueryValueEx(hKey, valueName, 0, NULL, (LPBYTE) buffer, &dataLength) == ERROR_SUCCESS)
{
result = buffer;
}
free(buffer);
}
RegCloseKey(hKey);
}
return result;
}
std::vector<std::wstring> GetStringArray( const wchar_t *subKeyName )
{
return GetStringArray(HKEY_LOCAL_MACHINE, L"SOFTWARE\\pGina3.fork", subKeyName);
}
std::vector<std::wstring> GetStringArray( HKEY base, const wchar_t *subKeyName, const wchar_t *valueName )
{
std::vector<std::wstring> result;
HKEY hKey = NULL;
if( RegOpenKeyEx(base, subKeyName, 0, KEY_READ, &hKey) == ERROR_SUCCESS)
{
DWORD dataLength = 0;
if(RegQueryValueEx(hKey, valueName, 0, NULL, NULL, &dataLength) == ERROR_SUCCESS)
{
int bufferSize = dataLength + 2*sizeof(wchar_t);
int buffLength = bufferSize / sizeof(wchar_t);
wchar_t * buffer = (wchar_t *) malloc(bufferSize);
ZeroMemory(buffer, bufferSize);
if(RegQueryValueEx(hKey, valueName, 0, NULL, (LPBYTE) buffer, &dataLength) == ERROR_SUCCESS)
{
std::wstring str;
size_t index = 0;
size_t len = wcsnlen(&buffer[index], buffLength);
while(len > 0 && len < buffLength - index)
{
str = &buffer[index];
result.push_back(str);
index += len + 1;
len = wcsnlen(&buffer[index], buffLength - index);
}
}
free(buffer);
}
RegCloseKey(hKey);
}
return result;
}
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Win32;
using log4net;
using pGina.Shared.Settings;
namespace pGina.CredentialProvider.Registration
{
public abstract class CredProviderManager
{
public Settings CpInfo { get; set; }
public CredProviderManager()
{
CpInfo = new Settings();
}
public static CredProviderManager GetManager()
{
if (Abstractions.Windows.OsInfo.IsWindows())
{
if (Abstractions.Windows.OsInfo.IsVistaOrLater())
return new DefaultCredProviderManager();
else
return new GinaCredProviderManager();
}
else
{
throw new Exception("Must be executed on a Windows OS.");
}
}
public void ExecuteDefaultAction()
{
switch (CpInfo.OpMode)
{
case OperationMode.INSTALL:
this.Install();
break;
case OperationMode.UNINSTALL:
this.Uninstall();
break;
case OperationMode.DISABLE:
this.Disable();
break;
case OperationMode.ENABLE:
this.Enable();
break;
}
}
public abstract void Install();
public abstract void Uninstall();
public abstract void Disable();
public abstract void Enable();
public abstract bool Registered();
public abstract bool Registered6432();
public abstract bool Enabled();
public abstract bool Enabled6432();
}
public class GinaCredProviderManager : CredProviderManager
{
private static readonly string GINA_KEY = @"Software\Microsoft\Windows NT\CurrentVersion\Winlogon";
private ILog m_logger = LogManager.GetLogger("GinaCredProviderManager");
public GinaCredProviderManager()
{
this.CpInfo.ShortName = "pGinaGINA";
}
public override void Install()
{
FileInfo dll = null;
if (Abstractions.Windows.OsInfo.Is64Bit())
{
dll = DllUtils.Find64BitDll(this.CpInfo.Path, this.CpInfo.ShortName);
}
else
{
dll = DllUtils.Find32BitDll(this.CpInfo.Path, this.CpInfo.ShortName);
}
if (dll != null)
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(GINA_KEY, true))
{
if (key != null)
{
m_logger.DebugFormat("{0} {1} => {2}", key.ToString(), "GinaDLL",
dll.FullName);
key.SetValue("GinaDLL", dll.FullName);
key.SetValue("NoDomainUI", 1);
key.SetValue("DontDisplayLastUserName", 1);
}
}
}
else
{
throw new Exception("GINA DLL not found in " + CpInfo.Path);
}
}
public override void Uninstall()
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(GINA_KEY, true))
{
if (key != null)
{
m_logger.DebugFormat("Deleting GinaDLL value in {0}", key.ToString());
key.DeleteValue("GinaDLL", false);
key.DeleteValue("NoDomainUI", false);
}
}
}
public override void Disable()
{
dynamic pGinaSettings = new pGinaDynamicSettings();
pGinaSettings.GinaPassthru = true;
}
public override void Enable()
{
dynamic pGinaSettings = new pGinaDynamicSettings();
pGinaSettings.GinaPassthru = false;
}
public override bool Registered()
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(GINA_KEY))
{
if (key != null)
{
object value = key.GetValue("GinaDLL");
return value != null;
}
else
{
return false;
}
}
}
public override bool Registered6432()
{
return true;
}
public override bool Enabled()
{
dynamic pGinaSettings = new pGinaDynamicSettings();
bool passthru = pGinaSettings.GetSetting("GinaPassthru", false);
return !passthru;
}
public override bool Enabled6432()
{
return true;
}
}
public class DefaultCredProviderManager : CredProviderManager
{
/*
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers\{**GUID**}]
@="pGinaCredentialProvider"
[HKEY_CLASSES_ROOT\CLSID\{**GUID**}]
@="pGinaCredentialProvider"
[HKEY_CLASSES_ROOT\CLSID\{**GUID**}\InprocServer32]
@="SampleCredUICredentialProvider.dll"
"ThreadingModel"="Apartment"
*/
private ILog m_logger = LogManager.GetLogger("DefaultCredProviderManager");
static readonly string PROVIDER_KEY_BASE = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers";
static readonly string CP_FILTER_KEY_BASE = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Provider Filters";
static readonly string CLSID_BASE = @"CLSID";
static readonly string PROVIDER_KEY_BASE_6432 = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers";
static readonly string CP_FILTER_KEY_BASE_6432 = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Authentication\Credential Provider Filters";
static readonly string WINDIR = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
// The registry keys
string ProviderKey
{
get { return string.Format(@"{0}\{{{1}}}", PROVIDER_KEY_BASE, CpInfo.ProviderGuid.ToString()); }
}
string CredentialProviderFilterKey
{
get { return string.Format(@"{0}\{{{1}}}", CP_FILTER_KEY_BASE, CpInfo.ProviderGuid.ToString()); }
}
string ClsidRoot
{
get { return string.Format(@"{0}\{{{1}}}", CLSID_BASE, CpInfo.ProviderGuid.ToString()); }
}
string ClsidInProc
{
get { return string.Format(@"{0}\InprocServer32", this.ClsidRoot); }
}
string ProviderKey6432
{
get { return string.Format(@"{0}\{{{1}}}", PROVIDER_KEY_BASE_6432, CpInfo.ProviderGuid.ToString()); }
}
string CredentialProviderFilterKey6432
{
get { return string.Format(@"{0}\{{{1}}}", CP_FILTER_KEY_BASE_6432, CpInfo.ProviderGuid.ToString()); }
}
public DefaultCredProviderManager()
{
// Defaults for pGina Credential Provider
this.CpInfo.ProviderGuid = new Guid("{D0BEFEFB-3D2C-44DA-BBAD-3B2D04557246}");
this.CpInfo.ShortName = "pGinaCredentialProvider";
}
private string GetCpDllPath()
{
return Path.Combine(WINDIR, "System32", CpInfo.ShortName + ".dll");
}
private string GetCpDllPath6432()
{
return Path.Combine(WINDIR, "Syswow64", CpInfo.ShortName + ".dll");
}
public override void Install()
{
m_logger.InfoFormat("Installing credential provider {0} {{{1}}}",
CpInfo.ShortName,
CpInfo.ProviderGuid.ToString());
// Copy the DLL
if (Abstractions.Windows.OsInfo.Is64Bit()) // Are we on a 64 bit OS?
{
FileInfo x64Dll = DllUtils.Find64BitDll(CpInfo.Path, CpInfo.ShortName);
FileInfo x32Dll = DllUtils.Find32BitDll(CpInfo.Path, CpInfo.ShortName);
string destination64 = GetCpDllPath();
string destination32 = GetCpDllPath6432();
if (x64Dll == null && x32Dll == null)
{
throw new Exception("No 64 or 32 bit DLL found in: " + CpInfo.Path);
}
if (x64Dll != null)
{
m_logger.DebugFormat("Found 64 bit DLL: {0}", x64Dll.FullName);
m_logger.DebugFormat(" copying to: {0}", destination64);
File.Copy(x64Dll.FullName, destination64, true);
}
else
{
m_logger.Error("WARNING: No 64 bit DLL found.");
}
if (x32Dll != null)
{
m_logger.DebugFormat("Found 32 bit DLL: {0}", x32Dll.FullName);
m_logger.DebugFormat(" copying to: {0}", destination32);
File.Copy(x32Dll.FullName, destination32, true);
// Write registry keys for 32 bit DLL
// The provider
using (RegistryKey key = Registry.LocalMachine.CreateSubKey(this.ProviderKey6432))
{
key.SetValue("", CpInfo.ShortName);
}
// The provider filter
using (RegistryKey key = Registry.LocalMachine.CreateSubKey(this.CredentialProviderFilterKey6432))
{
key.SetValue("", CpInfo.ShortName);
}
}
else
{
m_logger.Error("WARNING: No 32 bit DLL found.");
}
}
else
{
FileInfo x32Dll = DllUtils.Find32BitDll(CpInfo.Path, CpInfo.ShortName);
string destination = GetCpDllPath();
if (x32Dll != null)
{
m_logger.DebugFormat("Found 32 bit DLL: {0}", x32Dll.FullName);
m_logger.DebugFormat(" copying to: {0}", destination);
File.Copy(x32Dll.FullName, destination, true);
}
else
{
throw new Exception("No 32 bit DLL found in: " + CpInfo.Path);
}
}
m_logger.Debug("Writing registry entries...");
// Write registry values
using (RegistryKey key = Registry.LocalMachine.CreateSubKey(this.ProviderKey))
{
m_logger.DebugFormat("{0} @=> {1}", key.ToString(), CpInfo.ShortName);
key.SetValue("", CpInfo.ShortName);
}
using (RegistryKey key = Registry.LocalMachine.CreateSubKey(this.CredentialProviderFilterKey))
{
m_logger.DebugFormat("{0} @=> {1}", key.ToString(), CpInfo.ShortName);
key.SetValue("", CpInfo.ShortName);
}
using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(this.ClsidRoot))
{
m_logger.DebugFormat("{0} @=> {1}", key.ToString(), CpInfo.ShortName);
key.SetValue("", CpInfo.ShortName);
}
using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(this.ClsidInProc))
{
m_logger.DebugFormat("{0} @=> {1}", key.ToString(), CpInfo.ShortName);
key.SetValue("", CpInfo.ShortName);
m_logger.DebugFormat("{0} {1} => {2}", key.ToString(), "ThreadingModel", "Apartment");
key.SetValue("ThreadingModel", "Apartment");
}
}
public override void Uninstall()
{
m_logger.InfoFormat("Uninstalling credential provider {0} {{{1}}}",
CpInfo.ShortName,
CpInfo.ProviderGuid.ToString());
string dll = GetCpDllPath();
string dll6432 = GetCpDllPath6432();
if (File.Exists(dll))
{
m_logger.DebugFormat("Deleting: {0}", dll);
File.Delete(dll);
}
if (File.Exists(dll6432))
{
m_logger.DebugFormat("Deleting: {0}", dll6432);
File.Delete(dll6432);
}
string guid = "{" + CpInfo.ProviderGuid.ToString() + "}";
DeleteRegistryKey(Registry.LocalMachine, PROVIDER_KEY_BASE, guid);
DeleteRegistryKey(Registry.LocalMachine, CP_FILTER_KEY_BASE, guid);
DeleteRegistryKey(Registry.LocalMachine, PROVIDER_KEY_BASE_6432, guid);
DeleteRegistryKey(Registry.LocalMachine, CP_FILTER_KEY_BASE_6432, guid);
DeleteRegistryKey(Registry.ClassesRoot, CLSID_BASE, string.Format("{0}\\{1}", guid, "InprocServer32"));
DeleteRegistryKey(Registry.ClassesRoot, CLSID_BASE, guid);
}
private void DeleteRegistryKey(RegistryKey baseKey, string parentSubKey, string childSubKey)
{
using (RegistryKey key = baseKey.OpenSubKey(parentSubKey, true))
{
if (key != null)
{
m_logger.DebugFormat("Deleting {0}\\{1}", key.ToString(), childSubKey);
key.DeleteSubKey(childSubKey,false);
}
}
}
public override void Disable()
{
m_logger.InfoFormat("Disabling credential provider: {0} {{{1}}}",
CpInfo.ShortName,
CpInfo.ProviderGuid.ToString());
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(this.ProviderKey, true))
{
if (key != null)
{
m_logger.DebugFormat("Writing {0}: {1} => {2}", key.ToString(), "Disabled", 1);
key.SetValue("Disabled", 1);
}
else
{
m_logger.Error("WARNING: No credential provider registry entry found for that GUID.");
}
}
if (Abstractions.Windows.OsInfo.Is64Bit())
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(this.ProviderKey6432, true))
{
if (key != null)
{
m_logger.DebugFormat("Writing {0}: {1} => {2}", key.ToString(), "Disabled", 1);
key.SetValue("Disabled", 1);
}
else
{
m_logger.Error("WARNING: No 32-bit registry entry found with that GUID.");
}
}
}
}
public override void Enable()
{
m_logger.InfoFormat("Enabling credential provider: {0} {{{1}}}",
CpInfo.ShortName,
CpInfo.ProviderGuid.ToString());
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(this.ProviderKey, true))
{
if (key != null)
{
m_logger.DebugFormat("Deleting {0}: {1}", key.ToString(), "Disabled");
if (key.GetValue("Disabled") != null)
key.DeleteValue("Disabled");
}
else
{
m_logger.Error("WARNING: Did not find a registry entry for that GUID.");
}
}
if (Abstractions.Windows.OsInfo.Is64Bit())
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(this.ProviderKey6432, true))
{
if (key != null)
{
m_logger.DebugFormat("Deleting {0}: {1}", key.ToString(), "Disabled");
if (key.GetValue("Disabled") != null)
key.DeleteValue("Disabled");
}
else
{
m_logger.Error("WARNING: Did not find a (32 bit) registry entry for that GUID.");
}
}
}
}
public override bool Registered()
{
bool result = false;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(this.ProviderKey))
{
if (key != null)
result = true;
}
return result;
}
public override bool Enabled()
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(this.ProviderKey))
{
if (key == null) return false;
object value = key.GetValue("Disabled");
if (value == null) return true;
else
{
return (int)value == 0;
}
}
}
public override bool Registered6432()
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(this.ProviderKey6432))
{
return key != null;
}
}
public override bool Enabled6432()
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(this.ProviderKey6432))
{
if (key == null) return false;
object value = key.GetValue("Disabled");
if (value == null) return true;
else
{
return (int)value == 0;
}
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.ServiceProcess;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Reflection;
using Microsoft.Win32;
using log4net;
using System.Configuration.Install;
namespace pGina.InstallUtil
{
class Program
{
static readonly string PGINA_SERVICE_NAME = "pGina";
static readonly string PGINA_SERVICE_EXE = "pGina.Service.ServiceHost.exe";
static readonly string PGINA_CONFIG_EXE = "pGina.Configuration.exe";
// Initalized in the static constructor
static readonly SecurityIdentifier ADMIN_GROUP;
static readonly SecurityIdentifier USERS_GROUP;
static readonly SecurityIdentifier SYSTEM_ACCT;
static readonly SecurityIdentifier AUTHED_USERS;
private static readonly string INSTALL_UTIL_PATH;
private static readonly string PGINA_SERVICE_FULL_PATH;
static Program()
{
// Init logging
pGina.Shared.Logging.Logging.Init();
// Intialize readonly variables
PGINA_SERVICE_FULL_PATH = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), PGINA_SERVICE_EXE);
INSTALL_UTIL_PATH = Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(),
"installutil.exe");
ADMIN_GROUP = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
USERS_GROUP = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
SYSTEM_ACCT = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
AUTHED_USERS = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
}
static ILog m_logger = LogManager.GetLogger("pGina.InstallUtil");
static int Main(string[] args)
{
if (args.Length == 0)
{
m_logger.Error("Missing argument. Must be one of \"post-install\" or \"post-uninstall\".");
return 1;
}
try
{
if (args[0].Equals("post-install", StringComparison.CurrentCultureIgnoreCase))
{
DoPostInstall();
}
else if (args[0].Equals("post-uninstall", StringComparison.CurrentCultureIgnoreCase))
{
DoPostUninstall();
}
else
{
m_logger.ErrorFormat("Unrecognzied action: {0}", args[0]);
return 1;
}
}
catch (Exception e)
{
m_logger.ErrorFormat("Exception occured: {0}", e);
return 1;
}
return 0;
}
private static void DoPostInstall()
{
SetRegistryAcls();
InstallAndStartService();
RegisterAndEnableCredentialProvider();
// Probably not necessary or useful...
//SetFileSystemAcls();
}
private static void DoPostUninstall()
{
// Uninstall service
if (ServiceInstalled())
{
StopService();
UninstallService();
}
else
{
m_logger.Info("pGina service is not installed, skipping uninstall.");
}
// Uninstall CP
UninstallCredentialProvider();
}
private static void SetFileSystemAcls()
{
if (!File.Exists(PGINA_CONFIG_EXE))
{
throw new Exception(string.Format("Unable to find configuration executable: {0}", PGINA_CONFIG_EXE));
}
m_logger.InfoFormat("Setting ACLs on {0}", PGINA_CONFIG_EXE);
FileSystemAccessRule userReadAndExecute = new FileSystemAccessRule(USERS_GROUP, FileSystemRights.ReadAndExecute, AccessControlType.Allow);
FileSystemAccessRule userRead = new FileSystemAccessRule(USERS_GROUP, FileSystemRights.Read, AccessControlType.Allow);
FileSystemAccessRule adminFull = new FileSystemAccessRule(ADMIN_GROUP, FileSystemRights.FullControl, AccessControlType.Allow);
FileSystemAccessRule systemFull = new FileSystemAccessRule(SYSTEM_ACCT, FileSystemRights.FullControl, AccessControlType.Allow);
FileSystemAccessRule authedUsersMod = new FileSystemAccessRule(AUTHED_USERS, FileSystemRights.Modify, AccessControlType.Allow);
FileSystemAccessRule usersMod = new FileSystemAccessRule(USERS_GROUP, FileSystemRights.Modify, AccessControlType.Allow);
FileSecurity fs = File.GetAccessControl(PGINA_CONFIG_EXE);
fs.SetAccessRuleProtection(true, false);
fs.RemoveAccessRuleAll(authedUsersMod);
fs.RemoveAccessRuleAll(usersMod);
fs.AddAccessRule(userReadAndExecute);
fs.AddAccessRule(adminFull);
fs.AddAccessRule(systemFull);
File.SetAccessControl(PGINA_CONFIG_EXE, fs);
}
private static void SetRegistryAcls()
{
string pGinaSubKey = pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot;
using (RegistryKey key = Registry.LocalMachine.CreateSubKey(pGinaSubKey))
{
if (key != null)
{
m_logger.InfoFormat("Setting ACLs on {0}", key.Name);
RegistryAccessRule allowRead = new RegistryAccessRule(
USERS_GROUP, RegistryRights.ReadKey,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None, AccessControlType.Allow);
RegistryAccessRule adminFull = new RegistryAccessRule(
ADMIN_GROUP, RegistryRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None, AccessControlType.Allow);
RegistryAccessRule systemFull = new RegistryAccessRule(
SYSTEM_ACCT, RegistryRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None, AccessControlType.Allow);
RegistrySecurity keySec = key.GetAccessControl();
if (m_logger.IsDebugEnabled)
{
m_logger.DebugFormat("{0} before update:", key.Name);
ShowSecurity(keySec);
}
// Remove inherited rules
keySec.SetAccessRuleProtection(true, false);
// Add full control for administrators and system.
keySec.AddAccessRule(adminFull);
keySec.AddAccessRule(systemFull);
// Remove any read rules for users (if they exist)
keySec.RemoveAccessRuleAll(allowRead);
// Apply the rules..
key.SetAccessControl(keySec);
if (m_logger.IsDebugEnabled)
{
m_logger.DebugFormat("{0} after update: ", key.Name);
ShowSecurity(keySec);
}
}
}
}
private static void RegisterAndEnableCredentialProvider()
{
pGina.CredentialProvider.Registration.CredProviderManager cpManager =
pGina.CredentialProvider.Registration.CredProviderManager.GetManager();
m_logger.Info("Registering CP/GINA....");
cpManager.CpInfo.OpMode = CredentialProvider.Registration.OperationMode.INSTALL;
cpManager.ExecuteDefaultAction();
m_logger.Info("Enabling CP/GINA...");
cpManager.CpInfo.OpMode = CredentialProvider.Registration.OperationMode.ENABLE;
cpManager.ExecuteDefaultAction();
}
private static void UninstallCredentialProvider()
{
pGina.CredentialProvider.Registration.CredProviderManager cpManager =
pGina.CredentialProvider.Registration.CredProviderManager.GetManager();
m_logger.Info("Uninstalling CP/GINA....");
cpManager.CpInfo.OpMode = CredentialProvider.Registration.OperationMode.UNINSTALL;
cpManager.ExecuteDefaultAction();
}
private static void InstallAndStartService()
{
if (!File.Exists(PGINA_SERVICE_EXE))
{
throw new Exception("The service executable was not found.");
}
if (ServiceInstalled())
{
m_logger.Warn("Service already installed, re-installing.");
StopService();
UninstallService();
}
InstallService();
StartService();
}
private static bool ServiceInstalled()
{
using (ServiceController pGinaService = GetServiceController())
{
return pGinaService != null;
}
}
private static void StopService()
{
using (ServiceController pGinaService = GetServiceController())
{
if (pGinaService != null)
{
if (pGinaService.Status == ServiceControllerStatus.Running)
{
m_logger.InfoFormat("Stopping pGina service...");
pGinaService.Stop();
}
}
else
throw new Exception("pGina service not installed");
}
}
private static void StartService()
{
using (ServiceController pGinaService = GetServiceController())
{
if (pGinaService != null)
{
if ( pGinaService.Status != ServiceControllerStatus.Running )
{
m_logger.InfoFormat("Starting pGina service...");
pGinaService.Start();
}
}
else
throw new Exception("pGina service not installed");
}
}
private static void UninstallService()
{
m_logger.InfoFormat("Uninstalling pGina service...");
// If we can find the .NET installutil.exe, run that, otherwise, use
// ManagedInstallerClass (not recommended by MSDN, but works).
if (File.Exists(INSTALL_UTIL_PATH))
{
// Need quotes around the path when calling installutil.exe
string[] args = { "/u", string.Format("\"{0}\"", PGINA_SERVICE_FULL_PATH) };
// Call the .NET installutil.exe
CallInstallUtil(args);
}
else
{
m_logger.DebugFormat("Can't find .NET installutil.exe ({0}), trying ManagedInstallerClass.InstallHelper", INSTALL_UTIL_PATH);
ManagedInstallerClass.InstallHelper(new string[] { "/u", PGINA_SERVICE_FULL_PATH });
}
}
private static void InstallService()
{
m_logger.InfoFormat("Installing pGina service...");
// If we can find the .NET installutil.exe, run that, otherwise, use
// ManagedInstallerClass (not recommended by MSDN, but works).
if (File.Exists(INSTALL_UTIL_PATH))
{
// Need quotes around the path when calling installutil.exe
string[] args = { string.Format( "\"{0}\"", PGINA_SERVICE_FULL_PATH ) };
// Call the .NET installutil.exe
CallInstallUtil(args);
}
else
{
m_logger.DebugFormat("Can't find .NET installutil.exe ({0}), trying ManagedInstallerClass.InstallHelper", INSTALL_UTIL_PATH);
ManagedInstallerClass.InstallHelper(new string[] {PGINA_SERVICE_FULL_PATH});
}
}
private static ServiceController GetServiceController()
{
ServiceController pGinaService = null;
foreach (ServiceController ctrl in ServiceController.GetServices())
{
if (ctrl.ServiceName == PGINA_SERVICE_NAME)
{
pGinaService = ctrl;
break;
}
}
return pGinaService;
}
private static void ShowSecurity(RegistrySecurity security)
{
foreach (RegistryAccessRule ar in security.GetAccessRules(true, true, typeof(NTAccount)))
{
m_logger.DebugFormat(" User: {0}", ar.IdentityReference);
m_logger.DebugFormat(" Type: {0}", ar.AccessControlType);
m_logger.DebugFormat(" Rights: {0}", ar.RegistryRights);
m_logger.DebugFormat(" Inheritance: {0}", ar.InheritanceFlags);
m_logger.DebugFormat(" Propagation: {0}", ar.PropagationFlags);
m_logger.DebugFormat(" Inherited? {0}", ar.IsInherited);
}
}
private static void CallInstallUtil(string[] args)
{
Process proc = new Process();
proc.StartInfo.FileName = INSTALL_UTIL_PATH;
proc.StartInfo.Arguments = String.Join(" ", args);
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived);
proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit();
// ---check result---
if (proc.ExitCode != 0)
{
throw new Exception(String.Format("InstallUtil error -- code {0}", proc.ExitCode));
}
}
static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
m_logger.Info(e.Data);
}
static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
m_logger.Error(e.Data);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
namespace proquota
{
static class Program
{
public static string uPath = "";
public static long uPath_size_max;
private static EventLog evntlog = new EventLog();
private static string logging = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\quota.log";
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static int Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
if (args.Length != 2)
{
Program.Log("Parameter error:\nI need two parameters", EventLogEntryType.Error);
return 1;
}
if (!System.IO.Directory.Exists(args[0]))
{
Program.Log(String.Format("Parameter error:\nCan't find:{0}", args[0]), EventLogEntryType.Error);
return 2;
}
if (!long.TryParse(args[1], out uPath_size_max))
{
Program.Log(String.Format("Parameter error:\nCan't parse {0} to long", args[1]), EventLogEntryType.Error);
Application.Exit();
}
if (uPath_size_max <= 10 * 1024)
{
Program.Log(String.Format("{0} is less or equal {1}\nQuota limit to low", args[1], 10 * 1024), EventLogEntryType.Warning);
Application.Exit();
}
uPath = args[0];
evntlog.Source = "proquota";
evntlog.Log = "Application";
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
return 0;
}
public static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args)
{
Exception e = args.ExceptionObject as Exception;
Log(String.Format("CurrentDomain_UnhandledException:\n{0}", e.ToString()), EventLogEntryType.Error);
Application.Exit();
}
public static void Log(string text, EventLogEntryType type)
{
evntlog.WriteEntry(text, type);
/*lock (evntlog)
{
System.IO.File.AppendAllText(logging, String.Format("{0:HH:mm:ss.ff} {1}{2}", DateTime.UtcNow,text, Environment.NewLine));
}*/
}
}
}
<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <Windows.h>
#include <vector>
namespace pGina
{
namespace Memory
{
class ObjectCleanupBase
{
public:
ObjectCleanupBase(void * memory) : m_memory(memory) {}
virtual ~ObjectCleanupBase() {}
protected:
void * m_memory;
};
class FreeCleanup : public ObjectCleanupBase
{
public:
FreeCleanup(void *memory) : ObjectCleanupBase(memory) {}
virtual ~FreeCleanup()
{
if(m_memory)
free(m_memory);
}
};
class DeleteCleanup : public ObjectCleanupBase
{
public:
DeleteCleanup(void *memory) : ObjectCleanupBase(memory) {}
virtual ~DeleteCleanup()
{
if(m_memory)
delete m_memory;
}
};
class LocalFreeCleanup : public ObjectCleanupBase
{
public:
LocalFreeCleanup(void *memory) : ObjectCleanupBase(memory) {}
virtual ~LocalFreeCleanup()
{
if(m_memory)
LocalFree(m_memory);
}
};
class CoTaskMemFreeCleanup : public ObjectCleanupBase
{
public:
CoTaskMemFreeCleanup(void *memory) : ObjectCleanupBase(memory) {}
virtual ~CoTaskMemFreeCleanup()
{
if(m_memory)
CoTaskMemFree(m_memory);
}
};
class ObjectCleanupPool
{
public:
ObjectCleanupPool() {}
~ObjectCleanupPool()
{
for(std::vector<ObjectCleanupBase *>::iterator itr = m_cleanupVector.begin(); itr != m_cleanupVector.end(); ++itr)
{
delete *itr;
}
m_cleanupVector.clear();
}
void AddFree(void *mem)
{
if(mem)
{
Add(new FreeCleanup(mem));
}
}
void Add(void *obj)
{
Add(new DeleteCleanup(obj));
}
void Add(ObjectCleanupBase *obj)
{
if(obj)
{
m_cleanupVector.push_back(obj);
}
}
private:
std::vector<ObjectCleanupBase *> m_cleanupVector;
};
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include <windows.h>
#include <stdio.h>
#include <assert.h>
#include <lm.h>
#include <WtsApi32.h>
#include "Helpers.h"
namespace pGina
{
namespace Helpers
{
std::wstring GetMachineName()
{
WCHAR computerName[MAX_COMPUTERNAME_LENGTH+1];
DWORD computerNameLen = ARRAYSIZE(computerName);
if (!GetComputerNameW(computerName, &computerNameLen))
return L".";
else
return computerName;
}
bool UserIsRemote()
{
return 0 != GetSystemMetrics(SM_REMOTESESSION);
}
bool IsUserLocalAdmin(std::wstring username)
{
bool result = false;
LPUSER_INFO_3 userInfo;
if(NetUserGetInfo(NULL, username.c_str(), 3, (LPBYTE *)&userInfo) == NERR_Success)
{
result = (userInfo->usri3_priv == USER_PRIV_ADMIN);
NetApiBufferFree(userInfo);
}
return result;
}
std::wstring GetSessionUsername(DWORD sessionId)
{
std::wstring result;
LPWSTR buffer = NULL;
DWORD bufferSize = 0;
if(WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, sessionId, WTSUserName, &buffer, &bufferSize))
{
result = buffer;
WTSFreeMemory(buffer);
}
return result;
}
std::wstring GetSessionDomainName(DWORD sessionId)
{
std::wstring result;
LPWSTR buffer = NULL;
DWORD bufferSize = 0;
if(WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, sessionId, WTSDomainName, &buffer, &bufferSize))
{
result = buffer;
WTSFreeMemory(buffer);
}
return result;
}
DWORD GetCurrentSessionId()
{
DWORD sessionId = -1;
ProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
return sessionId;
}
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using log4net;
using pGina.Shared.Interfaces;
using pGina.Shared.Types;
using pGina.Shared.Settings;
using Abstractions.WindowsApi;
namespace pGina.Plugin.SessionLimit
{
public class PluginImpl : IPluginConfiguration, IPluginEventNotifications
{
private ILog m_logger = LogManager.GetLogger("SessionLimitPlugin");
private Timer m_timer;
private SessionCache m_cache;
#region Init-plugin
public static Guid PluginUuid
{
get { return new Guid("{D73131D7-7AF2-47BB-BBF4-4F8583B44962}"); }
}
public PluginImpl()
{
using (Process me = Process.GetCurrentProcess())
{
Settings.Init();
m_logger.DebugFormat("Plugin initialized on {0} in PID: {1} Session: {2}", Environment.MachineName, me.Id, me.SessionId);
}
}
public string Name
{
get { return "Session Limit"; }
}
public string Description
{
get { return "Enforces limits to user's sessions"; }
}
public string Version
{
get
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public Guid Uuid
{
get { return PluginUuid; }
}
#endregion
public Boolean LogoffRequestAddTime()
{
Stopping();
return false;
}
public Boolean LoginUserRequest(string username)
{
return false;
}
private void StartTimer()
{
m_logger.Debug("Starting timer");
m_timer = new Timer(new TimerCallback(SessionLimitTimerCallback), null, TimeSpan.FromSeconds(0),
TimeSpan.FromSeconds(60));
}
private void StopTimer()
{
m_logger.Debug("Stopping timer");
m_timer.Dispose();
m_timer = null;
}
private void SessionLimitTimerCallback(object state)
{
int limit = Settings.Store.GlobalLimit;
if (limit > 0)
{
m_logger.Debug("Checking for sessions to logoff");
List<int> sessions = m_cache.SessionsLoggedOnLongerThan(TimeSpan.FromMinutes(limit));
m_logger.DebugFormat("Found {0} sessions.", sessions.Count);
foreach (int sess in sessions)
{
m_logger.DebugFormat("Logging off session {0}", sess);
bool result = Abstractions.WindowsApi.pInvokes.LogoffSession(sess);
if (result)
m_logger.Debug("Log off successful.");
else
m_logger.Debug("Log off failed.");
}
}
}
public void Configure()
{
Configuration conf = new Configuration();
conf.ShowDialog();
}
public void Starting()
{
m_cache = new SessionCache();
StartTimer();
}
public void Stopping()
{
StopTimer();
m_cache = null;
}
public void SessionChange(int SessionId, System.ServiceProcess.SessionChangeReason Reason, SessionProperties properties)
{
// Only applies to pGina sessions!
if (properties != null)
{
switch (Reason)
{
case System.ServiceProcess.SessionChangeReason.SessionLogon:
LogonEvent(SessionId);
break;
case System.ServiceProcess.SessionChangeReason.SessionLogoff:
LogoffEvent(SessionId);
break;
}
}
}
private void LogonEvent(int sessId)
{
m_logger.DebugFormat("LogonEvent: {0}", sessId);
m_cache.Add(sessId);
}
private void LogoffEvent(int sessId)
{
m_logger.DebugFormat("LogoffEvent: {0}", sessId);
m_cache.Remove(sessId);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace pGina.Plugin.Kerberos
{
public partial class Configuration : Form
{
public Configuration()
{
InitializeComponent();
SettingsToUi();
}
private void SettingsToUi()
{
string Realm_str = Settings.Store.Realm;
this.rText.Text = Realm_str;
}
private void UiToSettings()
{
Settings.Store.Realm = this.rText.Text.Trim();
}
private void save_Click(object sender, EventArgs e)
{
this.UiToSettings();
this.Close();
}
private void cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void Btn_help(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/kerberos.html");
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web.Script.Serialization;
namespace pGina.Plugin.MultiEmail
{
public partial class Configuration : Form
{
private static string popSslPort = "995";
private static string popPort = "110";
private static string imapPort = "143";
private static string imapSslPort = "993";
private string[] m_protocolOptions;
private BindingList<ServersList> m_servers;
private JavaScriptSerializer m_jsonSerializer = new JavaScriptSerializer();
public Configuration()
{
InitializeComponent();
InitUi();
LoadSettings();
}
private void InitUi()
{
m_protocolOptions = new string[]
{
ServersList.ProtocolOption.POP3.ToString(),
ServersList.ProtocolOption.IMAP.ToString()
};
protocolComboBox.Items.AddRange(m_protocolOptions);
protocolComboBox.SelectedIndex = 1;
DisableAndClearAllEditFields();
m_serversListDgv.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = "Protocol",
DataPropertyName = "Protocol",
HeaderText = "Protocol",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
ReadOnly = true
});
m_serversListDgv.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = "Server",
DataPropertyName = "Server",
HeaderText = "Server",
AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
ReadOnly = true
});
m_serversListDgv.Columns.Add(new DataGridViewCheckBoxColumn()
{
Name = "UseSsl",
DataPropertyName = "UseSsl",
HeaderText = "SSL",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
ReadOnly = true
});
m_serversListDgv.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = "Port",
DataPropertyName = "Port",
HeaderText = "Port",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
ReadOnly = true
});
m_serversListDgv.Columns.Add(new DataGridViewCheckBoxColumn()
{
Name = "AppendDomain",
DataPropertyName = "AppendDomain",
HeaderText = "Append",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
ReadOnly = true
});
m_serversListDgv.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = "Domain",
DataPropertyName = "Domain",
HeaderText = "Domain",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
ReadOnly = true
});
m_serversListDgv.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = "Timeout",
DataPropertyName = "Timeout",
HeaderText = "Timeout",
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
ReadOnly = true
});
m_serversListDgv.RowValidating += m_serversListDgv_RowValidating;
m_serversListDgv.SelectionChanged += m_serversListDgv_SelectionChanged;
protocolComboBox.LostFocus += protocolComboBox_LostFocus;
serverTextBox.LostFocus += serverTextBox_LostFocus;
portTextBox.LostFocus += portTextBox_LostFocus;
domainTextBox.LostFocus += domainTextBox_LostFocus;
timeoutTextBox.LostFocus += timeoutTextBox_LostFocus;
portTextBox.Validating += portTextBox_Validating;
}
private void EnableEditFields()
{
protocolLabel.Enabled = true;
protocolComboBox.Enabled = true;
serverLabel.Enabled = true;
serverTextBox.Enabled = true;
portLabel.Enabled = true;
portTextBox.Enabled = true;
sslCheckBox.Enabled = true;
appendDomainCheckBox.Enabled = true;
if (appendDomainCheckBox.Checked == true)
{
domainLabel.Enabled = true;
domainTextBox.Enabled = true;
}
else
{
domainLabel.Enabled = false;
domainTextBox.Enabled = false;
}
timeoutLabel.Enabled = true;
timeoutTextBox.Enabled = true;
}
private void SetEditFields(ServersList server)
{
protocolComboBox.SelectedItem = server.Protocol.ToString();
serverTextBox.Text = server.Server;
portTextBox.Text = server.Port;
if (server.UseSsl == true)
sslCheckBox.Checked = true;
else
sslCheckBox.Checked = false;
if (server.AppendDomain == false)
appendDomainCheckBox.Checked = false;
else
appendDomainCheckBox.Checked = true;
domainTextBox.Text = server.Domain;
timeoutTextBox.Text = server.Timeout;
}
private void DisableAndClearAllEditFields()
{
protocolLabel.Enabled = false;
protocolComboBox.Enabled = false;
serverLabel.Enabled = false;
serverTextBox.Enabled = false;
serverTextBox.Text = "";
portLabel.Enabled = false;
portTextBox.Enabled = false;
sslCheckBox.Enabled = false;
appendDomainCheckBox.Enabled = false;
domainLabel.Enabled = false;
domainTextBox.Enabled = false;
timeoutLabel.Enabled = false;
timeoutTextBox.Enabled = false;
}
private void LoadSettings()
{
string jsonData = Settings.Store.Servers.ToString();
List<ServersList> servers = new List<ServersList>();
if (!String.IsNullOrEmpty(jsonData))
{
servers = m_jsonSerializer.Deserialize<List<ServersList>>(jsonData);
}
m_servers = new BindingList<ServersList>(servers);
m_serversListDgv.DataSource = m_servers;
}
void protocolComboBox_LostFocus(object sender, EventArgs e)
{
if (m_serversListDgv.SelectedRows.Count > 0)
{
DataGridViewRow row = m_serversListDgv.SelectedRows[0];
int idx = row.Index;
ServersList server = (ServersList)row.DataBoundItem;
server.Protocol = (ServersList.ProtocolOption)Enum.Parse(typeof(ServersList.ProtocolOption), protocolComboBox.SelectedItem.ToString());
m_servers.ResetItem(idx);
}
}
void serverTextBox_LostFocus(object sender, EventArgs e)
{
if (m_serversListDgv.SelectedRows.Count > 0)
{
DataGridViewRow row = m_serversListDgv.SelectedRows[0];
int idx = row.Index;
ServersList server = (ServersList)row.DataBoundItem;
server.Server = serverTextBox.Text;
m_servers.ResetItem(idx);
}
}
void portTextBox_LostFocus(object sender, EventArgs e)
{
if (m_serversListDgv.SelectedRows.Count > 0)
{
DataGridViewRow row = m_serversListDgv.SelectedRows[0];
int idx = row.Index;
ServersList server = (ServersList)row.DataBoundItem;
server.Port = portTextBox.Text;
m_servers.ResetItem(idx);
}
}
void domainTextBox_LostFocus(object sender, EventArgs e)
{
if (m_serversListDgv.SelectedRows.Count > 0)
{
DataGridViewRow row = m_serversListDgv.SelectedRows[0];
int idx = row.Index;
ServersList server = (ServersList)row.DataBoundItem;
server.Domain = domainTextBox.Text;
m_servers.ResetItem(idx);
}
}
void timeoutTextBox_LostFocus(object sender, EventArgs e)
{
if (m_serversListDgv.SelectedRows.Count > 0)
{
DataGridViewRow row = m_serversListDgv.SelectedRows[0];
int idx = row.Index;
ServersList server = (ServersList)row.DataBoundItem;
server.Timeout = timeoutTextBox.Text;
m_servers.ResetItem(idx);
}
}
void m_serversListDgv_SelectionChanged(object sender, EventArgs e)
{
int numRowsSelected = m_serversListDgv.SelectedRows.Count;
if (numRowsSelected == 0)
DisableAndClearAllEditFields();
else
{
DataGridViewRow row = m_serversListDgv.SelectedRows[0];
ServersList server = (ServersList)row.DataBoundItem;
SetEditFields(server);
EnableEditFields();
}
}
private void m_serversListDgv_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
// MessageBox.Show(m_serversListDgv.CurrentRow.Index.ToString());
if (m_serversListDgv.Focused == true)
if (! validateFields())
e.Cancel = true;
}
private void protocolComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (protocolComboBox.SelectedItem.ToString() == ServersList.ProtocolOption.POP3.ToString())
portTextBox.Text = (sslCheckBox.Checked ? popSslPort : popPort);
else
portTextBox.Text = (sslCheckBox.Checked ? imapSslPort : imapPort);
portTextBox_LostFocus(sender, e);
}
private void sslCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (protocolComboBox.SelectedItem.ToString() == ServersList.ProtocolOption.POP3.ToString())
portTextBox.Text = (sslCheckBox.Checked ? popSslPort : popPort);
else
portTextBox.Text = (sslCheckBox.Checked ? imapSslPort : imapPort);
if (m_serversListDgv.SelectedRows.Count > 0)
{
DataGridViewRow row = m_serversListDgv.SelectedRows[0];
int idx = row.Index;
ServersList server = (ServersList)row.DataBoundItem;
if (sslCheckBox.Checked == true)
server.UseSsl = true;
else
server.UseSsl = false;
portTextBox_LostFocus(sender,e);
m_servers.ResetItem(idx);
}
}
private void serverTextBox_TextChanged(object sender, EventArgs e)
{
if (m_serversListDgv.SelectedRows.Count > 0 && serverTextBox.Text.Trim().Length == 0)
{
MessageBox.Show("Server address can not be blank.");
}
}
private void portTextBox_Validating(object sender, CancelEventArgs e)
{
try
{
int port = Convert.ToInt32(portTextBox.Text);
if (port < 0) throw new FormatException();
}
catch (FormatException)
{
MessageBox.Show("Port must be an integer greater than 0.");
e.Cancel = true;
}
}
private void domainAppendCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (appendDomainCheckBox.Checked)
{
domainLabel.Enabled = true;
domainTextBox.Enabled = true;
}
else
{
domainLabel.Enabled = false;
domainTextBox.Enabled = false;
}
if (m_serversListDgv.SelectedRows.Count > 0)
{
DataGridViewRow row = m_serversListDgv.SelectedRows[0];
int idx = row.Index;
ServersList server = (ServersList)row.DataBoundItem;
if (appendDomainCheckBox.Checked == true)
server.AppendDomain = true;
else
server.AppendDomain = false;
m_servers.ResetItem(idx);
}
}
private void domainTextBox_TextChanged(object sender, EventArgs e)
{
if (appendDomainCheckBox.Checked && domainTextBox.Text.Trim().Length == 0)
{
MessageBox.Show("A domain must be entered if \"Append domain to username\" is checked.");
}
}
private void newServerButton_Click(object sender, EventArgs e)
{
if (validateFields())
{
ServersList server = new ServersList();
m_servers.Add(server);
protocolComboBox_SelectedIndexChanged(sender, e);
m_serversListDgv.Rows[m_serversListDgv.Rows.Count - 1].Selected = true;
m_serversListDgv.CurrentCell = m_serversListDgv.Rows[m_serversListDgv.Rows.Count - 1].Cells[0];
}
}
private void m_deleteServerButton_Click(object sender, EventArgs e)
{
int numRowsSelected = m_serversListDgv.SelectedRows.Count;
if (numRowsSelected > 0)
{
m_servers.RemoveAt(m_serversListDgv.SelectedRows[0].Index);
}
}
private void m_saveCloseButton_Click(object sender, EventArgs e)
{
if (validateFields())
{
List<ServersList> servers = m_servers.ToList<ServersList>();
Settings.Store.Servers = m_jsonSerializer.Serialize(servers).ToString();
this.Close();
}
}
private void m_cancelButton_Click(object sender, EventArgs e)
{
this.Close();
}
private Boolean validateFields()
{
Boolean state = true;
if (m_serversListDgv.SelectedRows.Count > 0 && (serverTextBox.Text.Trim().Length == 0 || (appendDomainCheckBox.Checked && domainTextBox.Text.Trim().Length == 0)))
{
state = false;
if (serverTextBox.Text.Trim().Length == 0)
MessageBox.Show("Server address can not be blank.");
if (appendDomainCheckBox.Checked && domainTextBox.Text.Trim().Length == 0)
MessageBox.Show("A domain must be entered if \"Append domain to username\" is checked.");
}
return state;
}
private void btnOk_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
private void settingsChanged(object sender, EventArgs e)
{
updateSettings();
}
private void updateSettings()
{
domainLabel.Enabled = appendDomainCheckBox.Checked;
domainTextBox.Enabled = appendDomainCheckBox.Checked;
}
private void Btn_help(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/multiemail.html");
}
}
}
<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <Windows.h>
#include <string>
#include <pGinaMessages.h>
#include <Threading.h>
namespace pGina
{
namespace Transactions
{
class Log
{
public:
static void Debug(const wchar_t *format, ...);
static void Info(const wchar_t *format, ...);
static void Warn(const wchar_t *format, ...);
static void Error(const wchar_t *format, ...);
private:
static void LogInternal(const wchar_t *level, const wchar_t *message);
};
class Service
{
public:
static bool Ping();
};
class User
{
public:
class LoginResult
{
public:
LoginResult()
: m_result(false) {}
LoginResult(bool result, std::wstring const& user, std::wstring const& pass, std::wstring const& domain, std::wstring const& msg)
: m_username(user), m_domain(domain), m_password(pass), m_message(msg), m_result(result) {}
std::wstring Username() { return m_username; }
void Username(std::wstring const& v) { m_username = v; }
std::wstring Password() { return m_password; }
void Password(std::wstring const& v) { m_password = v; }
std::wstring Domain() { return m_domain; }
void Domain(std::wstring const& v) { m_domain = v; }
bool Result() { return m_result; }
void Result(bool v) { m_result = v; }
std::wstring Message() { return m_message; }
void Message(std::wstring const& v) { m_message = v; }
void Clear() {
Username(L""); Password(L""); Domain(L"");
Result(false); Message(L"");
}
private:
std::wstring m_username;
std::wstring m_domain;
std::wstring m_password;
std::wstring m_message;
bool m_result;
};
static LoginResult ProcessLoginForUser(const wchar_t *username, const wchar_t *domain, const wchar_t *password, pGina::Protocol::LoginRequestMessage::LoginReason reason);
static bool LocalLoginForUser(const wchar_t *username, const wchar_t *password);
static LoginResult ProcessChangePasswordForUser( const wchar_t *username, const wchar_t *domain, const wchar_t *oldPassword, const wchar_t *newPassword );
};
/* Generic transaction for receiving some text for a field in the UI. */
class TileUi
{
public:
static std::wstring GetDynamicLabel(const wchar_t *labelName);
};
class LoginInfo
{
public:
class UserInformation
{
public:
std::wstring OriginalUsername() { return m_orig_uname; }
void OriginalUsername(std::wstring const &v) { m_orig_uname = v; }
std::wstring Username() { return m_username; }
void Username(std::wstring const& v) { m_username = v; }
std::wstring Domain() { return m_domain; }
void Domain(std::wstring const& v) { m_domain = v; }
UserInformation() {}
UserInformation(const std::wstring & orig_uname, const std::wstring & uname, const std::wstring& dom):
m_orig_uname(orig_uname), m_username(uname), m_domain(dom) {}
private:
std::wstring m_username;
std::wstring m_domain;
std::wstring m_orig_uname;
};
static UserInformation GetUserInformation( int session_id );
static void Move(const wchar_t *username, const wchar_t *domain, const wchar_t *password, int old_session, int new_session);
};
class ServiceStateThread : public pGina::Threading::Thread
{
public:
typedef void (*NOTIFY_STATE_CHANGE_CALLBACK)(bool newState);
ServiceStateThread();
bool IsServiceRunning();
void SetCallback(NOTIFY_STATE_CHANGE_CALLBACK callback);
protected:
virtual DWORD ThreadMain();
private:
void SetServiceRunning(bool b);
private:
bool m_serviceRunning;
NOTIFY_STATE_CHANGE_CALLBACK m_callback;
};
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
using pGina.Shared.Types;
using log4net;
using System.Text;
using Newtonsoft.Json.Linq;
namespace pGina.Plugin.Cbits
{
public class HttpAccessor
{
private static Dictionary<string, UInfo> resps = new Dictionary<string, UInfo>();
private static ILog m_logger = LogManager.GetLogger("CbitsAccessor");
static HttpAccessor()
{
}
public static BooleanResult getResponse(UserInformation uinfo)
{
try
{
// BEGIN TLS1.2 hack
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
ServicePointManager.DefaultConnectionLimit = 9999;
// END TLS1.2 hack
WebRequest request = WebRequest.Create(Settings.resolveSettings());
request.Method = "POST";
request.Timeout = 5000;
dynamic postObject = new JObject();
postObject.username = uinfo.Username;
postObject.password = <PASSWORD>;
string postData = postObject.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = request.GetResponse())
{
using (Stream dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(dataStream))
{
string responseFromServer = reader.ReadToEnd();
m_logger.InfoFormat("Response: {0}", responseFromServer);
UInfo proc_uinfo = UInfo.parseResponse(responseFromServer);
if (resps.ContainsKey(proc_uinfo.uname))
{
resps.Remove(proc_uinfo.uname);
}
resps.Add(proc_uinfo.uname, proc_uinfo);
uinfo.Username = proc_uinfo.uname;
uinfo.Fullname = proc_uinfo.fullName;
}
}
}
return new BooleanResult() { Success = true };
}
catch(WebException webx)
{
m_logger.ErrorFormat("Accessor.WebException: {0}", webx.Message);
using (HttpWebResponse res = (HttpWebResponse)webx.Response)
{
if (res != null)
{
using (StreamReader resReader = new StreamReader(res.GetResponseStream()))
{
string responseBody = resReader.ReadToEnd();
if (responseBody.Length > 0)
{
String message = ((JObject)JToken.Parse(responseBody)).Value<String>("message");
return new BooleanResult() { Success = false, Message = message };
}
}
}
}
return new BooleanResult() { Success = false, Message = webx.Message };
}
catch (Exception e)
{
// very bad scenario
m_logger.ErrorFormat("Accessor.Exception: {0}", e.StackTrace);
return new BooleanResult() { Success = false, Message = e.Message };
}
}
public static BooleanResult getPwChangeResponse(String uname, String pwd, String old)
{
try
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(Settings.resolveSettings());
// Set the Method property of the request to POST.
request.Method = "POST";
request.Timeout = 2000;
// Create POST data and convert it to a byte array.
string postData = "{\"username\":\"" + uname + "\",\"password\":\"" + pwd + "\",\"old\":\"" + pwd + "\"}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
// Get the response.
using (WebResponse response = request.GetResponse())
{
using (Stream dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
using (StreamReader reader = new StreamReader(dataStream))
{
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
m_logger.InfoFormat("PWDCHResponse: {0}", responseFromServer);
return new BooleanResult() { Success = true, Message = responseFromServer };
}
}
}
}
catch (WebException webx)
{
m_logger.ErrorFormat("PWDCHAccessor.WebException: {0}", webx.Message);
using (HttpWebResponse res = (HttpWebResponse)webx.Response)
{
if (res != null)
{
using (StreamReader resReader = new StreamReader(res.GetResponseStream()))
{
string responseBody = resReader.ReadLine();
if (responseBody.Length > 0)
{
return new BooleanResult() { Success = false, Message = responseBody };
}
}
}
}
return new BooleanResult() { Success = false, Message = webx.Message };
}
catch (Exception e)
{
// very bad scenario
m_logger.ErrorFormat("PWDCHAccessor.Exception: {0}", e.StackTrace);
return new BooleanResult() { Success = false, Message = e.Message };
}
}
public static UInfo getUserInfo(String uname)
{
if (! resps.ContainsKey(uname))
{
return null;
}
return resps[uname];
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include "Threading.h"
namespace pGina
{
namespace Threading
{
Thread::Thread() :
m_threadHandle(0),
m_running(false)
{
}
Thread::~Thread()
{
if(Running())
Stop();
if(m_threadHandle != 0)
CloseHandle(m_threadHandle);
}
void Thread::Start()
{
if(Running())
return;
Running(true);
m_threadHandle = CreateThread(NULL, 0, _internal_threadmain, this, 0, 0);
}
void Thread::Stop()
{
if(!Running())
return;
Running(false);
WaitForSingleObject(m_threadHandle, INFINITE);
CloseHandle(m_threadHandle);
m_threadHandle = 0;
}
bool Thread::Running()
{
ScopedLock lock(m_mutex);
return m_running;
}
void Thread::Running(bool v)
{
ScopedLock lock(m_mutex);
m_running = v;
}
/* static */
DWORD WINAPI Thread::_internal_threadmain(LPVOID arg)
{
Thread *thread = static_cast<Thread *>(arg);
return thread->ThreadMain();
}
Mutex::Mutex()
{
m_mutexHandle = CreateMutex(NULL, FALSE, NULL);
}
bool Mutex::Lock()
{
DWORD res = WaitForSingleObject(m_mutexHandle, INFINITE);
if(res == WAIT_OBJECT_0 || res == WAIT_ABANDONED)
return true;
return false;
}
bool Mutex::Unlock()
{
if(ReleaseMutex(m_mutexHandle))
return true;
return false;
}
}
}<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <Windows.h>
#include <credentialprovider.h>
#include <list>
#include <pGinaTransactions.h>
#include <Threading.h>
#include "TileUiTypes.h"
#include "Credential.h"
#include "Provider.h"
namespace pGina
{
namespace Service
{
class StateHelper
{
public:
static void Start();
static void Stop();
static std::wstring GetStateText();
static bool GetState();
static void AddTarget(pGina::CredProv::Credential *ptr);
static void RemoveTarget(pGina::CredProv::Credential *ptr);
static void AddTarget(pGina::CredProv::Provider *ptr);
static void RemoveTarget(pGina::CredProv::Provider *ptr);
static void NotifyStateChanged(bool newState);
static std::wstring GetUsername();
static std::wstring GetPassword();
static bool GetLoginChangePassword();
static void PushUsername(std::wstring username, std::wstring password, bool Login);
static void StateHelper::SetProvScenario(CREDENTIAL_PROVIDER_USAGE_SCENARIO Scenario);
private:
static pGina::Transactions::ServiceStateThread s_serviceStateThread;
static std::list<pGina::CredProv::Provider *> s_providers;
static std::list<pGina::CredProv::Credential *> s_creds;
static pGina::Threading::Mutex s_mutex;
static std::wstring s_username;
static std::wstring s_password;
static bool s_LoginChangePassword;
};
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pGina.Plugin.SessionLimit
{
class SessionCache
{
Dictionary<int, DateTime> m_cache;
public SessionCache()
{
m_cache = new Dictionary<int, DateTime>();
}
public void Add(int sessId)
{
lock (this)
{
if (m_cache.ContainsKey(sessId))
m_cache[sessId] = DateTime.Now;
else
m_cache.Add(sessId, DateTime.Now);
}
}
public void Remove(int sessId)
{
lock (this)
{
m_cache.Remove(sessId);
}
}
private TimeSpan LoggedInTimeSpan(int sessId)
{
if (m_cache.ContainsKey(sessId))
return DateTime.Now - m_cache[sessId];
else
return TimeSpan.Zero;
}
public List<int> SessionsLoggedOnLongerThan(TimeSpan span)
{
lock (this)
{
List<int> sessionList = new List<int>();
foreach (int sessId in m_cache.Keys)
{
TimeSpan sessSpan = LoggedInTimeSpan(sessId);
if (sessSpan >= span)
{
sessionList.Add(sessId);
}
}
return sessionList;
}
}
}
}
<file_sep>/*
Copyright (c) 2016, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#pragma once
#include <Windows.h>
#include <iostream>
#include <map>
#include "MessageProperty.h"
#include "Buffer.h"
namespace pGina
{
namespace Messaging
{
class Message
{
public:
typedef std::map<std::wstring, PropertyBase *> PropertyMap;
Message();
~Message();
static Message * Demarshal(pGina::Memory::Buffer &buffer);
static Message * Demarshal(pGina::Memory::Buffer *buffer);
static pGina::Memory::Buffer * Marshal(Message *);
template<typename T>
bool Exists(std::wstring const& propertyName)
{
PropertyMap::iterator itr = m_properties.find(propertyName);
if(itr != m_properties.end())
{
pGina::Messaging::Property<T> * prop = dynamic_cast<pGina::Messaging::Property<T> *>(itr->second);
return prop != 0;
}
return false;
}
template<typename T>
T Property(std::wstring const& propertyName)
{
PropertyMap::iterator itr = m_properties.find(propertyName);
if(itr != m_properties.end())
{
pGina::Messaging::Property<T> * prop = static_cast<pGina::Messaging::Property<T> *>(itr->second);
return prop->Value();
}
return T();
}
template<typename T>
void Property(std::wstring const& propertyName, T const& value, PropertyType type)
{
// Create a new property to be inserted
pGina::Messaging::Property<T> * prop = new pGina::Messaging::Property<T>(propertyName, value, type);
// If we already have a property by this name, we need to clean it up
PropertyMap::iterator itr = m_properties.find(propertyName);
if(itr != m_properties.end())
{
PropertyBase * base = itr->second;
delete base;
m_properties.erase(itr);
}
// Insert our new property
m_properties[propertyName] = prop;
}
PropertyMap& Properties() { return m_properties; }
private:
static int MarshalToBuffer(Message *msg, pGina::Memory::Buffer * buffer);
PropertyMap m_properties;
};
}
}<file_sep># SSHAuth plugin
This plugin uses a SSH server for authentication. The plugin connects
to the specified SSH server and attempts to authenticate as the given
user with the "password" authentication method. It is not necessary
for the user to be able to open an actual shell or execute commands on
the SSH server, but note that SSH authentication stage will return
failure if the user shell is set to "/sbin/nologin".
## Known issues
* Does not support the keyboard-interactive authentication method that
many SSH servers offer instead of password authentication.
* Uses the first address returned by getaddrinfo for the SSH server
hostname, so if multiple addresses are returned then it may not
work.
* No support for changing passwords.
## Libraries
This plugin does most of its work in native code, which is built in a
DLL (SSHAuthNative.dll).
Building this DLL requires static libraries for *libssh2* and its
dependencies *OpenSSL* and *Zlib*. Such static libraries are included
in this repository, but alternatively they can be built from source
and moved to the corresponding folders specified in the library
pragma directives of SSHAuthNative.cs before attempting to build this
plugin.
## Author
This SSHAuth plugin for pGina 3.x was developed by <NAME>.
This plugin was inspired by a [pGina 1.x and 2.x plugin also named SSHAuth developed by <NAME>](http://sshauth.sourceforge.net/). However, due to the significant plugin interface changes for pGina 3.x, this plugin was developed from scratch rather than being derived from that codebase.
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace pGina.Plugin.scripting
{
public partial class Configuration : Form
{
public Configuration()
{
InitializeComponent();
LoadSettings();
}
private void SaveSettings()
{
try
{
Settings.Store.authe_sys = Setgridview(this.authentication_sys_grid);
Settings.Store.autho_sys = Setgridview(this.authorization_sys_grid);
Settings.Store.gateway_sys = Setgridview(this.gateway_sys_grid);
Settings.Store.notification_sys = Setgridview(this.notification_sys_grid);
Settings.Store.notification_usr = Setgridview(this.notification_usr_grid);
Settings.Store.changepwd_sys = Setgridview(this.changepwd_sys_grid);
Settings.Store.changepwd_usr = Setgridview(this.changepwd_usr_grid);
}
catch (Exception ex)
{
MessageBox.Show(this, String.Format("scripting plugin\n\n{0}", ex.Message), "can't save settings in registry");
}
}
private void LoadSettings()
{
try
{
Getgridview(this.authentication_sys_grid, (string[])Settings.Store.authe_sys, 2);
Getgridview(this.authorization_sys_grid, (string[])Settings.Store.autho_sys, 2);
Getgridview(this.gateway_sys_grid, (string[])Settings.Store.gateway_sys, 2);
Getgridview(this.notification_sys_grid, (string[])Settings.Store.notification_sys, 4);
Getgridview(this.notification_usr_grid, (string[])Settings.Store.notification_usr, 4);
Getgridview(this.changepwd_sys_grid, (string[])Settings.Store.changepwd_sys, 2);
Getgridview(this.changepwd_usr_grid, (string[])Settings.Store.changepwd_usr, 2);
}
catch (Exception ex)
{
MessageBox.Show(this, String.Format("scripting plugin\n\n{0}", ex.Message), "can't load settings from registry");
}
}
private void help_btn_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://mutonufoai.github.io/pgina/documentation/plugins/scripting.html");
}
private void save_btn_Click(object sender, EventArgs e)
{
SaveSettings();
this.Close();
}
private void close_btn_Click(object sender, EventArgs e)
{
this.Close();
}
private void Getgridview(DataGridView grid, string[] data, int column)
{
List<string> lines = data.ToList();
foreach (string line in lines)
{
string[] split = line.Split('\t');
if (split.Count() == 2 && column == 2)
{
split[0] = split[0].Trim();
split[1] = split[1].Trim();
if (!String.IsNullOrEmpty(split[0]) && !String.IsNullOrEmpty(split[1]))
{
bool pwd = Convert.ToBoolean(split[0]);
string script = split[1];
grid.Rows.Add(pwd, script);
}
}
if (split.Count() == 4 && column == 4)
{
split[0] = split[0].Trim();
split[1] = split[1].Trim();
split[2] = split[2].Trim();
split[3] = split[3].Trim();
if (!String.IsNullOrEmpty(split[0]) && !String.IsNullOrEmpty(split[1]) && !String.IsNullOrEmpty(split[2]) && !String.IsNullOrEmpty(split[3]))
{
bool pwd = Convert.ToBoolean(split[0]);
bool logon = Convert.ToBoolean(split[1]);
bool logoff = Convert.ToBoolean(split[2]);
string script = split[3];
grid.Rows.Add(pwd, logon, logoff, script);
}
}
}
/*
string[] AttribConv = Settings.Store.AttribConv;
grid.DataSource = data;
dataGridView1.ColumnCount = 2;
for (int x = 0; x < AttribConv.Count(); x++)
{
string[] split = AttribConv[x].Split('\t');
if (split.Count() == 2)
{
split[0] = split[0].Trim();
split[1] = split[1].Trim();
if (!String.IsNullOrEmpty(split[0]) && !String.IsNullOrEmpty(split[1]))
{
if (AttribConvert.Attribs.Contains(split[0]))
//if (Array.Exists(WinValues(), element => element == split[0]))
{
int index = AttribConvert.Attribs.IndexOf(split[0]);
//int index = Array.FindIndex(WinValues(), item => item == split[0]);
DataGridViewRow row = new DataGridViewRow();
DataGridViewComboBoxCell CellSample = new DataGridViewComboBoxCell();
CellSample.DataSource = AttribConvert.Attribs.ToArray(); // list of the string items that I want to insert in ComboBox.
CellSample.Value = AttribConvert.Attribs[index]; // default value for the ComboBox
row.Cells.Add(CellSample);
row.Cells.Add(new DataGridViewTextBoxCell()
{
Value = split[1]
});
dataGridView1.Rows.Add(row);
}
}
}
}*/
}
private string[] Setgridview(DataGridView grid)
{
List<string> AttribConv = new List<string>();
foreach (DataGridViewRow row in grid.Rows)
{
string script = "";
string logoff = "";
string logon = "";
string pwd = "";
if (row.Cells.Count == 4)
{
if (row.Cells[3].Value != null)
script = row.Cells[3].Value.ToString().Trim();
if (row.Cells[2].Value != null)
logoff = row.Cells[2].Value.ToString();
else
logoff = false.ToString();
if (row.Cells[1].Value != null)
logon = row.Cells[1].Value.ToString();
else
logon = false.ToString();
if (row.Cells[0].Value != null)
pwd = row.Cells[0].Value.ToString();
else
pwd = false.ToString();
}
if (row.Cells.Count == 2)
{
if (row.Cells[1].Value != null)
script = row.Cells[1].Value.ToString();
if (row.Cells[0].Value != null)
pwd = row.Cells[0].Value.ToString();
else
pwd = false.ToString();
}
if (!string.IsNullOrEmpty(pwd) && !string.IsNullOrEmpty(script))
{
if (!string.IsNullOrEmpty(logoff) && !string.IsNullOrEmpty(logon))
AttribConv.Add(String.Format("{0}\t{1}\t{2}\t{3}", pwd, logon, logoff, script));
else
AttribConv.Add(String.Format("{0}\t{1}", pwd, script));
}
}
if (AttribConv.Count > 0)
{
return AttribConv.ToArray();
}
return new string[] { };
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Pipes;
using Abstractions.Logging;
namespace Abstractions.Pipes
{
public abstract class Pipe
{
public string Name { get; private set; }
public Func<BinaryReader, BinaryWriter, bool> StreamAction { get; protected set; }
protected Pipe(string name)
{
StreamAction = null;
Name = name;
}
protected Pipe(string name, Func<BinaryReader, BinaryWriter, bool> action)
: this(name)
{
if (action == null)
throw new ArgumentNullException("action", string.Format("Stream action cannot be null, you want us to do *something* with the pipe right?"));
StreamAction = action;
}
protected Pipe(string name, Func<IDictionary<string, object>, IDictionary<string, object>> action)
: this(name)
{
if (action == null)
throw new ArgumentNullException("action", string.Format("Message action cannot be null, you want us to do *something* with the pipe right?"));
StreamAction = ((r, w) =>
{
return DefaultMessageHandler(r, w, action);
});
}
protected bool DefaultMessageHandler(BinaryReader reader, BinaryWriter writer, Func<IDictionary<string, object>, IDictionary<string, object>> callback)
{
int len = reader.ReadInt32();
byte[] bytes = reader.ReadBytes(len);
IDictionary<string, object> msg = PipeMessage.Demarshal(bytes);
IDictionary<string, object> reply = callback(msg);
if (reply != null)
{
WriteMessage(writer, reply);
if (((IDictionary<String, Object>)reply).ContainsKey("LastMessage"))
{
((IDictionary<String, Object>)reply).Remove("LastMessage"); // Don't marshal this property
return false;
}
}
return (reply != null);
}
protected void WriteMessage(BinaryWriter writer, IDictionary<string, object> msg)
{
byte[] encoded = PipeMessage.Marshal(msg);
writer.Write((int)encoded.Length);
writer.Write(encoded);
writer.Flush();
}
protected void HandlePipeConnection(BinaryReader reader, BinaryWriter writer, IDictionary<string, object> initialMessage)
{
try
{
// If we should announce with a specific message, do so
if (initialMessage != null)
{
WriteMessage(writer, initialMessage);
}
// So long as our Func<> returns true, we keep going. When it returns false,
// it is done and its time to closeup and look for another client.
while (StreamAction(reader, writer)) { }
}
catch (IOException)
{
throw;
}
catch(Exception e)
{
LibraryLogging.Error("Error while using pipe connection: {0}", e);
}
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include <assert.h>
#include "BinaryWriter.h"
#if _DEBUG
#define BOUNDS_CHECK(size) if( (m_cursor + size) - m_buffer > m_bufferLength ) assert(0)
#else
#define BOUNDS_CHECK(size)
#endif
namespace pGina
{
namespace Memory
{
void BinaryWriter::Write(int v)
{
if(m_cursor)
{
BOUNDS_CHECK(sizeof(int));
memcpy(m_cursor, &v, sizeof(int));
m_cursor += sizeof(int);
}
m_bytesWritten += sizeof(int);
}
void BinaryWriter::Write(unsigned char v)
{
if(m_cursor)
{
BOUNDS_CHECK(1);
m_cursor[0] = v;
m_cursor++;
}
m_bytesWritten++;
}
void BinaryWriter::Write(bool v)
{
unsigned char val = (v ? 0x01 : 0x00);
Write(val);
}
void BinaryWriter::Write(std::string const& v)
{
int numchars = static_cast<int>(v.size());
Encode7bitLength(numchars);
if(m_cursor)
{
memcpy(m_cursor, v.c_str(), numchars);
m_cursor += numchars;
}
m_bytesWritten += numchars;
}
void BinaryWriter::Write(std::wstring const& v)
{
int numchars = static_cast<int>(v.size()) * sizeof(wchar_t);
Encode7bitLength(numchars);
if(m_cursor)
{
memcpy(m_cursor, v.c_str(), numchars);
m_cursor += numchars;
}
m_bytesWritten += numchars;
}
void BinaryWriter::Encode7bitLength(int length)
{
unsigned int len = (unsigned int) length;
while(len >= 0x80)
{
unsigned char bit = (len | 0x80);
Write(bit);
len >>= 7;
}
// Truncate and write the remaining bit
Write((unsigned char) len);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using log4net;
using pGina.Shared.Interfaces;
using pGina.Shared.Types;
namespace pGina.Plugin.SSHAuth
{
public class PluginImpl : IPluginAuthentication, IPluginConfiguration
{
private ILog m_logger = LogManager.GetLogger("SSHAuth");
#region Init-plugin
public static Guid PluginUuid
{
get { return new Guid("{CC35057C-ACA8-499C-B127-AE4CF978F238}"); }
}
public PluginImpl()
{
using (Process me = Process.GetCurrentProcess())
{
m_logger.DebugFormat("Plugin initialized on {0} in PID: {1} Session: {2}", Environment.MachineName, me.Id, me.SessionId);
}
}
public string Name
{
get { return "SSHAuth"; }
}
public string Description
{
get { return "SSHAuth plugin"; }
}
public Guid Uuid
{
get { return PluginUuid; }
}
public string Version
{
get
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
#endregion
public void Starting() { }
public void Stopping() { }
public void Configure()
{
pGina.Plugin.SSHAuth.Configuration myDialog = new pGina.Plugin.SSHAuth.Configuration();
myDialog.ShowDialog();
}
[DllImport("SSHAuthNative.dll", EntryPoint = "ssh_connect_and_pw_auth", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int ssh_connect_and_pw_authx86(string host, string port, string user, string password, StringBuilder errmsg, int errlen);
[DllImport("SSHAuthNativex64.dll", EntryPoint = "ssh_connect_and_pw_auth", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int ssh_connect_and_pw_authx64(string host, string port, string user, string password, StringBuilder errmsg, int errlen);
public static int ssh_connect_and_pw_auth(string host, string port, string user, string password, StringBuilder errmsg, int errlen)
{
return IntPtr.Size == 8 /* 64bit */ ? ssh_connect_and_pw_authx64(host, port, user, password, errmsg, errlen) : ssh_connect_and_pw_authx86(host, port, user, password, errmsg, errlen);
}
public BooleanResult AuthenticateUser(SessionProperties properties)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
string sshHost = Settings.Store.Host;
string sshPort = Settings.Store.Port;
StringBuilder errsb = new StringBuilder(1024); // For return error message from native auth function
int rc;
rc = ssh_connect_and_pw_auth(sshHost, sshPort, userInfo.Username, userInfo.Password, errsb, errsb.Capacity);
if (rc == 0)
{
// Successful authentication
return new BooleanResult() { Success = true };
}
// Authentication failure
return new BooleanResult() { Success = false, Message = errsb.ToString() };
}
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
namespace pGina.Shared.Types
{
public class UserInformation
{
/// <summary>
/// The list of groups for the user account
/// </summary>
public List<GroupInformation> Groups { get; set; }
// Currently ignored if plugin sets this.. but possibly useful if we go LSA in the future...
/// <summary>
/// The SID for the user (currently ignored)
/// default: Nobody
/// </summary>
public SecurityIdentifier SID
{
get
{
return (_SID == null) ? new SecurityIdentifier("S-1-0-0") : _SID;
}
set
{
_SID = value;
}
}
private SecurityIdentifier _SID;
/// <summary>
/// a valid user will return true
/// </summary>
public bool HasSID
{
get
{
return !SID.ToString().Equals("S-1-0-0", StringComparison.CurrentCultureIgnoreCase);
}
}
public int SessionID { get; set; }
/// <summary>
/// The username provided by the user.
/// </summary>
public string OriginalUsername
{
get
{
return (string.IsNullOrEmpty(_OriginalUsername)) ? "" : _OriginalUsername;
}
set
{
_OriginalUsername = value;
}
}
private string _OriginalUsername;
/// <summary>
/// The username
/// </summary>
public string Username
{
get
{
return (string.IsNullOrEmpty(_Username)) ? "" : _Username;
}
set
{
_Username = value;
}
}
private string _Username;
/// <summary>
/// The domain (a null value indicates that this is a local account).
/// </summary>
public string Domain
{
get
{
return (string.IsNullOrEmpty(_Domain)) ? "" : _Domain;
}
set
{
_Domain = value;
}
}
private string _Domain;
/// <summary>
/// The password
/// </summary>
public string Password
{
get
{
return (string.IsNullOrEmpty(_Password)) ? "" : _Password;
}
set
{
_Password = value;
}
}
private string _Password;
/// <summary>
/// The password provided by the user.
/// </summary>
public string OriginalPassword
{
get
{
return (string.IsNullOrEmpty(_OriginalPassword)) ? "" : _OriginalPassword;
}
set
{
_OriginalPassword = value;
}
}
private string _OriginalPassword;
/// <summary>
/// The old password
/// </summary>
public string oldPassword
{
get
{
return (string.IsNullOrEmpty(_oldPassword)) ? "" : _oldPassword;
}
set
{
_oldPassword = value;
}
}
private string _oldPassword;
/// <summary>
/// Is password expired
/// </summary>
public bool PasswordEXP
{
get
{
return (_PasswordEXP) ? true : false;
}
set
{
_PasswordEXP = value;
}
}
private bool _PasswordEXP;
/// <summary>
/// how long until the password does expire
/// </summary>
public TimeSpan PasswordEXPcntr { get; set; }
/// <summary>
/// Description of this user
/// </summary>
public string Description
{
get
{
return (string.IsNullOrEmpty(_Description)) ? "" : _Description;
}
set
{
_Description = value;
}
}
private string _Description;
/// <summary>
/// The full name associated with this user account.
/// </summary>
public string Fullname
{
get
{
return (string.IsNullOrEmpty(_Fullname)) ? "" : _Fullname;
}
set
{
_Fullname = value;
}
}
private string _Fullname;
/// <summary>
/// The email address associated with this user account.
/// </summary>
public string Email
{
get
{
return (string.IsNullOrEmpty(_Email)) ? "" : _Email;
}
set
{
_Email = value;
}
}
private string _Email;
/// <summary>
/// The LoginScript associated with this user account.
/// </summary>
public string LoginScript
{
get
{
return (string.IsNullOrEmpty(_LoginScript)) ? "" : _LoginScript;
}
set
{
_LoginScript = value;
}
}
private string _LoginScript;
/// <summary>
/// The Local Profile Path associated with this user account.
/// </summary>
public string LocalProfilePath
{
get
{
return (string.IsNullOrEmpty(_LocalProfilePath)) ? "" : _LocalProfilePath;
}
set
{
_LocalProfilePath = value;
}
}
private string _LocalProfilePath;
/// <summary>
/// User Profile: Full Name
/// </summary>
public string usri4_full_name
{
get
{
return (string.IsNullOrEmpty(_usri4_full_name)) ? "" : _usri4_full_name;
}
set
{
_usri4_full_name = value;
}
}
private string _usri4_full_name;
/// <summary>
/// User Profile: max profile size in kbytes
/// </summary>
public UInt32 usri4_max_storage { get; set; }
/// <summary>
/// User Profile: Where to store the roaming profile
/// </summary>
public string usri4_profile
{
get
{
return (string.IsNullOrEmpty(_usri4_profile)) ? "" : _usri4_profile;
}
set
{
_usri4_profile = value;
}
}
private string _usri4_profile;
/// <summary>
/// User Profile: Home drive letter
/// </summary>
public string usri4_home_dir_drive
{
get
{
return (string.IsNullOrEmpty(_usri4_home_dir_drive)) ? "" : _usri4_home_dir_drive;
}
set
{
_usri4_home_dir_drive = value;
}
}
private string _usri4_home_dir_drive;
/// <summary>
/// User Profile: Home drive path
/// </summary>
public string usri4_home_dir
{
get
{
return (string.IsNullOrEmpty(_usri4_home_dir)) ? "" : _usri4_home_dir;
}
set
{
_usri4_home_dir = value;
}
}
private string _usri4_home_dir;
/// <summary>
/// User Profile: pgSMB plugin: compressed filename %u.wim
/// </summary>
public string pgSMB_Filename
{
get
{
return (string.IsNullOrEmpty(_pgSMB_Filename)) ? "" : _pgSMB_Filename;
}
set
{
_pgSMB_Filename = value;
}
}
private string _pgSMB_Filename;
/// <summary>
/// User Profile: pgSMB plugin: profile share name
/// </summary>
public string pgSMB_SMBshare
{
get
{
return (string.IsNullOrEmpty(_pgSMB_SMBshare)) ? "" : _pgSMB_SMBshare;
}
set
{
_pgSMB_SMBshare = value;
}
}
private string _pgSMB_SMBshare;
public string script_authe_sys
{
get
{
return (string.IsNullOrEmpty(_script_authe_sys)) ? "" : _script_authe_sys;
}
set
{
_script_authe_sys = value;
}
}
private string _script_authe_sys;
public string script_autho_sys
{
get
{
return (string.IsNullOrEmpty(_script_autho_sys)) ? "" : _script_autho_sys;
}
set
{
_script_autho_sys = value;
}
}
private string _script_autho_sys;
public string script_gateway_sys
{
get
{
return (string.IsNullOrEmpty(_script_gateway_sys)) ? "" : _script_gateway_sys;
}
set
{
_script_gateway_sys = value;
}
}
private string _script_gateway_sys;
public string script_notification_sys
{
get
{
return (string.IsNullOrEmpty(_script_notification_sys)) ? "" : _script_notification_sys;
}
set
{
_script_notification_sys = value;
}
}
private string _script_notification_sys;
public string script_notification_usr
{
get
{
return (string.IsNullOrEmpty(_script_notification_usr)) ? "" : _script_notification_usr;
}
set
{
_script_notification_usr = value;
}
}
private string _script_notification_usr;
public string script_changepwd_sys
{
get
{
return (string.IsNullOrEmpty(_script_changepwd_sys)) ? "" : _script_changepwd_sys;
}
set
{
_script_changepwd_sys = value;
}
}
private string _script_changepwd_sys;
public string script_changepwd_usr
{
get
{
return (string.IsNullOrEmpty(_script_changepwd_usr)) ? "" : _script_changepwd_usr;
}
set
{
_script_changepwd_usr = value;
}
}
private string _script_changepwd_usr;
public UserInformation()
{
Groups = new List<GroupInformation>();
}
public bool InGroup(GroupInformation group)
{
foreach (GroupInformation exGroup in Groups)
{
if (exGroup.Name == group.Name)
{
// Copy new sid if old isn't set
if (exGroup.SID == null && group.SID != null)
exGroup.SID = group.SID;
return true;
}
if (exGroup.SID != null && group.SID != null && exGroup.SID == group.SID)
return true;
}
return false;
}
// Adds a group and checks for duplicates (skips if dupl)
public bool AddGroup(GroupInformation group)
{
if (!InGroup(group))
{
// No dupl
Groups.Add(group);
return true;
}
return false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json.Linq;
namespace pGina.Plugin.Cbits
{
public class UInfo
{
public string whyCannotLogin;
public string uname;
public string fullName;
public string email;
public string[] groups;
public static UInfo parseResponse(string res)
{
UInfo u = new UInfo();
pGinaCbitsResponse jres = JToken.Parse(res).ToObject<pGinaCbitsResponse>();
// reason why could not login (empty = can login)
u.whyCannotLogin = jres.message;
u.uname = jres.username;
if (u.uname == null)
{
throw new Exception("Bad response arrived: " + res);
}
u.fullName = jres.name;
u.email = jres.email;
u.groups = jres.groups.Split(';');
if (u.groups.Length == 1 && u.groups[0].Contains(";"))
{
throw new Exception("Bad response arrived (groups wrong): " + res);
}
return u;
}
}
public class pGinaCbitsResponse
{
public String message { get; set; }
public String username { get; set; }
public String name { get; set; }
public String groups { get; set; }
public String email { get; set; }
}
}
<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include "ServiceStateHelper.h"
namespace pGina
{
namespace Service
{
/* static */ bool StateHelper::s_LoginChangePassword;
/* static */ std::wstring StateHelper::s_password;
/* static */ std::wstring StateHelper::s_username;
/* static */ pGina::Threading::Mutex StateHelper::s_mutex;
/* static */ pGina::Transactions::ServiceStateThread StateHelper::s_serviceStateThread;
/* static */ std::list<pGina::CredProv::Provider *> StateHelper::s_providers;
/* static */ std::list<pGina::CredProv::Credential *> StateHelper::s_creds;
/* static */
void StateHelper::Start()
{
s_serviceStateThread.SetCallback(NotifyStateChanged);
s_serviceStateThread.Start();
}
/* static */
void StateHelper::Stop()
{
s_serviceStateThread.Stop();
}
/* static */
std::wstring StateHelper::GetStateText()
{
if(s_serviceStateThread.IsServiceRunning())
{
return L"Service Status: Connected";
}
else
{
return L"Service Status: Disconnected";
}
}
/* static */
bool StateHelper::GetState()
{
if(s_serviceStateThread.IsServiceRunning())
{
return true;
}
else
{
return false;
}
}
/* static */
void StateHelper::AddTarget(pGina::CredProv::Provider *ptr)
{
pGina::Threading::ScopedLock lock(s_mutex);
s_providers.push_back(ptr);
}
/* static */
void StateHelper::RemoveTarget(pGina::CredProv::Provider *ptr)
{
pGina::Threading::ScopedLock lock(s_mutex);
s_providers.remove(ptr);
}
/* static */
void StateHelper::AddTarget(pGina::CredProv::Credential *ptr)
{
pGina::Threading::ScopedLock lock(s_mutex);
s_creds.push_back(ptr);
}
/* static */
void StateHelper::RemoveTarget(pGina::CredProv::Credential *ptr)
{
pGina::Threading::ScopedLock lock(s_mutex);
s_creds.remove(ptr);
}
/* static */
void StateHelper::NotifyStateChanged(bool newState)
{
pGina::Threading::ScopedLock lock(s_mutex);
for(std::list<pGina::CredProv::Credential *>::iterator itr = s_creds.begin();
itr != s_creds.end(); ++itr)
{
pGina::CredProv::Credential * ptr = *itr;
ptr->ServiceStateChanged(newState);
}
for(std::list<pGina::CredProv::Provider *>::iterator itr = s_providers.begin();
itr != s_providers.end(); ++itr)
{
pGina::CredProv::Provider * ptr = *itr;
ptr->ServiceStateChanged(newState);
}
}
/* static */
std::wstring StateHelper::GetUsername()
{
pGina::Threading::ScopedLock lock(s_mutex);
return StateHelper::s_username;
}
/* static */
std::wstring StateHelper::GetPassword()
{
pGina::Threading::ScopedLock lock(s_mutex);
return StateHelper::s_password;
}
/* static */
bool StateHelper::GetLoginChangePassword()
{
pGina::Threading::ScopedLock lock(s_mutex);
return StateHelper::s_LoginChangePassword;
}
/* static */
void StateHelper::PushUsername(std::wstring username, std::wstring password, bool Login)
{
pGina::Threading::ScopedLock lock(s_mutex);
StateHelper::s_username.clear();
StateHelper::s_password.clear();
StateHelper::s_username = username;
StateHelper::s_password = <PASSWORD>;
StateHelper::s_LoginChangePassword = Login;
}
/* static */
void StateHelper::SetProvScenario(CREDENTIAL_PROVIDER_USAGE_SCENARIO Scenario)
{
pGina::Threading::ScopedLock lock(s_mutex);
for(std::list<pGina::CredProv::Provider *>::iterator itr = s_providers.begin();
itr != s_providers.end(); ++itr)
{
pGina::CredProv::Provider * ptr = *itr;
ptr->m_usageScenario = Scenario;
}
}
}
}<file_sep>/*
Copyright (c) 2017, pGina Team
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 pGina Team 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 HOLDER 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.
*/
#include <Macros.h>
#include "CredentialProviderFilter.h"
#include "Dll.h"
#include "ProviderGuid.h"
#pragma warning(push)
#pragma warning(disable : 4995)
#include <shlwapi.h>
#pragma warning(pop)
#include <wincred.h>
namespace pGina {
namespace CredProv {
IFACEMETHODIMP CredentialProviderFilter::QueryInterface(__in REFIID riid, __deref_out void **ppv)
{
static const QITAB qit[] =
{
QITABENT(CredentialProviderFilter, ICredentialProviderFilter),
{0},
};
return QISearch(this, qit, riid, ppv);
}
IFACEMETHODIMP_(ULONG) CredentialProviderFilter::AddRef()
{
return InterlockedIncrement(&m_referenceCount);
}
IFACEMETHODIMP_(ULONG) CredentialProviderFilter::Release()
{
LONG count = InterlockedDecrement(&m_referenceCount);
if (!count)
delete this;
return count;
}
HRESULT STDMETHODCALLTYPE CredentialProviderFilter::Filter(
/* [in] */ CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus,
/* [in] */ DWORD dwFlags,
/* [size_is][in] */ GUID *rgclsidProviders,
/* [size_is][out][in] */ BOOL *rgbAllow,
/* [in] */ DWORD cProviders)
{
pDEBUG(L"CredentialProviderFilter::Filter");
// Retrieve the registry settings
std::vector<std::wstring> rawFilterSettings =
pGina::Registry::GetStringArray(L"CredentialProviderFilters");
// If there's nothing there, there's nothing to do.
if( rawFilterSettings.size() == 0 ) return S_OK;
// Unpack the settings
struct FilterSetting { GUID uuid; int filter; std::wstring uuidStr; };
std::vector<struct FilterSetting> filterSettings;
for( DWORD i = 0; i < rawFilterSettings.size(); i++ )
{
std::wstring s = rawFilterSettings[i];
size_t idx = s.find_first_of(L"\t");
if( idx != std::wstring::npos )
{
std::wstring guidStr = s.substr(0, idx);
std::wstring filterStr = s.substr(idx+1);
struct FilterSetting setting;
HRESULT hr = CLSIDFromString(guidStr.c_str(), &(setting.uuid));
if( SUCCEEDED(hr) )
{
setting.uuidStr = guidStr;
setting.filter = _wtoi(filterStr.c_str());
filterSettings.push_back(setting);
//pDEBUG(L"Loaded filter setting: %s %d", setting.uuidStr.c_str(), setting.filter);
}
}
}
// Loop over each cred prov and see if we need to filter it
for( DWORD i = 0; i < cProviders; i++ )
{
bool doFilter = false;
struct FilterSetting setting;
for( DWORD j = 0; j < filterSettings.size(); j++ )
{
if( IsEqualGUID( filterSettings[j].uuid, rgclsidProviders[i] ) )
{
doFilter = true;
setting = filterSettings[j];
}
}
// If we are filtering this CP
if( doFilter )
{
// If we are configured to filter in this scenario
if(
(cpus == CPUS_LOGON && ((setting.filter & 0x1) != 0)) ||
(cpus == CPUS_UNLOCK_WORKSTATION && ((setting.filter & 0x2) != 0)) ||
(cpus == CPUS_CHANGE_PASSWORD && ((setting.filter & 0x4) != 0)) ||
(cpus == CPUS_CREDUI && ((setting.filter & 0x8) != 0))
)
{
pDEBUG(L"Filtering %s", setting.uuidStr.c_str() );
rgbAllow[i] = FALSE;
}
}
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CredentialProviderFilter::UpdateRemoteCredential(
/* [in] */ const CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION *pcpcsIn,
/* [out] */ CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION *pcpcsOut)
{
HRESULT result;
if( pcpcsIn != NULL && pcpcsIn->cbSerialization > 0
&& (pcpcsOut->rgbSerialization = (BYTE *)CoTaskMemAlloc(pcpcsIn->cbSerialization)) != NULL )
{
pcpcsOut->ulAuthenticationPackage = pcpcsIn->ulAuthenticationPackage;
pcpcsOut->clsidCredentialProvider = CLSID_CpGinaProvider;
pcpcsOut->cbSerialization = pcpcsIn->cbSerialization;
CopyMemory(pcpcsOut->rgbSerialization, pcpcsIn->rgbSerialization, pcpcsIn->cbSerialization);
result = S_OK;
}
else
result = S_FALSE;
pDEBUG(L"CredentialProviderFilter::UpdateRemoteCredential(%p) returns %ld", pcpcsIn, result);
return result;
}
CredentialProviderFilter::CredentialProviderFilter(void) :
m_referenceCount(1)
{
AddDllReference();
}
CredentialProviderFilter::~CredentialProviderFilter(void)
{
ReleaseDllReference();
}
}
} | b8a57e43b82c9c3e61ac50f8dac05e03c6d7a048 | [
"Markdown",
"C#",
"Text",
"C",
"C++"
] | 147 | Markdown | ComputerBits/pGina | 9213542efa1888e65cafdf7610e9065569979afb | a4c0a76616748b0c294cdd0288c2dd6c67a98237 |
refs/heads/master | <repo_name>5881/BUCHI<file_sep>/makefile
project.hex: project
avr-objcopy -O ihex project project.hex
project:
avr-gcc -std=gnu99 -mmcu=atmega8 -O2 -o project main.c
write: project.hex
avrdude -c arduino-ft232r -pm8 -v -v -b 115200 -U flash:w:project.hex
#sudo avrdude -c nikolaew -pm8 -P /dev/ttyS0 -U flash:w:project.hex
clean:
rm project project.hex
all: clean project.hex write
fuse:
avrdude -c arduino-ft232r -pm8 -v -v -b 1200 -U lfuse:w:0xFF:m -U hfuse:w:0xC9:m
<file_sep>/main.c
//контроллер роторного испарителя 1.0
//В этой программе зашкаливоющее количество дефениций
#define F_CPU 11059200UL
#include <avr/io.h>
#include <avr/interrupt.h>
//#include <math.h>
#include <stdio.h>
#include <util/delay.h>
//Настройка UART
#define UART_SPEED 115200
#define UBBR_VALUE (F_CPU/UART_SPEED/16)-1
//Конфигурация дисплея
#define ST PC1
#define DS PC0
#define SH PC2
#define PORT_74HC545 PORTC
//Расположение кнопок на панели
// PB0 PB1
// PD7
// PD5 PD6
//Назначение кнопок
#define BUT1 !(PINB&(1<<PB0))
#define BUT2 !(PINB&(1<<PB1))
#define BUT3 !(PIND&(1<<PD7))
#define BUT4 !(PIND&(1<<PD6))
#define BUT5 !(PIND&(1<<PD5))
#define PUMP_RUN PORTC|=(1<<PC3)
#define PUMP_STOP PORTC&=~(1<<PC3)
#define CLAPAN_OPEN PORTC|=(1<<PC4)
#define CLAPAN_CLOSE PORTC&=~(1<<PC4)
//#define CLAPAN_STATE PORTC&(1<<PC4)
//#define PUMP_STATE PORTC&(1<<PC3)
#define HISTERESIS 10
int max_presure=1000;
unsigned char count=0;
unsigned char symbol[11]={0xfa,0x82,0xb9,0xab,0xc3,\
0x6b,0x7b,0xa2,0xfb,0xeb,0x00};//массив цифр
unsigned char out[4]={0xfa,0x82,0xb9,0xab};//отображаемый массив
unsigned char mode=0x00;
void usart_init(void){
UBRRH=UBBR_VALUE>>8;
UBRRL=UBBR_VALUE&0xff;
//настройка конфигурации
UCSRC|=(1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);//8N1
UCSRB|=(1<<RXEN)|(1<<TXEN);//включаем usart
};
void put_char(unsigned char data,FILE *stream){
while(!(UCSRA&(1<<5)));//ждём готовности
UDR=data;//отправляем
//return 0;
};
static unsigned char get_char(FILE *stream){
while(!(UCSRA&(1<<7)));
return UDR;
};
static FILE mystdout=\
FDEV_SETUP_STREAM(put_char,get_char,_FDEV_SETUP_RW);
void timer0_init(){
//тактовая частота FCPU/8
TCCR0|=(1<<CS01);
//Прерывание по переполнению
TIMSK|=(1<<TOIE0);
}
//Индикация динамическая на прерываниях, очень удачно вышло
//Для расширения порта использована 74HC545
ISR(TIMER0_OVF_vect){
static unsigned char dig=0;//отображаемая цифра
unsigned char temp=mode|0x0F;//на всяк случай сброс катодов
temp&=~(1<<(3-dig));
for(unsigned char i=0;i<8;i++){//Засылаем байт mode в 74HC545
if(temp&(1<<7)) PORT_74HC545|=(1<<DS);//Линия данных
else PORT_74HC545&=~(1<<DS);
PORT_74HC545|=(1<<SH);//Линия такта
temp<<=1;//Переходим к следующему биту
PORT_74HC545&=~(1<<SH);
}
temp=out[dig];//считываем значение из массива
for(unsigned char i=0;i<8;i++){//Засылаем символа в 74HC545
if(temp&(1<<7)) PORT_74HC545|=(1<<DS);//Линия данных
else PORT_74HC545&=~(1<<DS);
PORT_74HC545|=(1<<SH);//Линия такта
temp<<=1;//Переходим к следующему биту
PORT_74HC545&=~(1<<SH);
}
PORT_74HC545|=(1<<ST);//Выводим значение засланное в 74HC545
PORT_74HC545&=~(1<<ST);
dig++;//Переходим к следующей
if(dig>3) dig=0;
}
void adc_init(){
//настройка ацп
// напряжение сравнения внутренний источник 2,56 в, вход adc7
ADMUX|=(1<<REFS0)|(1<<REFS1)|(1<<MUX2)|(1<<MUX1)|(1<<MUX0);
//Частота fcpu/128, включение компаратора
ADCSRA|=(1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
}
int mesure(){//Замер с компенсацией шумов за счёт усреднения
unsigned int temp=0;
for(unsigned char i=0;i<64;i++){//набираем статистику
ADCSRA|=(1<<ADSC); //запуск преобразования
while(!(ADCSRA&(1<<ADIF)));//Ждём окончание преобразования
ADCSRA|=(1<<ADIF);//сбрасываем флаг преобразования
temp+=ADCW;
}
return (int)(temp>>6);
}
int correct(unsigned int m){//перевод значений adc в torr
int p=m-200;
if(p<0)p=0;
p*=1.47;
return p;
}
int get_correct_pressure(){
int p;
p=mesure();
p=correct(p);
return p;
}
void indicate(unsigned int data){
//unsigned int temp;
unsigned char m=1, temp_out[4];
//считываем значение
//temp=mesure();
//раскладываем значение на цыфры и переводим в символы
for(unsigned char i=0;i<4;i++){
temp_out[i]=symbol[data%10];
if(i!=3) data/=10;
};
//избавляемся от ведущих нулей
for(unsigned char i=3;i>0;i--){
if(temp_out[i]==0xfa && m) temp_out[i]=0;
else m=0;
}
//переписываем значения в массив вывода
cli();
for(unsigned char i=0;i<4;i++) out[i]=temp_out[i];
sei();
}
void button_scan(){
//Расположение кнопок на панели
// BUT1 BUT2
// BUT3
// BUT5 BUT4
//Назначение кнопок
// PB0 - RUN
if(BUT1){
mode|=(1<<6);//режим установки давления
if (max_presure<800) max_presure+=1;
if (count<13) count+=1;
return;
}
if(BUT5){
mode|=(1<<6);
if(max_presure) max_presure-=1;
if(count<13) count+=1;
return;
}
if(BUT2){
//mode=(1<<4);
//RUN pump
//cloce
max_presure=0;
return;
}
if(BUT3){
//mode|=(1<<7);
max_presure=740;
PUMP_STOP; mode&=~(1<<5);
CLAPAN_OPEN; mode|=1<<4;
//stop pump
//open
return;
}
if(mode&(1<<6)){_delay_ms(500); mode&=~(1<<6); count=0;}
//mode|=(1<<5); //если ничего не нажато то стандартный режим.
}
void mantain(int mantain_pressure){
int p;
p=get_correct_pressure();
if(mantain_pressure==1000 && p>730)
{CLAPAN_CLOSE; mode&=~(1<<4); return;}//заглушка чтбы не держать клапан открытым
//если давление больше заданного, надо закрыть клапан
//если он открыт конечно.
if (p>mantain_pressure)
{CLAPAN_CLOSE; mode&=~(1<<4);}
//Если давление сильно больше заданного (больше гистерезиса)
//надо включить насос
if (p>(mantain_pressure+HISTERESIS) && max_presure<730)
{PUMP_RUN; mode|=(1<<5);}
//Если давление меньше заданного, надо выключить насос
//конечно если он включен
if (p<mantain_pressure)
{PUMP_STOP; mode&=~(1<<5);}
//Если давление сильно меньше заданного, надо открыть клапан
//Если он был закрыт.
if (p<(mantain_pressure-HISTERESIS))
{CLAPAN_OPEN; mode|=1<<4;}
}
int main(void){
DDRD=0;//Настройка портов
DDRC=0xff;
DDRB=0;
PORTD=0b11100000;//тут висят кнопки
PORTB=0b11;//тут висят кнопки
PORTC=0;
int presure;//пришлось добавить знак чтобы избежать
//проблем вблизи нуля
usart_init();//Настройка UART
timer0_init();//Настройка таймера0
adc_init();//Настройка АЦП
stdin=stdout=&mystdout;//Поток ввода-вывода
printf("Shaman's pump controller\r\n");//отладочное сообщение
unsigned char but1_mode=0;
sei();//разрешение прерываний
while(1){
//Насос и клапан работают независимо от режима отображения!
presure=get_correct_pressure();//Замеряем текущее давление
indicate(presure);
mantain(max_presure);
if(BUT1){//RUN
while(BUT1);
if(!but1_mode){max_presure=0; but1_mode=1;}
else {max_presure=presure; but1_mode=0;}
continue;
}
if(BUT5){//^P
//Остановить насос
//открыть клапан
//померить давление и отобразить его и так пока нажата кнопка
PUMP_STOP; mode&=~(1<<5);
CLAPAN_OPEN; mode|=1<<4;
while(BUT5){
presure=get_correct_pressure();//Замеряем текущее давление
indicate(presure);
_delay_ms(200);
max_presure=presure;
}
CLAPAN_CLOSE; mode&=~(1<<4);
continue;
}
if(BUT2){
//закрыть клапан
//Включить насос
//Мерять давление пока нажата кнопка
CLAPAN_CLOSE; mode&=~(1<<4);
PUMP_RUN; mode|=(1<<5);
while(BUT2){
presure=get_correct_pressure();//Замеряем текущее давление
indicate(presure);
_delay_ms(200);
max_presure=presure;
}
PUMP_STOP; mode&=~(1<<5);
continue;
}
if(BUT3){
//mode|=(1<<7);
//STOP
max_presure=1000;
PUMP_STOP; mode&=~(1<<5);
CLAPAN_OPEN; mode|=1<<4;
//stop pump
//open
continue;
}
_delay_ms(200);
};
return 0;
}
<file_sep>/README.md
#Контроллер роторного испарителя BUHI
Совместим с насосом BUCHI V300
Использован микроконтроллер ATmega8 и avr-gcc
<NAME> 2016
| d4f6a88bb179f913b9814557cbd2651f3147a59c | [
"Markdown",
"C",
"Makefile"
] | 3 | Makefile | 5881/BUCHI | a55f6b3e01b0665726ae36ad114f1f2f01d9d714 | 4c1a3e5bd10e4cc449aa9337bf9ffd55c26f235d |
refs/heads/master | <file_sep>#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
/**
*!\brief storage of chart of isotope
*
* contain max and min A values for a given Z which are allowed in GEMINI
*/
struct SIsotope
{
short unsigned iAmax; //!< maximun A value
short unsigned iAmin; //!< minimum A value
};
/**
*!\brief defines accessable region of chart of nuclides
* contains the neutron rich and proton rich
* limits to the chart of nuclides for which
* decay fragments can be chosen
*/
class CChart
{
private:
CChart();
static CChart *fInstance; //!< instance member to make this class a singleton
SIsotope * isotope; //!< lists max and min A for each Z
static int const iZmax; //!< max Z allowed in GEMINI
int * iZindex; //!< list the array number of the lightest isotope of each Z
public:
static CChart* instance(); //!< instance member to make this a singleton
~CChart();
int getAmax(int iZ);
int getAmin(int iZ);
int getIndex(int iZ,int iA);
int iMassDim; //!< dimension of mass array
};
<file_sep>#include "CMerson.h"
//**************************************************************************
// merson initialization
void CMerson::initMerson(double acc0,double step_min0, double step00,int jtest0)
{
acc = acc0;
step_min = step_min0;
step0 = step00;
jtest = jtest0;
ok = 1;
}
//**************************************************************************
// solve system of coupled ordinary differential equations
void CMerson::solveMerson(valarray<double> *y, double xstart,
double xend)
{
int n = y->size();
valarray<double> yz(n);
valarray<double> a(n);
valarray<double> b(n);
valarray<double> f(n);
// rzero is a number with a magnitude of order equal to the noise level of
//the machine i.e. in the range of the rounding errors
double const rzero =1.0e-23;
//jtest = test parameter related to the steplength in the following way.
//jtest = 0, if during the calculation we get ABS(H) less than hmin (by
//repeated halving of the steplength), than an error message is printed,
//ok is set equal to .FALSE. followed by return to the calling program
//jtest = 1, checking as for jtest=0, but the calculation will continue
//with the fixed dtep length hmin
ok = 1;
// store internally parameters in list
double x = xstart;
double step = step0;
int leave = 0;
for (;;)
{
double hsv = step;
double cof = xend - x;
if (abs(step) >= abs(cof))
{
//step length is greater than remaining interval to be integrated
step = cof;
//if (abs(cof/hsv) < rzero) *y = w;
leave = 1;
//if leave is true, then step is equal to the maximum possible
//steplength within the remaining part of the domain of
//integration.
}
yz = *y;
double ht = step/3.;
f = diff(x,*y);
a = ht*f;
*y = a + yz;
x = x + ht;
f = diff(x,*y);
a = 0.5*a;
*y = 0.5*ht*f + a + yz;
f = diff(x,*y);
b = 4.5*ht*f;
*y = 0.25*b + 0.75*a + yz;
x = x + 0.5*ht;
f = diff(x,*y);
a = 2.*ht*f + a;
*y = 3.*a - b + yz;
x = x + 0.5*step;
f = diff(x,*y);
int accuracy = 1;
int k = 0;
while (accuracy && k < n)
{
b[k] = -0.5*ht*f[k] - b[k] + 2.*a[k];
(*y)[k] = (*y)[k] - b[k];
a[k] = abs(5.*acc* (*y)[k]);
b[k] = abs(b[k]);
if (abs((*y)[k]) > rzero && b[k] > a[k]) accuracy = 0;
k++;
}
//if accuracy is false, the required accuracy for all computed values
//was not obtained
if (accuracy==0)
{
//halve step length
cof = 0.5*step;
if(abs(cof) >= step_min)
{
*y = yz;
x = x - step;
step = cof;
leave = 0;
}
else if (jtest == 0)
{
cout << "**Merson error***" << endl;
cout << "jtest= " <<jtest <<" step_min= " << step_min
<< " x= " << x << endl;
ok = 0;
abort();
}
else
{
//continue with constant step length equal to hmin
step = step_min;
if (hsv < 0.) step = -step;
}
}
else
{
//required accuray obtained
//test if step length doubling is possible
valarray<double> g(b-0.03125*a);
if (g.max() <= 0.0) step = 2.0*step;
}
if (leave) break;
}
// calculation has finished -
}
<file_sep>#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
/**
*!\brief stores parameters for a component of the GDR lineshape
*
*/
struct Lshape
{
float strength; //!< Lorentzian strength (fraction)
float energy; //!< Centroid [MeV]
float gamma; //!< Width [MeV]
};
/**
*!\brief user-defined GDR line shape
*
* Reads in and calculates the GDR line shape in the E1 gamma-decay
* branch of a hot compound nucleus. It reads file tbl/GDR.inp
* for the parameters of up to 5 Lorentzians.
* The parameters are the strength, the centriod [MeV] and the
* width [MeV]. The sum of the stregths should add to unity
*
*/
class CGdr
{
public:
static CGdr* instance(); //!< instance member to make this a singleton
float getLineShape(float e);
protected:
static CGdr* fInstance; //!< instance member to make this a singleton
CGdr(); //!< constructor
int N; //!< number of Lorentzians in lineshape
Lshape lineShape[5]; //!< parameters for each Lorentzian
};
<file_sep>#include "CSigCharged.h"
CSigCharged::CSigCharged(string sName0, float Zp0, float Ap0)
{
Zp = Zp0;
Ap = Ap0;
if (sName0 == "neutron")
{
neutron = 1;
return;
}
neutron = 0;
sName = "tl/"+sName0+".inv";
string fullName;
if (getenv("GINPUT") == NULL) fullName = sName;
else
{
string dir(getenv("GINPUT"));
fullName = dir+sName;
}
ifstream ifFile (fullName.c_str());
if (ifFile.fail() )
{
cout << "file " << fullName << " not found in CSigCharged" << endl;
abort();
}
ifFile >> rc0 >> rc1 >> rc2;
ifFile >> rI0 >> rI1 >> rI2;
ifFile >> omega0 >> omega1 >> omega2 >> omega3;
ifFile >> a0;
ifFile >> aa0;
ifFile.close();
ifFile.clear();
}
//******************************************
void CSigCharged::prepare(float Z, float A)
{
if (neutron)
{
n0 = 10.386*(1.-exp((-Z/24.50)));
n1 = 1.227+0.03444*Z;
n2 = 2.;
barrier = .5;
return;
}
float A13 = pow(A,(float)(1./3.));
float rc = rc0/A13 + rc1 + rc2*A13;
barrier = Zp*Z*1.44/rc;
float rI = rc0/A13 + rI1 + rI2*A13;
float mu = A*Ap/(A+Ap);
InvInertia = 2.*mu*pow(rI,2)/41.563;
omega = omega0 + omega1*A + omega2*exp(-A/omega3);
a = a0;
aa = aa0;
offset = barrier/2.;
}
//*****************************************
float CSigCharged::getInverseXsec(float energy)
{
if (neutron) return (n0+ n1*energy)*(1.-exp(-energy/n2));
float ddelta = sqrt(pow(offset,2)+pow(energy-barrier,2)) - offset;
float delta;
if (energy > barrier) delta = energy - barrier - a*ddelta;
else delta = energy - barrier - aa*ddelta;
float out = InvInertia*(delta + omega*log(1.+exp(-delta/omega)));
if (out < 0.) out = 0.;
return out;
}
//******************************************
float CSigCharged::getBarrier()
{
return barrier;
}
<file_sep>#include "CSigBarDist.h"
float CSigBarDist::width=1.;
float const CSigBarDist::width0=1.5;
//****************************************************************
/**
* constructor
/param sName0 is the name of the files containing fitted coeff.
*/
CSigBarDist::CSigBarDist(string sName0, float Zp0, float Ap0)
{
Zp = Zp0;
Ap = Ap0;
string sName = sName0;
sigCharged[1] = new CSigCharged(sName,Zp,Ap);
sName = sName0+"P";
//see if second file is there
string fullName;
if (getenv("GINPUT") == NULL) fullName = "tl/"+sName+".inv";
else
{
string dir(getenv("GINPUT"));
fullName = dir+"tl/"+sName+".inv";
}
ifstream ifFile(fullName.c_str());
if (ifFile.fail() || sName0 == "neutron" )
{
one = 1;
return;
}
ifFile.close();
ifFile.clear();
one = 0;
sigCharged[2] = new CSigCharged(sName,Zp,Ap);
sName = sName0+"M";
sigCharged[0] = new CSigCharged(sName,Zp,Ap);
}
//****************************************************
/**
* destructor
*/
CSigBarDist::~CSigBarDist()
{
if (one) delete sigCharged[1];
else for (int i=0;i<3;i++) delete sigCharged[i];
}
//*******************************************
/**
* returns the quantity
* \f$S=\sum_{\ell=0}^{\infty} (2\ell+1)T_{\ell}(\varepsilon)\f$
* which is related to the inverse cross section by
* \f$S=\frac{\sigma_{inv}}{\pi\lambda^{2}}\f$
\param fEk is the kinetic energy of the evaporated particle
\param temp is temperature of daughter in MeV
*/
float CSigBarDist::getInverseXsec(float fEk, float temp)
{
if (one || temp <= 0. || width == 0.)
return sigCharged[1]->getInverseXsec(fEk);
float deltaR = sqrt(temp)*width;
float ee[3];
for (int i=0;i<3;i++)
{
ee[i] = sigCharged[i]->getInverseXsec(fEk);
if (ee[i] == 0.) return 0.;
}
/*
float c1 = (ee[2]-ee[0])/2./width0;
float c2 = (ee[2]+ee[0]-2.*ee[1])/pow(width0,2)/2.;
float s0 = ee[1] + deltaR*c1 + c2*pow(deltaR,2);
float s1 = ee[1];
float s2 = ee[1] - deltaR*c1 + c2*pow(deltaR,2);
return (s0+s1+s2)/3.;
*/
float c2 = (ee[2]+ee[0]-2.*ee[1])/pow(width0,2)/2.;
float out = ee[1] + 2./3.*c2*pow(deltaR,2);
if (out < 0.) out = 0.;
return out;
}
//**************************************************
/**
* set the parameter controlling the width of the barrier distribution
\param width00 - radial shift is \f$ \Delta R= \sqrt T* width00 \f$
*/
void CSigBarDist::setBarWidth(float width00)
{
width = width00;
}
//***************************************************
/**
* returns the parameter controlling the width of the barrier dist
*/
float CSigBarDist::getBarWidth()
{
return width;
}
//**************************************************************************
/**
* prints out the width parameter
*/
void CSigBarDist::printParameters()
{
cout << "tl barrier width parameter = " << width << endl;
}
//**************************************************************************
/**
* prepares for a series of opertions for a given iZ
/param iZ0 is proton number of daughter
*/
void CSigBarDist::prepare(float Z0, float A0)
{
Z = Z0;
A = A0;
sigCharged[1]->prepare(Z,A);
if (one) return;
sigCharged[0]->prepare(Z,A);
sigCharged[2]->prepare(Z,A);
}
//**********************************************************
/**
* returns the barrier in MeV
*/
float CSigBarDist::getBarrier()
{
return sigCharged[1]->getBarrier();
}
<file_sep>#include "CTlArray.h"
/**
* Constructor
\param sName0 is the name of the *.tl file in directory /tl where
the parameters specifying the transmission coefficents are contained
*/
CTlArray::CTlArray(string sName0)
{
sName = "tl/"+sName0+".tl";
string fullName;
if (getenv("GINPUT") == NULL) fullName = sName;
else
{
string dir(getenv("GINPUT"));
fullName = dir+sName;
}
ifstream ifFile (fullName.c_str());
if (ifFile.fail() )
{
cout << "file " << sName << " not found in CTlArray" << endl;
abort();
}
float fx[7];
string line;
getline(ifFile,line);
ifFile >> shift;
iZMin = 2;
int kk;
for (int i=1;i<=120;i++)
{
ifFile >> kk >> fx[0] >> fx[1] >> fx[2]
>> fx[3] >> fx[4] >> fx[5] >> fx[6];
//see if data is ok
if (isnan(fx[0]))
{
iZMin = kk;
break;
}
if (fx[0] == 0. && fx[1] == 0. && fx[2] == 0. && fx[3] == 0.)
{
iZMin = kk;
break;
}
if (ifFile.bad() || ifFile.eof())
{
cout << "trouble reading file " << sName << " in CTlArray" << endl;
}
for (int j=0;j<7;j++)zcoef.Tl[kk].coef[j] = fx[j];
}
ifFile.clear();
ifFile.close();
}
//************************************************************
/**
* prepares for a series of calls with the same Z value
\param iZ is the proton number of the daughter
*/
void CTlArray::prepare(int iZ)
{
trans = &zcoef.Tl[iZ];
}
//***********************************************************
/**
* The transmission coeff are parameterized as \f$\frac{1}{1+exp(x)}\f$
* this function returns the value of x
\param iL is the orbital angular momentum of the evaporated particle
\param fEk is the kinetic energy of the evaporated particle
*/
float CTlArray::getTermInExp(int iL, float fEk)
{
float fL = (float)(iL+1);
float fC1 = trans->coef[6];
float fC2 = trans->coef[0] + fL*(trans->coef[1] + fL*trans->coef[2]);
float fC3 = trans->coef[3] + fL*(trans->coef[4] + fL*trans->coef[5]);
fEk += shift;
// the interpolation can have a maximum, must find
float emax; // energy of maximum or minimum
float d2e; //second derivative at stationary point
if (fC1 == 0.0)
{
emax = 0.0;
d2e = 0.0;
}
else
{
emax = fC3/fC1;
if (emax > 0.0) //real stationary points
{
emax = sqrt(emax);
d2e = 2.0*fC3/pow(emax,3);
}
else
{
emax = 0.0;//no real maximum
d2e = 0.0;
}
}
float fX;
if (fEk < emax && d2e < 0.0)
{
//fit has a maximum at positive ek, set tl=0 below this energy
fX = 100.;
}
else if (fEk > emax && d2e > 0.0)
{
//fit has minimum at positive ek, set eetl at it minimum
//value above this energy
fX = fC1*emax + fC2 + fC3/emax;
}
else
{
fX = fC1*fEk + fC2 + fC3/fEk;
}
return fX;
}
//***************************************************
/**
* Returns the transmission coefficient
\param iL is the orbital angular momentum of the evaporated particle
\param fEk is the kinetic energy of the evaporated particle
*/
float CTlArray::getTl(int iL, float fEk)
{
float fX = getTermInExp(iL,fEk);
return 1.0/(1.0+exp(fX));
}
//***********************************
/**
* returns the quantity
* \f$S=\sum_{\ell=0}^{\infty} (2\ell+1)T_{\ell}(\varepsilon)\f$
* which is related to the inverse cross section by
* \f$S=\frac{\sigma_{inv}}{\pi\lambda^{2}}\f$
\param fEk is the kinetic energy of the evaporated particle
*/
float CTlArray::getInverseXsec(float fEk)
{
float tot = 0.;
float xmax = 0.;
int iL = 0;
for(;;)
{
float x = (float)(2*iL+1)*getTl(iL,fEk);
xmax = max(x,xmax);
tot += x;
if (x < xmax*.01) break;
iL++;
if (iL > 20) break;
}
return tot;
}
<file_sep>#include "CGdr.h"
CGdr* CGdr::fInstance = 0;
/**
* Constructor
*/
CGdr::CGdr()
{
string fileName("tbl/GDR.inp");
string fullName;
if (getenv("GINPUT") == NULL) fullName = fileName;
else
{
string dir(getenv("GINPUT"));
fullName = dir+fileName;
}
ifstream ifFile (fullName.c_str());
if (ifFile.fail())
{
cout << " file " << fullName << " not found" << endl;
abort();
}
//skip line
string line;
getline(ifFile,line);
//read in paramters of Lorentzian's , up to five are allowed
double a,b,c;
N = 0;
for (int i=0;i<5;i++)
{
ifFile >> a >> b >> c;
if (ifFile.eof()) break;
if (ifFile.bad()) break;
if (a== 0.) break;
lineShape[N].strength = a;
lineShape[N].energy = b;
lineShape[N].gamma = c;
N++;
}
if (N == 0)
{
cout << "no user-defined GDR" << endl;
abort();
}
}
//******************************************************
/**
* returns the GDR line shape as a sum of up to 5 user-defined
* Lorentzians
\param e is the gamma energy in MeV
*/
float CGdr::getLineShape(float e)
{
float out = 0.;
for (int i=0;i<N;i++)
{
out += lineShape[i].gamma*lineShape[i].strength*pow(e,4)/
(pow(pow(e,2)-pow(lineShape[i].energy,2),2)+pow(lineShape[i].gamma*e,2));
}
return out;
}
//***************************
CGdr* CGdr::instance()
{
if (fInstance == 0) {
fInstance = new CGdr;
}
return fInstance;
}
<file_sep>#include <iostream>
using namespace std;
class CWaves
{
public:
CWaves(double,double,int);
~CWaves();
double *F; // regular wavefunction
double *dF; // derivative of regular
double *G; // irregular wavefunction
double *dG; // derivative of irregular
double *sigma; // Coulomb phase shifts
private:
void coulombWave();
void sphericalBessel();
double rho;
double gamma;
int lMaximum;
};
//*******************************************************
<file_sep>#include "CHistory.h"
CEvap *CHistory::evap;
CHistory::HistoryStringToDigitsTranslator CHistory::theTranslator;
const int CHistory::maxInt32Len = numeric_limits<int32_t>::digits10;
const char CHistory::Evaporation = 'e';
const char CHistory::EvaporationResidue = 'E';
const char CHistory::Multifragmentation = 'm';
const char CHistory::AsymmetricFissionLight = 'a';
const char CHistory::AsymmetricFissionHeavy = 'A';
const char CHistory::SymmetricFissionLight = 'f';
const char CHistory::SymmetricFissionHeavy = 'F';
const char CHistory::SaddleToScission = 's';
const char CHistory::NonStatistical = 'n';
void CHistory::tagDaughters(CNucleus *n, std::string const &parentHistory) {
CNucleus *daughterLight = n->getLightDaughter();
CNucleus *daughterHeavy = n->getHeavyDaughter();
if(!daughterLight && !daughterHeavy) {
return;
}
// Saddle-to-scission transition or gamma decay
if(!daughterLight) {
// Gamma decay
theMap[daughterHeavy] = parentHistory;
tagDaughters(daughterHeavy, parentHistory);
return;
}
std::string lightHistory, heavyHistory;
if(n->isSaddleToScission()) {
if(daughterLight->iZ <= maxEvapZ) {
lightHistory = addToHistory(Evaporation, addToHistory(SaddleToScission, parentHistory));
heavyHistory = addToHistory(SaddleToScission, parentHistory);
} else {
lightHistory = addToHistory(SymmetricFissionLight, parentHistory);
heavyHistory = addToHistory(SymmetricFissionHeavy, parentHistory);
}
theMap[daughterLight] = lightHistory;
theMap[daughterHeavy] = heavyHistory;
} else {
if(n->isNotStatistical()) {
lightHistory = addToHistory(NonStatistical, parentHistory);
heavyHistory = addToHistory(NonStatistical, parentHistory);
} else if(daughterLight->iZ <= maxEvapZ) {
lightHistory = addToHistory(Evaporation, parentHistory);
heavyHistory = addToHistory(EvaporationResidue, parentHistory);
} else {
lightHistory = addToHistory(AsymmetricFissionLight, parentHistory);
heavyHistory = addToHistory(AsymmetricFissionHeavy, parentHistory);
}
theMap[daughterLight] = lightHistory;
theMap[daughterHeavy] = heavyHistory;
}
tagDaughters(daughterLight, lightHistory);
tagDaughters(daughterHeavy, heavyHistory);
}
//************************************************************
/**
* add a step to the history variable
*/
std::string CHistory::addToHistory(char steptype, std::string const &prevhist)
{
std::string history;
size_t histLenMinus1 = prevhist.length();
char last;
if(histLenMinus1>0) {
histLenMinus1--;
last = prevhist.at(histLenMinus1);
} else {
last = '\0';
}
if( last == EvaporationResidue && steptype == Evaporation )
history = prevhist.substr(0,histLenMinus1) + Evaporation;
else if( last == EvaporationResidue && steptype == EvaporationResidue )
history = prevhist;
else if( last == SaddleToScission && steptype == SaddleToScission )
history = prevhist;
else
history = prevhist + steptype;
return history;
}
char CHistory::HistoryStringToDigitsTranslator::operator()(char const c) {
std::map<char,char>::const_iterator iter = theStepMap.find(c);
if(iter!=theStepMap.end())
return iter->second;
else
return '\0';
}
<file_sep>#ifndef mass_
#define mass_
#include "CChart.h"
#include <iomanip>
using namespace std;
/**
*!\brief mass excesses, pairing energy, etc
*
* Class associated with returning quanties associated with
* the mass formula
*/
class CMass
{
protected:
CMass(); //!< constructor
static CMass* fInstance; //!< instance member to make tis a singleton
float * fExpMass; //!<experimental mass array
float * fCalMass; //!<experimental mass array
float * fFRM; //!<finite range mass array
float * fPair; //!< pairing correction
//float * fBeta2; //!<deformation array
float * fShell; //!< shell correction
float * fShell2; //!< shell correction
void ReadFRDMFile();
void ReadThomasFermiFile();
public:
// mod-TU CMass();
~CMass();
CChart *chart; //!< contains the considered region of the chart of nuclides
static CMass* instance(); //!< instance member to make this a singleton
float getExpMass(int iZ,int iA);
float getCalMass(int iZ,int iA);
float getShellCorrection(int iZ, int iA);
float getShellCorrection2(int iZ, int iA);
float getFiniteRangeMass(int iZ,int iA);
float getFiniteRangeMass(float fZ,float fA);
float getLiquidDropMass(int iZ ,int iA);
float getPairing(int iZ,int iA);
float getPairing2(int iZ,int iA);
};
#endif
<file_sep>#ifndef tlArray_
#define tlArray_
#include <string>
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
using namespace std;
/**
*!\brief IWBC fit parameters
*
* This structure contains the parameters with were obtained from a fit
* to the IWBC transmission coefficients
*/
struct SAngTl
{
float coef[7]; //!< fit parameters
};
/**
*!\brief IWBC fit parameters
*
* Stores transmission coef. fit parameters for each daughter proton number
*/
struct SZcoef
{
SAngTl Tl[121]; //!< array of fit paramters for each daughter Z
};
/**
*!\brief IWBC transmission coefficients
*
* Provides transmission coefficients and inverse cross sections
* for light-partice evaporation
*/
class CTlArray
{
protected:
SZcoef zcoef; //!< structure to store coefficients parametrizating Tl's
string sName; //!< name of file containg Tl parameters
float shift; //!< energy shift used in the parametrization
SAngTl *trans; //!<pointer to coefficents for a select iZ
public:
CTlArray(string);
float getTermInExp(int iL,float fEk);
void prepare(int iZ);
float getTl(int iL ,float fEk);
float getInverseXsec(float fEk);
int iZMin; //!< the minimum Z-value for coefficinets are stored
};
#endif
<file_sep>class CRunAlpha
{
public:
CRunAlpha(int iZ,int iA, double Elab, int Nevents);
};
<file_sep>// -*- mode: c++ -*-
//
#ifndef nucleus_
#define nucleus_
#include "CMass.h"
#include "CYrast.h"
#include "CLevelDensity.h"
#include "CAngle.h"
#include <string>
#include <sstream>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include "CAngle.h"
#include "CEvap.h"
#include "CAngleDist.h"
#include "CScission.h"
#include "CWeight.h"
#include "SStoreEvap.h"
#include <vector>
#include "CGdr.h"
using namespace std;
/**
*!\brief storage
*
* this structure store information of the evaporated particle orbital AM
*/
struct SStoreSub
{
float gamma; //!< weight factor for the orbital amgular momentum
short unsigned L; //!< orbital angular momentum
};
typedef vector<SStoreSub> SStoreSubVector;
typedef vector<SStoreSub>::const_iterator SStoreSubIter;
/**
*!\brief storage
*
* this structure info on complex fragment channels
*/
struct SStore
{
double gamma; //!< decay width of channel
short unsigned iZ; //!< proton number of complex fragment
short unsigned iA; //!< mass number of complex fragment
};
typedef vector<SStore> SStoreVector;
typedef vector<SStore>::const_iterator SStoreIter;
/**
*!\brief storage
*
* structure stores information of evaporation decay sub channels
*/
struct SStoreChan
{
float S2; //!< spin of daughter
float Ek; //!< kinetic energy of evaporated particle (MeV)
float Ex; //!< excitation energy of daughter (MeV)
float gamma; //!< partial decay width for this subchannel (MeV)
float temp; //!< temperature of daughter (MeV)
float UPA; //!< thermal excitation energy per nucleus of daughter (MeV)
short unsigned L; //!< orbital angular momentum of evaporated particle
};
/**
*!\brief Hauser-Feshbach, Bohr-Wheeler, Morretto, formulisms
*
* Class CNucleus impliments the GEMINI statistical mode code.
* It follows the decay of a compound nucleus by a sequential series of
* binary decays. The decay widths are calculated with Hauser-Feshbash
* formulism for light particles and Morreto's transition-state formulism
* for other binary decays
*/
class CNucleus : public CNuclide, public CWeight
{
protected:
float Ecoul; //!< Coulomb barrier (HauserFeshbach)
bool notStatistical; //!< this does not decay statistically, evap. frag. only
short unsigned notStatisticalMode;//!< specifies type of nonStatisical decay
float fPairing; //!< pairing energy
float fShell; //!<shell correction
float fU0; //!< thermal excitation energy
float Erot; //!<yrast energy
float Jmax; //!< max spin with a fission barrier
float fMInertia; //!< spherical moment of inertia
float logLevelDensity; //!< store the log of the level density of the nucleus
float temp; //!< nuclear temperature
int fissionZ; //!< proton number of fission fragment
int fissionA; //!< mass number of fission fragment
int fissioningZ; //!< proton number of fission parent
int fissioningA; //!< mass number of fission parent
int iZ1_IMF_Max; //!< maximum Z for IMF emission
float fissionU; //!< thermal excitation energy of both fission fragments
float EdefScission; //!< deformation energy of the scission configuration
bool saddleToSciss; //!< indicated decay during saddle-to-scission transition
float timeSinceSaddle; //!< stores the time since the saddle was crossed
float timeSinceStart; //!< stores the time since the decay began
void saddleToScission();
void massAsymmetry(bool);
bool needSymmetricFission; //!< indicated the Bohr-Wheeler width is needed
static bool const noSymmetry;//!< true - old gemini with Morreto for all
float timeScission; //!< time required to go from saddle to scission
static float const viscosity_scission; //!< viscosity during saddleTosciss
static float const viscosity_saddle; //!< viscosity during saddleTosciss
static float timeTransient; //!< transient fission delay
static float fissionScaleFactor; //!< fission width scaled by this factor
static float barAdd; //!< adds to Sierk fission barrier
static unsigned iPoint; //!< pointer to array of stable fragments
static int iHF; //!< set evaporation mode
int HF; //!< evaporation mode chosen for a given decay
static bool noIMF; //!< no imf emission is considered
static bool BohrWheeler; //!< no imf emission is considered
float selectJ(float,float,float,float);
static short unsigned Zshell; //!< enforce shell effects in evaporation
static CYrast *yrast; //!< gives fission barriers and rotational energies
CScission scission; //!< gives scission energeis, etc
static CLevelDensity *levelDensity; //!< gives level densities
static CGdr * GDR ; //!< uder defined GDR line shape
bool bStable; //!< indicated this nucleus is particle-stable
static float const r0; //!< radius const (fm)
static float const sep; //!< separation between fragments
static float threshold; //!< used to turn off unlikey evaporations
CAngle spin; //!< orientation of the spin axis
float velocity[3]; //!< velocity vector of nucleus in cm/ns
float momentum[3]; //!< momentum vector in MeV/c
static CEvap *evap; //!< stores info on evaporated particles
CLightP * lightP; //!< points to the light-particle decay mode
float S2Loop(float Ekvalue);
float S2Width(float Ekvalue);
float EkWidth(float ek);
void getSpin( bool saddle);
float EkLoop();
float getSumTl(float,float);
float getWidthZA(float,short);
void angleEvap();
void angleIsotropic();
void angleGamma();
float S2Start; //!< Hauser-Feshback spin of daughter
float UMin; //!< min thermal excitation energy in Hauser-Feshbach
float EcostMin; //!<the min of the energetic cost of emitting light particles
static short unsigned const lMaxQuantum; //!< number of l-waves to store angular dist
static float de;//!< kinetic-energy interval for integrating in Hauser-Feshb
int lMin; //!< minimum orbital AM for Hauser-Feshbach
int lMax;//!< maximum orbital AM for Hauser-Feshbach
float lPlusSMax; //!< max value of l+S of evaporated particle
float lPlusSMin; //!< min value of l+S of evaporated particle
float rResidue; //!< radius of daughter
float rLightP; //!< radius of evaporated particle
//float fMInertiaOrbit; //!< moment of Inertia for orbital motion
float S2; //!< spin of daughter
float EYrast2; //!< rotational energy of daughter
SStoreEvap * storeEvap; //!< information of evap sub channels
SStoreSub * storeSub; //!< store info on l distribution
int iStore; //!< actual number of evap sub channels
short unsigned EvapZ2; //!< proton number of daughter after evap.
short unsigned EvapA2; //!< mass number of daughter after evap.
short unsigned EvapZ1; //!< proton number of evaporated particle
short unsigned EvapA1; //!< mass number of evaporated particle
short unsigned EvapL; //!< orbital AM of evaporated particle
short unsigned EvapMode; //!< ID number of evap channel
float EvapEx1; //!< excitation ennergy of evap. particle
float EvapEx2; //!< excitation energy of daughter after evap.
float EvapS2; //!< spin of daughter after evap
float EvapS1; //!< spin of evaporated particle
float EvapEk; //!< kinetic energy of evaporated particle (MeV)
float EvapLPlusS; //!< toatl spin plus orbital AM of evaporated particle
static CAngleDist angleDist; //!< selects angular distributions of decays
float GammaEx;//!< excitation energy after gamma emission
float GammaJ; //!< spin after gamma emission
int GammaL; //!< gamma type E1=1, E2 = 2
static float const gammaInhibition[3];
//!<scaling of gamma width from Weisskopf value
static float const wue[3]; //!<coeff for Weisskopf units (gamma decay)
void binaryDecay();
void exciteScission(float,float,bool sym=1);
float asyFissionWidth();
float asyFissionWidthZA();
float asyFissionWidthBW();
void force8Be();
void force5Li();
void force5He();
void force9B();
float evaporationWidthSS();
float gammaWidth();
float gammaWidthE1GDR();
float gammaWidthMultipole(int);
float hauserFeshbach(int);
float weiskopf( bool saddle);
void asyFissionDivide();
void recursiveDecay();
CNucleus*daughterLight; //!< pointer to the lighter of the decay products
CNucleus*daughterHeavy; //!< pointer to the heavier of the decay products
CNucleus*parent; //!< pointer to the parent nucleus
static int const Nproducts;
//!< total number of possible decay products from all decays
static vector<CNucleus *> allProducts;
//!< array of pointer to all decay products (stable or intermediate)
static vector<CNucleus *> stableProducts;
//!< array of pointers to all stable decay products for all CN decays
bool bResidue; //!< true if decay produced an evaporation residue
bool bSymmetricFission; //!< true if decay resulted in symmetric fission
bool bAsymmetricFission; //!< true if decay resulted in asymmetric fission
int multPostLight; //!< number of post-fission neutrons for lighter ff
int multPostHeavy; //!< number of post-fission neutrons for heavier ff
int multPreSaddle; //!< number of pre-scission neutrons emitted
int multSaddleToScission;
//!< number of neutrons emitted between saddle and scission
static float const kRotate; //!< constant to calculated rotational energy
void split(CAngle);
float sigma2; //!< variance of fission mass distribution
float symSaddlePoint;//!< symmetric saddle point energy
static float sumGammaEnergy; //!< store the energy emitted in gamma rays
static vector <float> GammaRayEnergy; //!< store each gamma ray energy
static int nGammaRays; //!< number of emitted gamma rays
static bool GDRParam; //!< if true, the standard formula for GDR decay width is used, if false the parametrized version
public:
bool abortEvent; //!< abort the event
float evaporationWidth();
float BohrWheelerWidth();
float LestoneFissionWidth();
float LestoneCorrection(float Usaddle, float momInertiaEff,short iAfAn);
static float const pi; //!< 3.14159
static double const EkFraction; // !< calculates the Ek spectra down to this
// fraction of the maximum
//functions
CNucleus();
CNucleus(int iZ,int iA);
CNucleus(int iZ,int iA, float fEx, float fJ);
~CNucleus();
float getSumGammaEnergy();
int getnGammaRays(); //get number of emitted gamma rays
float getGammaRayEnergy(int number); // get gamma ray energy
float getTime();
void setNewIsotope(int iZ0, int iA0, float fEx0, float fJ0);
void setCompoundNucleus(float fEx0,float fJ0);
void setCompoundNucleus(float fEx0,double dJ0);
void setCompoundNucleus(double dEx0,float fJ0);
void setCompoundNucleus(double dEx0,double dJ0);
void setSpinAxis(CAngle angle);
void setSpinAxisDegrees(CAngle angle);
void setVelocityPolar(float =0.,float=0.,float=0.);
void setVelocityCartesian(float vx=0.,float vy=0.,float vz=0.);
void reset();
static void resetGlobal();
void print();
void printStableProducts();
void printAllProducts();
void vCMofAllProducts();
void energyConservation();
CNucleus* getProducts(int=-1);
CNucleus* getParent();
CNucleus* getLightDaughter();
CNucleus* getHeavyDaughter();
CNucleus* getCompoundNucleus();
int getNumberOfProducts();
int getZmaxEvap();
void excite(float,float);
void excite(float,double);
void excite(double,float);
void excite(double,double);
void excite(float);
float getTheta();
float getThetaDegrees();
CAngle getAngle();
CAngle getAngleDegrees();
float getKE();
float getVelocity();
float getMomentum();
float* getVelocityVector();
float* getMomentumVector();
static void setTimeTransient(float time);
static void setFissionScaleFactor(float factor);
static void setBarWidth(float width);
static void setDeltaE(float de0);
static void setThreshold(float threshold0);
static void setAddToFisBarrier(float barAdd0);
static void setNoIMF();
static void setYesIMF();
static void setLestone();
static void setBohrWheeler();
static void setSolution(int isol);
static void setEvapMode(int iHF0=2);
static void setUserGDR(bool mode = true);
static float getTimeTransient();
static float getFissionScaleFactor();
static float getBarWidth();
static float getDeltaE();
static float getThreshold();
static float getAddToFisBarrier();
void decay();
bool isAsymmetricFission();
bool isSymmetricFission();
bool isNotStatistical();
bool isSaddleToScission();
bool isResidue();
int getMultPost();
int getMultPre();
int getMultPostLight();
int getMultPostHeavy();
int getMultPreSaddle();
int getMultSaddleToScission();
float getFissionTimeSymmetric(float & timeScission);
float getFissionTimeAsymmetric();
float getDecayWidth();
float getLogLevelDensity();
int origin; //!< specifies the origin of the fragment, prefission, post , etc
int origin2; //!< specifies the origin of the fragment, prefission, post , etc
void printParameters();
//*******ROOT********
//ClassDef(CNucleus,1) //Gemini Nucleus
};
#endif
<file_sep>#ifndef random_
#define random_
#include <cstdlib>
#include <cmath>
#include "TRandom3.h"
/**
* !\brief Random numbers for a number of distributions
*
* Random number generation using the root TRandom3 generator
* this is an alternative to the C++ generator in the main GEMINI++
* distribution
*/
class CRandom
{
protected:
CRandom();
static CRandom* fInstance; //!< instance member to make tis a singleton
bool one; //!< used for Gaus
float angle; //!< used for Gaus
float x; //!< parameter
float pi; //!< 3.14159
TRandom3 * randy;
public:
static CRandom* instance(); //!< instance member to make this a singleton
~CRandom();
double Rndm();
float Gaus(float mean,float sigma);
float expDecayTime(float width);
float BreitWigner(float mean ,float width);
};
#endif
<file_sep>#ifndef _levelDensity
#define _levelDensity
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
/**
*!\brief returns level density, entropy, temperature
*
* This class deals with level densities and related paramters.
* the level-density parameter is \f$a=\frac{A}{k_{\infty} - \left(k_{\infty} -k_{0} \right) \exp\left( \frac{\kappa}{k_{\infty}-k_{0}}\frac{U}{A}\right)}\f$
* where \f$ \kappa = a_{\kappa} \exp\left(c_{\kappa} A\right) \f$
*/
class CLevelDensity
{
private:
CLevelDensity();
static CLevelDensity *fInstance; //!< instance member to make this class a singleton
static float k0; //!< inverse level-density parameter at U=0
static float kInfinity; //!< inverse level-density parameter at U=infinity
static float aKappa; //!< mass dependence of kappa
static float cKappa; //!< mass dependence of kappa
static float af_an; //!< ratio of sym-fission saddle to equilibrium level-density para
static float aimf_an; //!< ratio of asy-fission(imf) saddle to equilibrium level-density para
static bool normal;
static float Ucrit0; //!< Ucrit for J= 0, vanishing of pairing
static float Jcrit; //!< spin for the vanishing of pairing
float aden; //!< little-density parameter
float entropy; //!< entropy
float temp; //!< temperature
static float eFade; //!< fade out of shell effects with excitation energy
static float jFade; //!< fade out of shell effects with spin
float fU; //!< thermal excitation energy in MeV
static float const pi; //!< the mathematical constant \f$\pi\f$
public:
static CLevelDensity *instance(); //!< instance member to make this class a singleton
float getLittleA(int iA,float fU0,float fPairing=0.,float fShell=0.,
float fJ=0.,short iFission=0);
float getLittleA(int iA, short iFission);
float getU(float fU0,float fPairing, float fShell, float fJ);
float getAden();
float getLogLevelDensitySpherical(int iA,float fU0,float fPairing,
float fShell,float fJ,float fMinertia,
short iFission=0);
float getLogLevelDensitySpherical(int iA,float fU0,float fPairing,
float fShell);
float getTemp();
float getEntropy();
static void setLittleA(float k00,float aKappa0=0., float cKappa0=0.,
float kInfinity=12.);
static void setAfAn(float af_an0);
static void setAimfAn(float aimf_an0);
static void setUcrit(float Ucrit00, float Jcrit);
static float getAKappa();
static float getCKappa();
static float getK0();
static float getKInfinity();
static float getAfAn();
static float getAimfAn();
static void printParameters();
float getLogLevelDensityScission(int iA, float U, float adenInv=8.);
float J;
};
#endif
<file_sep>//
//___________________________________________________________
//
// CChart
//
#include "CChart.h"
int const CChart::iZmax = 136;
CChart* CChart::fInstance = 0;
//****************************************************
/**
* Constructor reads in files with neutron and
* proton rick limits
*/
CChart::CChart()
{
string fileName("tbl/chart.tbl");
string fullName;
if (getenv("GINPUT") == NULL) fullName = fileName;
else
{
string dir(getenv("GINPUT"));
fullName = dir+fileName;
}
ifstream ifFile (fullName.c_str());
if (ifFile.is_open() != 1)
{
cout << "file " << fullName << "is not found" << endl;
abort();
}
isotope = new SIsotope[iZmax+1];
iZindex = new int [iZmax+1];
int iZ,iAmin,iAmax;
for (;;)
{
ifFile >> iZ >> iAmin >> iAmax;
if (ifFile.bad()) break;
if (ifFile.eof()) break;
if (iZ > iZmax) break;
isotope[iZ].iAmin = iAmin;
isotope[iZ].iAmax = iAmax;
}
ifFile.close();
ifFile.clear();
//construct index file
iMassDim = 0;
for ( int i=0;i<iZmax+1;i++)
{
iZindex[i] = iMassDim;
iMassDim += isotope[i].iAmax - isotope[i].iAmin + 1;
}
}
CChart* CChart::instance()
{
if (fInstance == 0) {
fInstance = new CChart;
}
return fInstance;
}
//***********************************************************
/**
*descructor
*/
CChart::~CChart()
{
//descructor
delete [] isotope;
delete [] iZindex;
}
//**************************************************
/**
*returns the maxium iA for a given element that will be considered
*in the decay
\param iZ is the proton number
*/
int CChart::getAmin(int iZ)
{
//returns the minimum A value for a given Z
if (iZ > iZmax)
{
cout << "CHart above its limits" << endl;
cout << "iZ=" << iZ << endl;
abort();
}
return isotope[iZ].iAmin;
}
//**************************************************
/**
* Returns the minimum iA for a given element that will be considered
*in the decay
\param iZ is the proton number
*/
int CChart::getAmax(int iZ)
{
//returns the maximum A value for a given Z
if (iZ > iZmax)
{
cout << "CChart above its limits" << endl;
cout << "iZ=" << iZ << endl;
abort();
}
return isotope[iZ].iAmax;
}
//*******************************************************
/**
* Returns the index number of a particular nuclide
\param iZ is the proton number
\param iA is the mass number
*/
int CChart::getIndex(int iZ, int iA)
{
//returns the index in the mass table for a specified Z,A
if (iZ < 0)
{
cout << " Z < 0 in chart" <<endl;
return -1;
}
else if (iZ > iZmax)
{
//cout << " Z > iZmax in CChart " << endl;
return -1;
}
if (iA < isotope[iZ].iAmin || iA > isotope[iZ].iAmax)
{
//cout << " outside chart of nuclides defined in CChart" << endl;
return -1;
}
return iZindex[iZ] + iA - isotope[iZ].iAmin;
}
<file_sep>#include "CAngle.h"
using namespace std;
// following line is needed in ROOT version
//ClassImp(CAngle)
float const CAngle::pi=acos(-1.);
/**
* Constructor
*/
CAngle::CAngle(float theta0, float phi0)
{
theta = theta0;
phi = phi0;
}
//************************************************
CAngle CAngle::transform(CAngle angle1, CAngle angle2)
/**
* This subroutine performs a rotational transformation.
*
* theta1,phi1 are the coordinates (spherical angles in
* radians)of a unit vector in the original coordinate systems.
* the z axis is made to rotate in the phi=phi2 plane by an
*angle theta2. The coordinates of the vector in the new
*reference frame are theta3,phi3
\param angle1 is the initial (theta,phi) angles
\param angle2 specifies the (theta,phi) rotation
*/
{
//
// To calculate the angle between two vectors
// theta1,phi1 and theta2,phi2
// use CALL transform(theta1,phi1,-theta2,phi2,theta3,phi3)
// i.e. theta3 in the angle between them, note the negative sign
// on theta2
// rotate vector in x-y plane by -phi2
// and find cartesian coordinates
float xp = sin(angle1.theta)*cos(angle1.phi-angle2.phi);
float yp = sin(angle1.theta)*sin(angle1.phi-angle2.phi);
float zp = cos(angle1.theta);
// rotate vector in z-x plane by theta2
float zt = zp*cos(angle2.theta) - xp*sin(angle2.theta);
float xt = xp*cos(angle2.theta) + zp*sin(angle2.theta);
float yt = yp;
// rotate vector in x-y plane back by +phi2
// and find spherical coordinates
float theta3, phi3;
if (xt == 0.0 && yt == 0.0) phi3 = 0.;
else
{
phi3 = atan2(yt,xt) + angle2.phi;
if (phi3 >2.* pi) phi3 = phi3 - 2.*pi;
if (phi3 < 0.0) phi3 = phi3 + 2.*pi;
}
if (zt > 1.0) theta3 = 0.;
else if (zt < -1.0) theta3 = pi;
else theta3 = acos(zt);
CAngle angle3(theta3,phi3);
return angle3;
}
<file_sep>#include "CMass.h"
//folowing is needed in ROOT version
//#include "Rtypes.h"
/**
*!\brief fusion xsection, Bass model, excitation energy in fusion
*
* class to determine excitation energy and
*the critical angular momemtum in fusion.
* The fusion xsection \f$ \sigma(\ell) = \pi\lambda^2 \sum \frac{2\ell +1}
{1+\exp\left(\frac{\ell-\ell_0}{\Delta_{\ell}}\right)}\f$
* where \f$\lambda\f$ is really lambdabar
* \f$ \Delta_{\ell}\f$ is the diffuseness
*/
class CFus
{
protected:
int iZp; //!< projectile proton number
int iAp; //!<projectle mass number
int iZt; //!<target proton number
int iAt; //!<target mass number
float fElab; //!< lab energy in MeV
float R12; //!< sum of radii
float U; //!< reduced mass
float A; //!< const for Coulomb potential
float B; //!< const for centrifugal potential
float C; //!< nuclear potential constant
static float const D; //!< Bass potential parameter
static float const E; //!< Bass potential parameter
static float const G; //!< Bass potential parameter
static float const H; //!< Bass potential parameter
float E1; //!< critical energy 1 in Bass Model
float E2; //!< critical energy 2 in Bass Model
float MAX; //!< maximum L for fusion barrier
float CL1; //!< angular momentum assocaited with E1
float CL2; //!< angular momentum associated with E2
float W[300]; //!< fusion barrier for each L
float F(float R,float AL);
float FF(float R,float AL);
float FFF(float R,float AL);
float FFFF(float R, float AL);
public:
float plb; //!< pi-lambdabar-squared in mb
float dif; //!<diffuseness
float Ecm; //!<reaction center of mass energy in MeV
float vcm; //!<Compound nucleus velocity in cm/ns
float vbeam; //!<beam velocity in cm/ns
float Ex; //!< excitation energy
int iZcn; //!< compound nucleus atomic number
int iAcn;//!< compound nucleus mass number
CFus(float plb0,float dif0);
CFus(int iZprojectile, int iAprojectile,
int iZtarget, int iAtarget, float ELab, float dif0);
void init(float plb0,float dif0);
float getL0(float xsection);
float getBassL();
float getBassXsec();
//following is needed in ROOT version
//ClassDef(CFus,1); //Gemini CFus
};
<file_sep>#ifndef sstoreEvap_
#define sstoreEvap_
/**
*!\brief storage
*
* this structure store information on an evaporation channel (n,p,..)
* - the final quantities are Monte-Carlo selected from the many
* subchannels (SStoreChan)
*/
#include <vector>
struct SStoreEvap
{
float gamma; //!< decay width of channel in MeV
float energy; //!< energy of evaporated particle in MeV
short unsigned spin; //!< spin of daughter
short unsigned L; //!< orbitla angular momentum of evaporated particle
};
typedef std::vector<SStoreEvap> SStoreEvapVector;
typedef std::vector<SStoreEvap>::const_iterator SStoreEvapIter;
#endif
<file_sep>
// The abstract base class merson is used to solve coupled first-order
// differential equations. To use one must define the differential equation
// diff which is a pure virtual function in the merson class. Otherwise their
// are two user functions.
// initMerson(acc,step_min,step0,jtest): initializes everything
// solveMersion(y,xstart,xend): solves the coupled set of
// equations
//
// xstart: start value for the domain of integration (double)
// xend: end value for the domian of integration (double)
//
// y:
// TNT array containing the dependent variables. When entering the routine
// the function values y(x),k=1,n and when returning to the calling
// program the computed function values y(xend),k=1,n
// the TNT array contains the number of function values n
//
// acc: prescribed relative accuracy ( to be obtained for all function values
// in the array y)
//
// step_min: absolute value of the minimum step length wanted
// step0: initial step length
//
//jtest = test parameter related to the steplength in the following way.
//jtest = 0, if during the calculation we get ABS(step) less than step_min (by
//repeated halving of the steplength), than an error message is printed,
//ok is set equal to 0 followed by return to the calling program
//jtest = 1, checking as for jtest=0, but the calculation will continue
//with the fixed step length step_min
//
// this class originated from the CERN LIBRARY no D 208.
// PURPOSE = step by step integration of a system of first order differential
// equations
//
// dyk(x)/dx = fk(x,y1(x),y2(x),.....,yn(x)), k=1,n
//
// with automatic error controll using the method due to merson.
// ok:
// a logical variable which is set equal to 1 when entering the
// routine. the value later is depending of jtest in the following way.
// jtest=1, ok= 1 always
// jtest=0, ok= 0 if the steplength becomes too small ( see
// description for jtest)
//
//base class merson
#include <valarray>
#include <iostream>
using namespace std;
class CMerson
{
public:
CMerson(){}
void initMerson (double,double,double,int);
void solveMerson(valarray<double>*,double,double);
double acc;
double step_min;
double step0;
int jtest;
int ok;
virtual valarray<double> diff (double, valarray<double>)=0;
};
<file_sep>#include "CMass.h"
#include <cmath>
CMass* CMass::fInstance = 0; // mod-TU
/**
* Constructor
*/
CMass::CMass()
{
chart = CChart::instance();
fExpMass = new float [chart->iMassDim];
fCalMass = new float [chart->iMassDim];
fFRM = new float [chart->iMassDim];
fPair = new float [chart->iMassDim];
//fBeta2 = new float [chart->iMassDim];
fShell = new float [chart->iMassDim];
fShell2 = new float [chart->iMassDim];
ReadThomasFermiFile();
ReadFRDMFile();
fExpMass[0] = 8.071;
fExpMass[1] = 7.289;
fCalMass[0] = 8.071;
fCalMass[1] = 7.289;
int iZmin = 4;
int iZmax = 136;
for (int iZ =iZmin;iZ<=iZmax;iZ++)
{
int iNmin = chart->getAmin(iZ)-iZ;
int iNmax = chart->getAmax(iZ)-iZ;
//cout << iZ << " " << iNmin << " " << iNmax << endl;
for (int iN = iNmin;iN<= iNmax;iN++)
{
int index = chart->getIndex(iZ,iZ+iN);
fPair[index] = getPairing2(iZ,iZ+iN);
//redefine the shell correction to be difference between
//experimental mass and (FRM masses plus given pairing corrections)
fShell2[index] = fExpMass[index] - fPair[index] - fFRM[index];
}
}
for (int iZ =iZmin;iZ<=iZmax;iZ++)
{
int iNmin = chart->getAmin(iZ)-iZ;
int iNmax = chart->getAmax(iZ)-iZ;
for (int iN = iNmin;iN<= iNmax;iN++)
{
int index = chart->getIndex(iZ,iZ+iN);
float fpairN;
if(iN%2 == 1) fpairN = 0.;
else if (iN-1 >= iNmin && iN+1 <= iNmax)
{
fpairN = -(getShellCorrection2(iZ,iZ+iN-1) +
getShellCorrection2(iZ,iZ+iN+1))/2.
+ getShellCorrection2(iZ,iZ+iN);
}
else if (iN-1 < iNmin) fpairN = -getShellCorrection2(iZ,iZ+iN+1)
+ getShellCorrection2(iZ,iZ+iN);
else if (iN+1 > iNmax) fpairN = -getShellCorrection2(iZ,iZ+iN-1)
+ getShellCorrection2(iZ,iZ+iN);
//then proton pairing
float fpairZ;
if(iZ%2 == 1) fpairZ = 0.;
else if (iZ+1 <= iZmax) fpairZ =
-(getShellCorrection2(iZ-1,iZ-1+iN)
+ getShellCorrection2(iZ+1,iZ+iN+1))/2.
+ getShellCorrection2(iZ,iZ+iN);
else if (iZ+1 > iZmax) fpairZ =
-getShellCorrection2(iZ+1,iZ+iN+1)+ getShellCorrection2(iZ,iZ+iN);
//fpairZ = 0.;
fPair[index] = fpairN + fpairZ + getPairing2(iZ,iZ+iN);
fShell[index] = fExpMass[index] - fFRM[index] - fPair[index];
}
}
}
CMass* CMass::instance() // mod-TU
{
if (fInstance == 0) {
fInstance = new CMass;
}
return fInstance;
}
//**********************************************
/**
* Destructor
*/
CMass::~CMass()
{
delete [] fExpMass;
delete [] fCalMass;
delete [] fFRM;
// delete [] fBeta2;
delete [] fShell;
delete fShell2;
}
//********************************************
/**
* Returns the experimental mass excess
*
* If teh experimental excess is not known, then the Moller Nix value
* is returned
\param iZ is the proton number
\param iA is the mass number
*/
float CMass::getExpMass(int iZ, int iA)
{
//find location of nuclide in array where the mass is stored
int i = chart->getIndex(iZ,iA);
return fExpMass[i];
}
//********************************************
/**
* Returns the calculated mass excess from Moller and Nix
*
\param iZ is the proton number
\param iA is the mass number
*/
float CMass::getCalMass(int iZ, int iA)
{
//find location of nuclide in array where the mass is stored
int i = chart->getIndex(iZ,iA);
return fCalMass[i];
}
//********************************************
/**
* Returns the shell correction from Moller and Nix
*
\param iZ is the proton number
\param iA is the mass number
*/
float CMass::getShellCorrection(int iZ, int iA)
{
//find location of nuclide in array where the mass is stored
int i = chart->getIndex(iZ,iA);
return fShell[i];
}
//********************************************
/**
* Returns the shell correction from Moller and Nix
*
\param iZ is the proton number
\param iA is the mass number
*/
float CMass::getShellCorrection2(int iZ, int iA)
{
//find location of nuclide in array where the mass is stored
int i = chart->getIndex(iZ,iA);
return fShell2[i];
}
//********************************************
/**
* Returns the liquid drop mass from moller and Nix
\param iZ is the protom number
\param iA is the mass number
*/
float CMass::getLiquidDropMass(int iZ, int iA)
{
//find location of nuclide in array where the mass is stored
int i = chart->getIndex(iZ,iA);
if ( i == -1)
{
return -1000;
}
return fFRM[i];
}
//*************************************************
/**
*
* Calculates macroscopic finite range model masses of spherical
* nucleus using formula of Krappe, Nix, and Sierk.
*
* Reference- (Phys Rev C20, 992 (1979))
* modified to use the parameters of Moller + Nix Nucl. Phys. A361(1981)
* 117. Pairing correction term for odd-odd nuclei
* is included, as this is the most appropriate ground state for hot nuclei
* where shell and pairing effects have washed out.
\param iZ is the proton number
\param iA is the mass number
*/
float CMass::getFiniteRangeMass(int iZ, int iA)
{
return getFiniteRangeMass((float)iZ,(float)iA);
}
//**********************************************************
/**
*
* Calculates macroscopic finite range model masses of spherical
* nucleus using formula of Krappe, Nix, and Sierk.
*
* Reference- (Phys Rev C20, 992 (1979))
* modified to use the parameters of Moller + Nix Nucl. Phys. A361(1981)
* 117. Pairing correction term for odd-odd nuclei
* is included, as this is the most appropriate ground state for hot nuclei
* where shell and pairing effects have washed out.
\param fZ is the proton number
\param fA is the mass number
*/
float CMass::getFiniteRangeMass(float fZ, float fA)
{
float fN = fA - fZ;
float fA13 = pow(fA,(float)(1./3.));
float fA23 = pow(fA13,2);
// relative neutron excess
float fI = (fN-fZ)/fA;
float fFiss = pow(fZ,2)/fA13;
// neutron-proton terms
float const fMassN = 8.071431;
float const fMassH = 7.289034;
float fEnz = fMassN*fN + fMassH*fZ;
//Volume energy
float const fAv = 15.9937;
float const fKv = 1.927;
float fEvol = -fAv*(1.-fKv*pow(fI,2))*fA;
// Surface energy
float const fa = 0.68;
float const fR0 = 1.16;
float const fAs = 21.13;
float const fKs = 2.3;
float fX=fa/(fR0*fA13);
float fact=1.-3.*pow(fX,2)
+ (1.+1./fX)*(2.+3.*fX+3.*pow(fX,2))*exp(-2./fX);
float fEsurf = fAs*(1.-fKs*pow(fI,2))*fA23*fact;
//Coulomb energy
float const e2 = 1.4399764;
fact = fFiss-0.76361*pow(fZ,(float)(4./3.))/fA13;
float fECoul = 0.6*e2/fR0*fact;
//Wigner term
float const fW = 36.;
float const ael = 1.433e-5;
float fEwigner = fW*fabs(fI)-ael*pow(fZ,(float)2.39);
//correction to Coulomb energy for diffuse surface
//see Davies & Nix Phys. Rev. C14 (1976) 1977
float const b = 0.99;
float ad=0.7071*b;
fX = ad/(fR0*fA13);
fact= 1 - 1.875*fX+2.625*pow(fX,3)
-.75*exp(-2./fX)*(1.+4.5*fX+7.*pow(fX,2)+3.5*pow(fX,3));
float fEcd = -3.*pow(fZ,2)*e2*pow(ad,2)/pow(fR0*fA13,3)*fact;
// correction to coulomb energy due to proton form factor
float const rp = 0.8;
float akf=1./fR0*pow(7.06858*fZ/fA,1./3.);
fX = pow(rp*akf,2);
float fEcpf=-0.125*pow(rp,2)*e2/pow(fR0,3)
*(3.0208-0.113541667*fX+0.0012624*pow(fX,2))*pow(fZ,2)/fA;
//A0 term
float const c0 = 4.4;
float fEa0=c0;
//Charge asymmetry term
float const ca = 0.212;
float fEca=ca*(pow(fZ,2)-pow(fN,2))/fA;
// pairing term for odd-odd nuclei
float deltau = 12./sqrt(fA);
float deltal = 20./fA;
float fEpair =deltau - 0.5 * deltal;
// add all terms
return fEnz+fEvol+fEsurf+fECoul+fEwigner+fEcd+fEcpf+fEa0+fEca+fEpair;
}
//******************************************
/**
* Returns the pairing correction to the mass formula.
* From from Moller Nix is used.
\param iZ is the proton number
\param iA is the mass number
*/
float CMass::getPairing(int iZ, int iA)
{
return fPair[chart->getIndex(iZ,iA)];
}
//****************************************
/**
* Returns the pairing correction to the mass formula.
* From from <NAME> is used.
\param iZ is the proton number
\param iA is the mass number
*/
float CMass::getPairing2(int iZ, int iA)
{
if(iZ==0 || iZ==iA)
return 0.;
float fZ = iZ;
float fA = iA;
float fN = fA - fZ;
int iN = iA - iZ;
int ioez = iZ%2;
int ioen = iN%2;
float fPairing;
if (iN == iZ && ioez ==1)
{
fPairing = 4.8/pow(fN,(float)(1./3.))
+ 4.8/pow(fZ,(float)(1./3.)) - 6.6/pow(fA,(float)(2./3.))
+ 30./fA;
}
else if (ioez == 1 && ioen == 1)
{
fPairing = 4.8/pow(fN,(float)(1./3.))
+ 4.8/pow(fZ,(float)(1./3.)) - 6.6/pow(fA,(float)(2./3.));
}
else if (ioez == 1 && ioen == 0)
{
fPairing = 4.8/pow(fZ,(float)(1./3.));
}
else if (ioez == 0 && ioen == 1)
{
fPairing = 4.8/pow(fN,(float)(1./3.));
}
else fPairing = 0.;
//want to redefine odd-odd to have zero paring energy
fPairing -= 4.8/pow(fN,(float)(1./3.))
+ 4.8/pow(fZ,(float)(1./3.)) - 6.6/pow(fA,(float)(2./3.));
if (iN == iZ) fPairing -= 30./fA;
return fPairing;
}
//******************************************
/**
* Reads in the mass table from Moller and Nix
*/
void CMass::ReadFRDMFile()
{
string fileName("tbl/mass.tbl");
string fullName;
if (getenv("GINPUT") == NULL) fullName = fileName;
else
{
string dir(getenv("GINPUT"));
fullName = dir+fileName;
}
ifstream ifFile (fullName.c_str());
if (ifFile.fail())
{
cout << "could not open" << fullName << endl;
abort();
}
while (!ifFile.eof())
{
char integ[6]={" "};
int izz,iaa;
for (int i=0;i<5;i++) integ[i] = ifFile.get();
izz = atoi(integ);
for (int i=0;i<5;i++) integ[i] = ifFile.get();
// inn = atoi(integ); // Unused
for (int i=0;i<5;i++) integ[i] = ifFile.get();
iaa = atoi(integ);
char floaty[11]={" "};
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
// fb = atof(floaty); // Unused
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
float f1,f2,f3;
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
f1 = atof(floaty);
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
f2 = atof(floaty); //calculated mass
bool there = 0;
for (int i=0;i<10;i++)
{
floaty[i] = ifFile.get();
if (floaty[i] != ' ') there = 1;
}
f3 = atof(floaty);//experimental mass
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
// f4 = atof(floaty); // Unused
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
// f5 = atof(floaty); // Unused
for (int i=0;i<10;i++) floaty[i] = ifFile.get();
// f6 = atof(floaty); // Unused
//read to end of line
for (;;)
{
if (ifFile.get() == 10) break;
if (ifFile.eof()) break;
}
int index = chart->getIndex(izz,iaa);
if (index >= 0)
{
float fPair = getPairing2(izz,iaa);
if (there) fExpMass[index] = f3;
else fExpMass[index] = f2;
fCalMass[index] = f2;
fFRM[index] = f2 - f1 - fPair;
fShell[index] = f1;
//fBeta2[index] = fb;
/*
if (izz == 10) cout << iaa << " " << iaa-izz << " " <<
fFRM[index] << " " << fShell[index] << " " << fPair <<
" " << fExpMass[index] << " " << fCalMass[index] << " "
<< there << endl;
*/
}
}
ifFile.clear();
ifFile.close();
}
//******************************************
/**
* Reads in the mass table from the Thomas Fermi Model
* of Myers and Swietcki
*/
void CMass::ReadThomasFermiFile()
{
string fileName("tbl/mass_tf.tbl");
string fullName;
if (getenv("GINPUT") == NULL) fullName = fileName;
else
{
string dir(getenv("GINPUT"));
fullName = dir+fileName;
}
ifstream ifFile (fullName.c_str());
if (ifFile.fail())
{
cout << "could not open mass_tf.tbl" << endl;
abort();
}
//skip introductory remarks in file
string line;
for (int i=0;i<66;i++)
{
getline(ifFile,line);
}
while (!ifFile.eof())
{
char integ3[4]={" "};
int izz,iaa;
for (int i=0;i<3;i++) integ3[i] = ifFile.get();
char integ4[5]={" "};
izz = atoi(integ3);
for (int i=0;i<4;i++) integ4[i] = ifFile.get();
//int inn = atoi(integ4); //Unused
for (int i=0;i<4;i++) integ4[i] = ifFile.get();
iaa = atoi(integ4);
char float5[11]={" "};
for (int i=0;i<5;i++) float5[i] = ifFile.get();
for (int i=0;i<5;i++) float5[i] = ifFile.get();
// char float8[9]={" "}; // Unused
for (int i=0;i<8;i++) float5[i] = ifFile.get();
char float6[7]={" "};
for (int i=0;i<6;i++) float6[i] = ifFile.get();
float fshell = atof(float6);
for (int i=0;i<5;i++) float5[i] = ifFile.get();
float fPairing = atof(float5);
for (int i=0;i<6;i++) float6[i] = ifFile.get();
for (int i=0;i<8;i++) float5[i] = ifFile.get();
char float7[8]={" "};
for (int i=0;i<7;i++) float7[i] = ifFile.get();
float f1 = atof(float7);
for (int i=0;i<7;i++) float7[i] = ifFile.get();
float f2 = atof(float7);
//read to end of line
for (;;)
{
if (ifFile.get() == 10) break;
if (ifFile.eof()) break;
}
int index = chart->getIndex(izz,iaa);
if (index >= 0)
{
//note do not use fPairing from table,
//we have refined odd-odd to have zero pairing
fPairing = getPairing2(izz,iaa);
fExpMass[index] = f2;
if (izz < 5) fCalMass[index] = f2;
else fCalMass[index] = f1;
fFRM[index] = fCalMass[index] - fshell - fPairing;
fShell[index] = fshell*2.;
}
}
ifFile.clear();
ifFile.close();
}
<file_sep>#include <cmath>
#include "CMass.h"
/**
*!\brief scission energies
*
* calculates information on scission point for saddle-to-scission
* evaporation and for fission mass distributions
*/
class CScission
{
protected:
static float const e2; //!< \f$e^{2} = 1.44 MeV fm^{-1}\f$
static float const kRotate; //!< constant for rotational energy
static float const slopeViola; //!< for Viola systematics of fission KE
static float const constViola; //!< for Viola systematics of fission KE
float mu0; //!< reduced mass
float Vc0; //!< Coulomb self energy of a symmetric frag
float R1; //!< radius of frag1 in fm
float momInertia1; //!< moment of inertia of frgament1
float R2; //!< radius of frag1 in fm
float momInertia2; //!< moment of inertia of frgament1
float k1; //!< part of the rotational energy
bool sym; //!< logical symmetic of non symmetric fission
float Z1;//!< atomic number of lighter fragment after fission
float Z2;//!< atomic number of heavier fragment
float A1;//!< mass number of lighter fragment after fission
float A2;//!< mass number of heavier fragment
CMass * mass; //!< gives mass excess
public:
static float const r0; //!< constant R=r0*A^(1/3)
float sep; //!< separation between the surafces of the 2 spheres
float sep0; //!< separation determined in init()
float sep1; //!< separation determined in sigmaFissionSystematics()
int iA; //!< mass number of system
int iZ; //!< proton number of system
float A; //!< float value of iA
float Z; //!< float value of iZ
float fJ; //!< spin of system
float Esymmetric; //!< energy for symmetric mass split
float ekTot; //!< total fission kinetic energy from getFissionKineticEnergy()
float Erotate1; //!<rotational energy of fragment1
float Erotate2; //!<rotational energy of fragment2
float Epair1; //!< pairing energy of frag1
float Epair2; //!< pairing energy of frag2
float Eshell1; //!< shell energy of frag1
float Eshell2; //!< shell energy of frag2
float EkCoul; //!< Colomb part of total fisison kinetic energy
float EkRot; //!< rotational part of total fission kinetic energy
CScission(int iZ0,int iA0,float fJ0, int iChan);
CScission();
void init(int iZ0,int iA0,float fJ0,int ichan,float Z1=0.,float A1=0.);
float getSep(float EkViola);
float getScissionEnergy();
float getScissionEnergy(int iZ1,int iA1);
float getFissionKineticEnergy(int iZ1, int iA1);
float sigmaFissionSystematicsScission(int iZ, int iA, float fJ, float fUscission);
float sigmaFissionSystematicsSaddle(int iZ, int iA, float fJ, float fUscission);
};
<file_sep>class CAvrigeanu
{
public:
//real
double R;
double a;
double V;
double Rc;
//imaginary
double Ri;
double ai;
double Wvol;
double Wsur;
double mu;
double zz;
void findPara(double Z, double A, double E);
CAvrigeanu(){};
};
<file_sep>#include "CPotPara.h"
#include <iostream>
using namespace std;
//*********************************************************************
// CPotPara constructor
CPotPara::CPotPara( double V0, double R0, double a0)
:V(V0),R(R0),a(a0)
{}
//********************************************************************
// initialization
void CPotPara::init(double V0, double R0, double a0)
{
V = V0;
R = R0;
a = a0;
}
//*****************************************************************
// Wood Saxon form factor
double CPotPara::woodSaxon(double r)
{
return -V/(1.+exp((r-R)/a));
}
//******************************************************************
//derivative of Wood Saxon *-4a
double CPotPara:: derWoodSaxon(double r)
{
float fact = exp((r-R)/a);
return -4.*fact*V/pow(1+fact,2);
}
//******************************************************************
//alternative surface potential - Gaussian
double CPotPara::gauss(double r)
{
return -V*exp(-pow((r-R)/a,2));
}
//*****************************************************************
CPotPara CPotPara::copy()
{
CPotPara out(V,R,a);
return out;
}
//******************************************************************
void CPotPara::print()
{
cout << "V= " << V << " R= " << R << " a= " << a << endl;
}
<file_sep>#ifndef lightP_
#define lightP_
#include "CNuclide.h"
#include "CTlBarDist.h"
#include "CSigBarDist.h"
#include "SStoreEvap.h"
#include <vector>
/**
*!\brief deals with a particular evaporation channel
*
* Class CLightP contains all the important information
* concerning a light particle evaporation channel, it has
* pointers to a cTlArray class to calculate transmission coeff.
*/
class CLightP : public CNuclide
{
protected:
bool mustDelete; //!< bool to remember that we must delete the tLArray
public:
CLightP(int iZ,int iA,float fS,string sName);
CLightP(int,int,float,CTlBarDist*,CSigBarDist*);
~CLightP(); //!< destructor
CTlBarDist *tlArray; //!< gives transmission coefficients
CSigBarDist *sigBarDist; //!< gives inverse xsections for charged part
float suppress; //!< suppression factor to scale Hauser-Feshbach width
float fMInertia; //!< moment of inertia of residue
float fMInertiaOrbit; //!< moment of inerria for orbit of light P
float separationEnergy; //!< separation energy in MeV
float fPair; //!< pairing energy of residue
float fShell; //!< shell correction for residue
CNuclide residue; //!< contains info on the daughter nucleus
bool odd; //!< true for odd mass
SStoreEvapVector storeEvap; //!<store evaporation info
float width; //!<decay width in MeV
float rLight; //!< radius of light particle in fm
};
#endif
<file_sep>#include "CSigCharged.h"
#include <cstdlib>
/**
*!\brief inverse cross section with barrier distributions
*
* calculates transmission coefficientinverse cross sections
* using a simplistic barrier
* distribution logic. The final result is the average of three
* inverse cross sections.
* \f$ T_{l}(Ek) = \frac{T_{l}^{R_{0}-\Delta R}(Ek) + T_{l}^{R_{0}}(Ek) + T_{l}^{R_{0}+\Delta R}(Ek)}{3} \f$
* where \f$ T_{l}^{R_{0}}\f$ is the standard coeff derived using the IWBC and
* global optical-model potential. The other two are for when the radius of
* the nuclear potential is shifted by \f$ \pm \Delta R \f$.
* where \f$ \Delta R = width*\sqrt{temperature} \f$.
*/
class CSigBarDist
{
private:
CSigCharged* sigCharged[3]; //!< arrays for standard radii and +- width0
bool one; //!< if true, no distribution, just standard radius is used
static float width; //!< width paramter determines shifted radii
static float const width0; //!< results readin from file for this shift
float Z; //!< calls to getInverseXsec refer to this residual proton number
float A; //!< calls to getInverseXsec refer to this residual mass number
float Zp; //!<proton number of evaporated particle
float Ap; //!<mass number of evaporated particle
public:
CSigBarDist(string, float Zp0, float Ap0 );
~CSigBarDist();
float getInverseXsec(float fEk, float temp);
static void setBarWidth(float width00);
static float getBarWidth();
static void printParameters();
void prepare(float Z, float A);
float getBarrier();
};
<file_sep>#include "CWeight.h"
float const fact0=0.3;
//****************************************************************************
/**
* Determines the degree of weighting for enhance IMF emission
\param gammaLight decay width for light-particle evaporation (MeV)
\param gammaImf decay width for IMF emission (MeV)
\param gammaFission Fission decay width (MeV)
\param gammaGamma Gamma-ray decay width
*/
void CWeight::findFactor(float gammaLight, float gammaImf, float gammaFission,
float gammaGamma)
{
if (gammaImf <= 0.)
{
fact = 1.;
iWeight = 0;
return;
}
if (gammaLight+gammaFission+gammaGamma <=0.)
{
fact = 1.;
iWeight = 0;
return;
}
float gammaTot = gammaLight+gammaImf+gammaFission+gammaGamma;
fact = fact0*(gammaTot-gammaImf)/(1.-fact0)/gammaImf;
if (fact < 1.)fact = 1.;
}
//*********************************************************
/**
* Chooses the decay channel given the decay widths.
* If IMF weighting is truned on, then IMF emission is enhanced and
* a running weight is calculated.
\param gammaLight decay width for light-particle evaporation (MeV)
\param gammaImf decay width for IMF emission (MeV)
\param gammaFission Fission decay width (MeV)
\param gammaGamma Gamma-ray decay width
\param xran Random number
*/
int CWeight::chooseChannel(float gammaLight, float gammaImf,
float gammaFission, float gammaGamma, float xran)
{
if (iWeight == 1) findFactor(gammaLight,gammaImf,gammaFission,gammaGamma);
float fact1 = 1.;
if (iWeight) fact1 = fact; //weighting turned on
float Gamma_real = gammaLight + gammaImf + gammaFission + gammaGamma;
float Gamma_weight = gammaLight + gammaImf*fact1 + gammaFission + gammaGamma;
float probLight = gammaLight/Gamma_weight;
float probImf = gammaImf*fact1/Gamma_weight + probLight;
float probFission = gammaFission/Gamma_weight + probImf;
//no need of weighting if only imf emission
if (gammaLight + gammaFission + gammaGamma <=0.) Gamma_weight = Gamma_real;
int iChan;
if (xran < probLight)
{
iChan = 0;
runningWeight *= Gamma_weight/Gamma_real;
if (iWeight > 0)iWeight++;
}
else if (xran < probImf)
{
iChan = 1;
runningWeight *= Gamma_weight/fact1/Gamma_real;
iWeight = 0; //turn weighting off for rest of event
}
else if (xran < probFission)
{
iChan =2;
runningWeight *= Gamma_weight/Gamma_real;
iWeight = 0; //turn weighting off for the rest of the event
}
else
{
iChan =3; //gamma ray emission
runningWeight *= Gamma_weight/Gamma_real;
iWeight = 0; //turn weighting off for the rest of the event
}
return iChan;
}
//************************************************************************
/**
* turns on IMF weighting, i.e. emhanced IMF emissions
*/
void CWeight::setWeightIMF()
{
iWeight = 1;
}
//**********************************************************************
/**
* When IMF weighting is turn on, this routine returns the weighting factor
* which should be used to increment all histograms. If weighting is turned
* off, then unity is returned
*/
float CWeight::getWeightFactor()
{
return runningWeight;
}
<file_sep>#include "CRandom.h"
#include <cmath>
/**
*!\brief angular distributions
*
* class to randomly selects a polar angle theta
* of an emitted fragment
*
*/
class CAngleDist
{
protected:
CRandom *ran; //!<random number generator
float ** dist; //!<array containing sampled distributions
static int const maxL; //!<maximum angular distribution for
//!<which distributions are made
static int const nAngle; //!< number of angular bins used
//!<to sample distributions
static float const pi; //!< the mathematical constant
public:
CAngleDist();
~CAngleDist();
float getTheta(int l);
};
<file_sep>#include "CAngleDist.h"
int const CAngleDist::maxL = 20;
int const CAngleDist::nAngle = 90;
float const CAngleDist::pi= acos(-1.);
//**********************************************************
/**
* Constructor
*/
CAngleDist::CAngleDist()
{
ran = CRandom::instance();
dist = new float* [maxL];
for (int i=0;i<maxL;i++)
{
dist[i] = new float [nAngle];
for (int j=0;j<nAngle;j++)
{
float theta = (float)(j+1)/180.*pi;
dist[i][j] = pow(sin(theta),2*i+1);
if (j > 0) dist[i][j] += dist[i][j-1];
}
for (int j=0;j<nAngle;j++)
{
dist[i][j] /= dist[i][nAngle-1];
}
}
}
//***********************************************************
/**
* Destructor
*/
CAngleDist::~CAngleDist()
{
for (int i=0;i<maxL;i++)
{
delete [] dist[i];
}
delete [] dist;
}
//*************************************************************
//!returns a random polar angle associated with a specified angular momentum
/**
* The angle is chosen from the
* distribution \f$P_l^l[cos(\theta)]^2 sin(\theta)\f$.
* This angle is expressed in radians.
* If the angular momentum is above maxL, an angle of
* 90 degrees is returned
\param l is the orbital angular-momentum quantum number
*/
float CAngleDist::getTheta(int l)
{
if (l >=maxL) return pi/2.;
float xran = ran->Rndm();
int i=0;
for (;;)
{
if (xran < dist[l][i]) break;
i++;
if (i == nAngle) break;
}
float theta = ((float)(i) + ran->Rndm())*pi/180.;
if (ran->Rndm() > 0.5) theta = pi - theta;
return theta;
}
<file_sep>#include "CYrast.h"
#include <cmath>
CYrast* CYrast::fInstance = 0; // singleton
double CYrast::addBar = 0.;
double const CYrast::pi=acos(-1.);
float const CYrast::deltaJ= 3.;
bool CYrast::first = 1;
bool CYrast::bForceSierk = 0;
float const CYrast::kRotate=41.563;
//RLDM constants
float const CYrast::x1h[11][6]={
{0.0,0.0,0.0,0.0,0.0,0.0},
{-0.0057,-0.0058,-0.006,-0.0061,-0.0062,-0.0063},
{-0.0193,-0.0203,-0.0211,-0.022,-0.023,-0.0245},
{-0.0402, -0.0427,-0.0456,-0.0497,-0.054,-0.0616},
{-0.0755,-0.0812,-0.0899,-0.0988,-0.109,-0.12},
{-0.1273,-0.1356,-0.147,-0.1592,-0.1745,-0.1897},
{-0.1755,-0.1986,-0.2128,-0.2296,-0.251,-0.26},
{-0.255,-0.271,-0.291,-0.301,-0.327,-0.335},
{-0.354,-0.36,-0.365,-0.372, -0.403,-0.42},
{0.0,0.0,0.0,0.0,0.0,0.0},
{0.0,0.0,0.0,0.0,0.0,0.0}};
float const CYrast::x2h[11][6]={
{0.0,0.0,0.0,0.0,0.0,0.0},
{-0.0018,-0.0019,-0.00215,-0.0024,-0.0025,-0.003},
{-0.0063,-0.00705,-0.0076,-0.0083,-0.0091,-0.0095},
{-0.015,-0.0158,-0.0166,-0.0192,-0.0217,-0.025},
{-0.0245,-0.0254,-0.029,-0.0351,-0.0478,-0.0613},
{-0.0387,-0.0438,-0.0532,-0.0622,-0.0845,-0.0962},
{-0.0616,-0.0717,-0.0821,-0.0972,-0.1123,-0.1274},
{-0.0793, -0.1014,-0.1138,-0.1262,-0.1394,-0.1526},
{-0.12,-0.134,-0.1503,-0.1666,-0.1829,-0.1992},
{-0.1528,-0.171,-0.1907,-0.2104,-0.2301,-0.2498}
,{0.0,0.0,0.0,0.0,0.0,0.0}};
float const CYrast::x3h[20][10]={
{0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0},
{-0.00012,-0.00014,-0.00016,-0.00018,-0.0002,-0.00024,-0.00029,-0.00036,
-0.00065,-0.00089},
{-0.00047,-0.0005,-.00058,-.00065,-.00074,-.00085,-.00101,-.00124,
-.00138,-.00178},
{-0.001,-0.00105,-0.00124,-0.00138,-0.00156,-0.00179,-0.00275,-0.00292,
-0.003,-0.003},
{-0.00176,-0.0019,-0.00211,-0.00235,-0.00263,-0.00298,-0.00449,-0.0053,
-0.0053,-0.0053},
{-0.003,-0.00308,-0.00318,-0.00352,-0.00392,-0.00417,-0.0062,-0.0062,
-0.0062,-0.0062},
{-0.00374,-0.0041,-0.00444,-0.00488,-0.00521,-0.00545,-0.0066,-0.0066,
-0.0066,-0.0066},
{-0.0053,-0.0055,-0.00585,-0.0064,-0.00695,-0.007,-0.007,-0.007,-0.007,-0.007},
{-0.00632,-0.007,-0.00742,-0.00792,-0.00856,-0.009,-0.009,-0.009,
-0.009,-0.009},
{-0.0079,-0.0085,-0.01022,-0.0119,-0.012,-0.012,-0.012,-0.012,-0.012,-0.012},
{-0.00944,-0.0102,-0.0142,-0.0182,-0.019,-0.019,-0.019,-0.019,-0.019,-0.019},
{-0.0112,-0.0133,-0.0182,-0.0238,-0.024,-0.024,-0.024,-0.024,-0.024,-0.024},
{-0.01303,-0.0178,-0.0226,-0.0274,-0.028,-0.028,-0.028,-0.028,-0.028,-0.028},
{-0.0165,-0.0254,-0.0343,-0.0343,-0.034,-0.034,-0.034,-0.034,-0.034,-0.034},
{-0.0203,-0.033,-0.04,-0.04,-0.04,-0.04,-0.04,-0.04,-0.04,-0.04},
{-0.025,-0.0406,-0.046,-0.047,-0.047,-0.047,-0.047,-0.047,-0.047,-0.047},
{-0.03036,-0.0482,-0.048,-0.048,-0.048,-0.048,-0.048,-0.048,-0.048,-0.048},
{-0.0363,-0.0558,-0.056,-0.056,-0.056,-0.056,-0.056,-0.056,-0.056,-0.056},
{-0.04234,-0.0634,-0.064,-0.064,-0.064,-0.064,-0.064,-0.064-0.064,-0.064},
{0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}};
float const CYrast::x1b[11][6]={
{0.28,.243,.221,.208,.195,.18},
{.211,.186,.17,.1506,.136,.12},
{0.152,.131,.1155,.096,.0795,.0625},
{.09725,.0795,.065,.0506,.0375,0.0253},
{.05771,.0455,.03414,.0235,.014,.0065},
{.03325,.0235,.0153,.0081,0.001,.0},
{.01625,.009,.0032,.0,.0,.0},
{.0071,.0,.0,.0,.0,.0},
{.0,.0,0.0,.0,.0,.0},
{.0,.0,.0,.0,.0,.0},
{0.,0.,0.,0.,0.,0.}};
float const CYrast::x2b[11][6]={
{.18,.1695,.1515,.133,.1155,.0949},
{.1495,.1363,.1165,.099,.0815,.0594},
{.12,.1032,.0864,.0678,.0469,.028},
{.09,.0725,.0556,.037,.019,.0057},
{.0625,.045,.0304,.016,.005,0.},
{.0406,.0264,.0151,.0052,0.,0.},
{.0253,.0144,.0027,0.,0.,0.},
{.0141,.006,0.,0.,0.,0.},
{.0065,.0008, 0.,0.,0.,0.},
{.002,0.,0.,0.,0.,0.},
{0.,0.,0.,0.,0.,0.}};
float const CYrast::x3b[20][10]={
{.0949,.0755,.0564,.0382,.0223,.0121,.00588,.00242,.00069,.0001},
{.0873,.0684,.049,.0306,.0162,.0074,.00267,.00055,0.,0.},
{.0801,.061,.0418,.0235,.0108,.00373,.00071,0.,0.,0.},
{.073,.054,.035,.0178,.0062,.00125,0.,0.,0.,0.},
{.0661,.047,.0284,.012,.0025,0.,0.,0., 0.,0.},
{.0594,.0404,.022,.0065,0.,0.,0.,0.,0.,0.},
{.0528,.034,.0159,.002,0.,0.,0.,0.,0.,0.},
{.0465,.0277,.01,0.,0.,0.,0.,0.,0.,0.},
{.0401,.0217,.0044,0.,0.,0.,0.,0.,0.,0.},
{.0339,.0158,.00024,0.,0.,0.,0., 0.,0.,0.},
{.028,.0106,0.,0.,0.,0.,0.,0.,0.,0.},
{.0219,.0064,0.,0.,0., 0.,0.,0.,0.,0.},
{.0164,.0025,0.,0.,0.,0.,0.,0.,0.,0.},
{.0122,0.,0.,0., 0.,0.,0.,0.,0.,0.},
{.0085,0.,0.,0.,0.,0.,0.,0.,0.,0.},
{.0057,0.,0., 0.,0.,0.,0.,0.,0.,0.},
{.0035,0.,0.,0.,0.,0.,0.,0.,0.,0.},
{.0016,0.,0.,0.,0.,0.,0.,0.,0.,0.},
{0.,0.,0.,0.,0.,0.,0.,0.,0.,0.},
{0.,0.,0., 0.,0.,0.,0.,0.,0.,0.}};
//sierk constants
double const CYrast:: emncof[4][5]={
{-9.01100e2,-1.40818e3, 2.77000e3,-7.06695e2, 8.89867e2},
{1.35355e4,-2.03847e4, 1.09384e4,-4.86297e3,-6.18603e2},
{-3.26367e3, 1.62447e3, 1.36856e3, 1.31731e3, 1.53372e2},
{7.48863e3,-1.21581e4, 5.50281e3,-1.33630e3, 5.05367e-2}};
double const CYrast:: elmcof[4][5]={
{ 1.84542e3,-5.64002e3, 5.66730e3,-3.15150e3, 9.54160e2},
{-2.24577e3, 8.56133e3,-9.67348e3, 5.81744e3,-1.86997e3},
{ 2.79772e3,-8.73073e3, 9.19706e3,-4.91900e3, 1.37283e3},
{-3.01866e1, 1.41161e3,-2.85919e3, 2.13016e3,-6.49072e2}};
double const CYrast::emxcof[5][7]={
{-4.10652732e6, 1.00064947e7,-1.09533751e7, 7.84797252e6,-3.78574926e6,
1.12237945e6,-1.77561170e5},
{ 1.08763330e7,-2.63758245e7, 2.85472400e7,-2.01107467e7, 9.48373641e6,
-2.73438528e6, 4.13247256e5},
{-8.76530903e6, 2.14250513e7,-2.35799595e7, 1.70161347e7,-8.23738190e6,
2.42447957e6,-3.65427239e5},
{ 6.30258954e6,-1.52999004e7, 1.65640200e7,-1.16695776e7, 5.47369153e6,
-1.54986342e6, 2.15409246e5},
{-1.45539891e6, 3.64961835e6,-4.21267423e6, 3.24312555e6,-1.67927904e6,
5.23795062e5,-7.66576599e4}};
double const CYrast::elzcof[7][7]={
{ 5.11819909e5,-1.30303186e6, 1.90119870e6,-1.20628242e6, 5.68208488e5,
5.48346483e4,-2.45883052e4},
{-1.13269453e6,2.97764590e6,-4.54326326e6, 3.00464870e6,-1.44989274e6,
-1.02026610e5, 6.27959815e4},
{ 1.37543304e6,-3.65808988e6,5.47798999e6,-3.78109283e6, 1.84131765e6,
1.53669695e4,-6.96817834e4},
{-8.56559835e5, 2.48872266e6,-4.07349128e6,3.12835899e6,-1.62394090e6,
1.19797378e5, 4.25737058e4},
{3.28723311e5,-1.09892175e6, 2.03997269e6,-1.77185718e6,9.96051545e5,
-1.53305699e5,-1.12982954e4},
{ 4.15850238e4,7.29653408e4,-4.93776346e5, 6.01254680e5,-4.01308292e5,
9.65968391e4,-3.49596027e3},
{-1.82751044e5, 3.91386300e5,-3.03639248e5, 1.15782417e5,-4.24399280e3,
-6.11477247e3, 3.66982647e2}};
double const CYrast::egscof[5][7][5]={
{{-1.781665232e6,-2.849020290e6, 9.546305856e5, 2.453904278e5, 3.656148926e5},
{ 4.358113622e6, 6.960182192e6,-2.381941132e6,-6.262569370e5,-9.026606463e5},
{-4.804291019e6,-7.666333374e6, 2.699742775e6, 7.415602390e5, 1.006008724e6},
{ 3.505397297e6, 5.586825123e6,-2.024820713e6,-5.818008462e5,-7.353683218e5},
{-1.740990985e6,-2.759325148e6, 1.036253535e6, 3.035749715e5, 3.606919356e5},
{ 5.492532874e5, 8.598827288e5,-3.399809581e5,-9.852362945e4,-1.108872347e5},
{-9.229576432e4,-1.431344258e5, 5.896521547e4, 1.772385043e4, 1.845424227e4}},
{{ 4.679351387e6, 7.707630513e6,-2.718115276e6,-9.845252314e5,-1.107173456e6},
{-1.137635233e7,-1.870617878e7, 6.669154225e6, 2.413451470e6, 2.691480439e6},
{ 1.237627138e7, 2.030222826e7,-7.334289876e6,-2.656357635e6,-2.912593917e6},
{-8.854155353e6,-1.446966194e7, 5.295832834e6, 1.909275233e6, 2.048899787e6},
{ 4.290642787e6, 6.951223648e6,-2.601557110e6,-9.129731614e5,-9.627344865e5},
{-1.314924218e6,-2.095971932e6, 8.193066795e5, 2.716279969e5, 2.823297853e5},
{ 2.131536582e5, 3.342907992e5,-1.365390745e5,-4.417841315e4,-4.427025540e4}},
{{-3.600471364e6,-5.805932202e6, 1.773029253e6, 4.064280430e5, 7.419581557e5},
{ 8.829126250e6, 1.422377198e7,-4.473342834e6,-1.073350611e6,-1.845960521e6},
{-9.781712604e6,-1.575666314e7, 5.161226883e6, 1.341287330e6,2.083994843e6},
{ 7.182555931e6, 1.156915972e7,-3.941330542e6,-1.108259560e6,-1.543982755e6},
{-3.579820035e6,-5.740079339e6, 2.041827680e6, 5.981648181e5, 7.629263278e5},
{ 1.122573403e6, 1.777161418e6,-6.714631146e5,-1.952833263e5,-2.328129775e5},
{-1.839672155e5,-2.871137706e5, 1.153532734e5, 3.423868607e4, 3.738902942e4}},
{{ 2.421750735e6, 4.107929841e6,-1.302310290e6,-5.267906237e5,-6.197966854e5},
{-5.883394376e6,-9.964568970e6, 3.198405768e6, 1.293156541e6, 1.506909314e6},
{ 6.387411818e6, 1.079547152e7,-3.517981421e6,-1.424705631e6,-1.629099740e6},
{-4.550695232e6,-7.665548805e6, 2.530844204e6, 1.021187317e6, 1.141553709e6},
{ 2.182540324e6, 3.646532772e6,-1.228378318e6,-4.813626449e5,-5.299974544e5},
{-6.518758807e5,-1.070414288e6, 3.772592079e5, 1.372024952e5, 1.505359294e5},
{ 9.952777968e4, 1.594230613e5,-6.029082719e4,-2.023689807e4,-2.176008230e4}},
{{-4.902668827e5,-8.089034293e5, 1.282510910e5,-1.704435174e4, 8.876109934e4},
{ 1.231673941e6, 2.035989814e6,-3.727491110e5, 4.071377327e3,-2.375344759e5},
{-1.429330809e6,-2.376692769e6, 5.216954243e5, 7.268703575e4, 3.008350125e5},
{ 1.114306796e6, 1.868800148e6,-4.718718351e5,-1.215904582e5,-2.510379590e5},
{-5.873353309e5,-9.903614817e5, 2.742543392e5, 9.055579135e4, 1.364869036e5},
{ 1.895325584e5, 3.184776808e5,-9.500485442e4,-3.406036086e4,-4.380685984e4},
{-2.969272274e4,-4.916872669e4, 1.596305804e4, 5.741228836e3, 6.669912421e3}}};
double const CYrast::aizroc[5][6]={
{ 2.34441624e4,-5.88023986e4, 6.37939552e4,-4.79085272e4,
2.27517867e4,-5.35372280e3},
{-4.19782127e4, 1.09187735e5,-1.24597673e5, 9.93997182e4,
-4.95141312e4, 1.19847414e4},
{ 4.18237803e4,-1.05557152e5, 1.16142947e5,-9.00443421e4,
4.48976290e4,-1.10161792e4},
{-8.27172333e3, 2.49194412e4,-3.39090117e4, 3.33727886e4,
-1.98040399e4, 5.37766241e3},
{ 5.79695749e2,-1.61762346e3, 2.14044262e3,-3.55379785e3,
3.25502799e3,-1.15583400e3}};
double const CYrast::ai70c[5][6]={
{ 3.11420101e4,-7.54335155e4, 7.74456473e4,-4.79993065e4,
2.23439118e4,-4.81961155e3},
{-7.24025043e4, 1.72276697e5,-1.72027101e5, 1.03891065e5,
-4.83180786e4, 1.08040504e4},
{ 7.14932917e4,-1.72792523e5, 1.75814382e5,-1.07245918e5,
4.86163223e4,-1.10623761e4},
{-2.87206866e4, 6.76667976e4,-6.50167483e4, 3.67161268e4,
-1.74755753e4, 4.67495427e3},
{1.67914908e4,-3.97304542e4, 3.81446552e4,-2.04628156e4,
7.20091899e3,-1.49978283e3}};
double const CYrast::ai95c[5][6]={
{-6.17201449e5, 1.45561724e6,-1.47514522e6, 9.37798508e5,
-3.74435017e5, 7.81254880e4},
{ 1.24304280e6,-2.94179116e6, 3.00170753e6,-1.92737183e6,
7.79238772e5,-1.64803784e5},
{-1.49648799e6, 3.52658199e6,-3.56784327e6, 2.26413602e6,
-9.02243251e5, 1.88619658e5},
{ 7.27293223e5,-1.72140677e6,1.75634889e6,-1.12885888e6,
4.57150814e5,-9.74833991e4},
{-3.75965723e5, 8.83032946e5,-8.87134867e5, 5.58350462e5,
-2.20433857e5, 4.62178756e4}};
double const CYrast::aimaxc[5][6]={
{-1.07989556e6, 2.54617598e6,-2.56762409e6, 1.62814115e6,
-6.39575059e5, 1.34017942e5},
{ 2.17095357e6,-5.13081589e6, 5.19610055e6,-3.31651644e6,
1.31229476e6,-2.77511450e5},
{-2.66020302e6, 6.26593165e6,-6.31060776e6, 3.99082969e6,
-1.56447660e6, 3.25613262e5},
{ 1.29464191e6,-3.05746938e6, 3.09487138e6,-1.97160118e6,
7.79696064e5,-1.63704652e5},
{-7.13073644e5, 1.67482279e6,-1.67984330e6, 1.05446783e6,
-4.10928559e5, 8.43774143e4}};
double const CYrast::ai952c[5][6]={
{-7.37473153e5, 1.73682827e6,-1.75850175e6, 1.11320647e6,
-4.41842735e5, 9.02463457e4},
{ 1.49541980e6,-3.53222507e6, 3.59762757e6,-2.29652257e6,
9.21077757e5,-1.90079527e5},
{-1.80243593e6, 4.24319661e6,-4.29072662e6, 2.71416936e6,
-1.07624953e6, 2.20863711e5},
{ 8.86920591e5,-2.09589683e6,2.13507675e6,-1.36546686e6,
5.48868536e5,-1.14532906e5},
{-4.62131503e5, 1.08555722e6,-1.09187524e6, 6.87308217e5,
-2.70986162e5, 5.61637883e4}};
double const CYrast::aimax2c[5][6]={
{-1.16343311e6, 2.74470544e6,-2.77664273e6, 1.76933559e6,
-7.02900226e5, 1.49345081e5},
{ 2.36929777e6,-5.60655122e6,5.70413177e6,-3.66528765e6,
1.47006527e6,-3.15794626e5},
{-2.82646077e6, 6.66086824e6,-6.72677653e6, 4.27484625e6,
-1.69427298e6, 3.58429081e5},
{ 1.39112772e6,-3.29007553e6, 3.34544584e6,-2.14723142e6,
8.61118401e5,-1.84500129e5},
{-7.21329917e5, 1.69371794e6,-1.69979786e6, 1.07037781e6,
-4.20662028e5, 8.80728361e4}};
double const CYrast::aimax3c[4][4]={
{-2.88270282e3, 5.30111305e3,-3.07626751e3,6.56709396e2},
{5.84303930e3,-1.07450449e4,6.24110631e3,-1.33480875e3},
{-4.20629939e3,7.74058373e3,-4.50256063e3, 9.65788439e2},
{1.23820134e3,-2.28228958e3, 1.33181316e3,-2.87363568e2}};
double const CYrast::aimax4c[4][4]={
{-3.34060345e3, 6.26384099e3,-3.77635848e3, 8.57180868e2},
{ 6.76377873e3,-1.26776571e4, 7.64206952e3,-1.73406840e3},
{-4.74821371e3, 8.89857519e3,-5.36266252e3, 1.21614216e3},
{ 1.46369384e3,-2.74251101e3, 1.65205435e3,-3.74262365e2}};
double const CYrast::bizroc[4][6]={
{ 5.88982505e2,-1.35630904e3, 1.32932125e3,-7.78518395e2,
2.73122883e2,-3.49600841e1},
{-9.67701343e2, 2.24594418e3,-2.24303790e3, 1.35440047e3,
-4.96538939e2, 6.66791793e1},
{ 1.17090267e3,-2.71181535e3, 2.67008958e3,-1.58801770e3,
5.66896359e2,-8.21530057e1},
{-3.83031864e2, 9.05191483e2,-9.30560410e2, 5.96618532e2,
-2.34403480e2, 3.97909172e1}};
double const CYrast::bi70c[4][6]={
{ 2.32414810e3,-5.42381778e3, 5.40202710e3,-3.26923144e3,
1.18318943e3,-1.93186467e2},
{-4.38084778e3, 1.03523570e4,-1.05573803e4, 6.59901160e3,
-2.47601209e3, 4.19497260e2},
{ 4.35377377e3,-1.01728647e4, 1.01311246e4,-6.14038462e3,
2.21957562e3,-3.62854365e2},
{-1.84533539e3, 4.41613298e3,-4.59403284e3, 2.95951225e3,
-1.14630148e3, 2.02702459e2}};
double const CYrast::bi95c[4][6]={
{ 1.55359266e3,-3.58209715e3, 3.50693744e3,-2.03992913e3,
7.05498010e2,-1.49075519e2},
{-2.86876240e3, 6.77107086e3,-6.90300614e3, 4.20246063e3,
-1.50290693e3, 3.13662258e2},
{ 2.60138185e3,-5.95414919e3, 5.70261588e3,-3.17188958e3,
9.89207911e2,-1.76320647e2},
{-1.75198402e3, 4.16635208e3,-4.25212424e3, 2.59953301e3,
-9.09813362e2, 1.51070448e2}};
double const CYrast::bimaxc[4][6]={
{ 4.17708254e3,-8.59358778e3, 6.46392215e3,-8.84972189e2,
-1.59735594e3, 1.39662071e3},
{-1.56318394e4, 3.54574417e4,-3.35945173e4, 1.65495998e4,
-3.32021998e3,-1.46150905e3},
{ 1.41292811e4,-3.11818487e4, 2.77454429e4,-1.19628827e4,
1.28008968e3, 1.66111636e3},
{-1.92878152e4, 4.56505796e4,-4.66413277e4, 2.89229633e4,
-1.07284346e4, 1.50513815e3}};
double const CYrast::b[8][5][5]={
{ {-17605.486, 7149.518, 23883.053, 21651.272, -348.402},
{ 67617.841, -43739.724, -72255.975, -79130.794, -44677.571},
{-38284.438, 1629.405, 49928.158, 41804.076, -4744.661},
{ 32124.997, -30258.577, -45416.684, -40347.682, -20718.220},
{ -7009.141, -12274.997, 5703.797, 4375.711, -2519.378}},
{{ 44633.464, -19664.988, -59871.761, -55426.914, -834.542},
{-168222.448, 111291.480, 179939.092, 198092.569, 111347.893},
{ 97361.913, -9404.674, -125757.922, -108003.071, 7218.634},
{-79483.915, 77325.943, 113433.935, 100793.473, 51134.715},
{ 17974.287, 28084.202, -15187.024, -12244.758, 4662.638}},
{{-52775.944, 26372.246, 69061.418, 66412.802, 4456.150},
{191743.968, -131672.398, -204896.966, -227867.388, -126609.907},
{-115704.145, 22053.324, 146315.778, 131364.763, 1176.787},
{ 89552.374, -92216.043, -129901.381, -115369.145, -56853.433},
{ -21565.916, -26595.626, 19490.177, 16758.541, -2102.079}},
{{ 43089.492, -24205.277, -54145.651, -54916.885, -6982.880},
{-148893.417, 105958.013, 157835.761, 178691.634, 97246.541},
{ 94988.919, -28100.912, -115999.016, -110379.031, -10165.655},
{ -68277.650, 75226.302, 100957.904, 89635.423, 41887.718},
{ 17720.511, 14837.634, -17476.245, -15762.519, -1297.194}},
{{-25673.002, 15584.030, 30291.575, 33008.500, 6161.347},
{ 83671.721, -60540.161, -86493.251, -101211.404, -53525.729},
{ -56872.290, 21837.845, 65632.326, 67209.922, 11367.245},
{ 37417.011, -43832.496, -56023.110, -49995.410, -21521.767},
{ -10406.752, -4483.654, 11314.537, 10435.311, 2206.541}},
{{ 11115.697, -6672.659, -11696.751, -14183.580, -3586.280},
{ -33914.223, 23453.203, 32630.486, 40847.174, 21223.389},
{ 24704.794, -10226.568, -25497.313, -29082.833, -7190.865},
{ -14734.982, 17457.735, 21457.946, 19706.266, 7745.219},
{ 4283.242, 214.103, -5058.390, -4715.987, -1303.557}},
{{ -3196.271, 1579.967, 2718.777, 3997.275, 1361.541},
{ 9152.527, -5182.345, -7412.465, -10822.583, -5804.143},
{ -7177.709, 2317.015, 5874.736, 8208.479, 2858.079},
{ 3919.329, -4068.562, -4982.296, -5065.564, -1948.636},
{ -1147.488, 265.063, 1372.992, 1333.320, 416.369}},
{{ 442.331, -219.051, -337.663, -575.255, -232.634},
{ -1217.351, 590.169, 854.438, 1468.791, 811.481},
{ 1031.157, -227.306, -651.183, -1174.558, -528.960},
{ -536.534, 413.429, 533.977, 663.064, 278.203},
{ 154.548, -54.623, -169.817, -183.006, -63.999}}};
float const CYrast::hbarc=197.32858;
float const CYrast::alfinv=137.035982;
float const CYrast::srznw=1.16;
float const CYrast::aknw=2.3;
float const CYrast::bb=0.99;
float const CYrast::um=931.5016;
float const CYrast::elm=0.51104;
float const CYrast::spdlt=2.99792458e23;
float const CYrast::asnw=21.13;
float const CYrast::kx[8]={0.0,0.08299,0.1632,0.2435,0.3217,0.402
,0.51182,0.617422};
float const CYrast::ky[6]={0.0,0.02,0.05,0.10,0.15,0.20};
float const CYrast::ka[11]={0.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.};
float const CYrast::r0=1.225;
float const CYrast::sep=2.;
//******************************************************************
/**
* Constructor
*/
CYrast::CYrast()
{
mass = CMass::instance(); // mass singleton
string fileName("tbl/sad.tbl");
string fullName;
if (getenv("GINPUT") == NULL) fullName = fileName;
else
{
string dir(getenv("GINPUT"));
fullName = dir+fileName;
}
ifstream ifFile (fullName.c_str());
if (ifFile.fail())
{
cout << "could not open file" << fullName << " in CYrast" << endl;
abort();
}
string line;
getline(ifFile,line);
//cout << line << endl;
for (int i5=0;i5<2;i5++)
for (int i4=0;i4<11;i4++)
for (int i3=0;i3<2;i3++)
{
getline(ifFile,line);
//cout << line << endl;
//cout << i3+1 << " " << i4+1 << " " << i5+1 << endl;
for (int i2=0;i2<8;i2++)
{
for(int i1=0;i1<6;i1++) ifFile >> c[i1][i2][i3][i4][i5];
getline(ifFile,line);
}
}
ifFile.close();
ifFile.clear();
}
CYrast* CYrast::instance()
{
if (fInstance == 0) {
fInstance = new CYrast;
}
return fInstance;
}
//*********************************************************************
/**
* Returns the yrast energy in MeV from the Rotating Liquid Drop Model
\param iZ is the proton number
\param iA is the mass number
\param fL is the angular momentum in hbar
*/
float CYrast::getYrastRLDM(int iZ, int iA, float fL)
{
float fZ = iZ;
float fA = iA;
float fN = fA - fZ;
float paren = 1.0 - 1.7826*pow((fN-fZ)/fA,2);
if (paren <= 0.) paren = 0.1; // what to do here
float eso = 17.9439*paren*pow(fA,(float)(2./3.));
float x = 0.019655*fZ*(fZ/fA)/paren;
float ero = 34.548*pow(fL,2)/pow(fA,(float)(5./3.));
float y = 1.9254*pow(fL,2)/(paren*pow(fA,(float)(7/3.)));
int ix = (int)(20.*x + 1.0);
float cx = (float)ix;
float bx = 20.*x + 1.0;
float dx = bx - cx;
float hf;
if (x <= 0.25)
{
float by = 10.*y + 1.;
if (by > 9.0) by = 9.0;
if (by < 1.0) by = 1.0;
int iy = (int)by;
float cy = iy;
float dy = by - cy;
float h1 = (x1h[iy-1][ix]-x1h[iy-1][ix-1])*dx+x1h[iy-1][ix-1];
float h2 = (x1h[iy][ix]-x1h[iy][ix])*dx+x1h[iy][ix];
hf = (h2-h1)*dy+h1;
}
else if (x < 0.5)
{
float by = 20.0*y + 1.0;
if (by > 11.0) by = 10.0;
if (by < 1.0) by = 1.0;
ix = ix - 5;
int iy =(int) by;
float cy = iy;
float dy = by - cy;
float h1 = (x2h[iy-1][ix]-x2h[iy-1][ix-1])*dx+x2h[iy-1][ix-1];
float h2 = (x2h[iy][ix]-x2h[iy][ix-1])*dx+x2h[iy][ix-1];
hf = (h2-h1)*dy + h1;
}
else
{
if (x > 0.94999999) x=0.949999999;
ix = (int)(20.0*x + 1.0);
ix = ix - 10;
float by = 100.0*y + 1.0;
if (by > 19.0) by = 19.0;
if (by < 1.0) by = 1.0;
int iy = (int)by;
float cy = iy;
float dy = by - cy;
float h1 = (x3h[iy-1][ix]-x3h[iy-1][ix-1])*dx+x3h[iy-1][ix-1];
float h2 = (x3h[iy][ix]-x3h[iy][ix-1])*dx+x3h[iy][ix-1];
hf = (h2-h1)*dy+h1;
}
return ero + hf*eso;
}
//*************************************************
/**
* calculates a array of Legendre Polynomials
\param x is the independent variable
\param n is the maximum order of the array
\param pl is the pointer to the array
*/
void CYrast::lpoly(double x, int n, double* pl)
{
pl[0] = 1.;
pl[1] = x;
for (int i=2;i<n;i++) pl[i] = ((double)(2*i-1)*x*pl[i-1]
- (double)(i-1)*pl[i-2])/(double)(i);
}
//************************************************
/**
* Returns the relative surface area of the saddle-point shape
* from the model of Sierk. The surface is relative to the
* value for a spherical nucleus
\param J is the angular momentum
*/
float CYrast::getBsSierk(float J)
{
double xa = A/320.0;
double JJ = (double)(J)/Jmax;
double pl[9];
lpoly (JJ,9,pl);
double paa[5];
lpoly (xa,5,paa);
double pzz[8];
lpoly (zz,8,pzz);
double bs = 0.0;
for (int izz = 0; izz<8;izz++)
for (int iaa = 0;iaa<5;iaa++)
for (int ill=0;ill<5;ill++)
{
bs += b[izz][iaa][ill]*pzz[izz]*paa[iaa]*pl[2*ill];
}
if (bs < 1.) bs = 1.;
return (float) bs;
}
//**************************************
/**
* Returns the Maximum angular momentum where the nucleus is stable
* against fission in the model of Sierk.
* ie. above this value the barrier vanishes.
* Units are in hbar.
\param iZ is proton number
\param iA is the mass number
*/
float CYrast::getJmaxSierk(int iZ, int iA)
{
if (iZ < 19 || iZ > 111)
{
cout << " Z out of range for CYrast::Jmax" << endl;
abort();
}
Z = (double)iZ;
A = (double)iA;
amin = 1.2*Z + 0.01*pow(Z,2);
amax = 5.8*Z - 0.024*pow(Z,2);
if ( A < amin || A > amax)
{
cout << "A out of limits for CYrast::Jmax" << endl;
abort();
}
double aa = 2.5e-3*A;
zz = 1.0e-2*Z;
Jmax= 0.0;
lpoly (zz,7,pz);
lpoly (aa,7,pa);
for (int i=0;i<5;i++)
for (int k=0;k<7;k++)
{
Jmax += emxcof[i][k]*pz[k]*pa[i];
}
return (float)Jmax;
}
//******************************************
/**
* Returns the fission barrier from the model of Sierk. Units are in MeV.
* The function getJmaxSierk() must be called beforehand
\param J is the angular momentum in hbar
*/
float CYrast::getBarrierFissionSierk(float J)
{
double dJ = (double)J;
if (Z > 102.0 && J > 0.0)
{
cout<< "z and J out of limits" << endl;
return 999.;
}
double bfis = 0.;
for (int i=0;i<7;i++)
for (int k=0;k<7;k++)
bfis += elzcof[i][k]*pz[k]*pa[i];
if (dJ < 1.) return (float)bfis;
double J80 = 0.0;
double J20 = 0.0;
for (int i=0;i<4;i++)
for (int k=0;k<5;k++)
{
J80 += elmcof[i][k]*pz[k]*pa[i];
J20 += emncof[i][k]*pz[k]*pa[i];
}
if (dJ <= J20)
{
double q = 0.2/(pow(J20,2)*pow(J80,2)*(J20-J80));
double qa = q*(4.0*pow(J80,3)-pow(J20,3));
double qb = -q*(4.0*pow(J80,2)-pow(J20,2));
bfis *= (1.0+qa*pow(dJ,2)+qb*pow(dJ,3));
}
else
{
float x = J20/Jmax;
float y = J80/Jmax;
float aj = (-20.0*pow(x,5)+25.0*pow(x,4)-4.0)*pow(y-1.0,2)*y*y;
float ak = (-20.0*pow(y,5)+25.0*pow(y,4)-1.0)*pow(x-1.0,2)*x*x;
float q = 0.2/((y-x)*pow((1.0-x)*(1.0-y)*x*y,2));
float qa = q*(aj*y-ak*x);
float qb = -q*(aj*(2.0*y+1.0)-ak*(2.0*x+1.0));
float zzz = dJ/Jmax;
float a1 = 4.0*pow(zzz,5)-5.0*pow(zzz,4) + 1.0;
float a2 = qa*(2.0*zzz+1.0);
bfis *= a1+(zzz-1.0)*(a2+qb*zzz)*zzz*zzz*(zzz-1.0);
}
if (bfis <= 0.0) bfis = 0.0;
if (J > Jmax) bfis = 0.0;
return (float)bfis;
}
//*****************************************
/**
* Returns the yrast energy is trhe model of Sierk.
* Units are in MeV. The function getJmazSierk must be called
* beforehand.
\param J is the angular momentum
*/
float CYrast::getYrastSierk(float J)
{
if (Z > 102.0 && J > 0.0)
{
cout <<"z and J out of limits" << endl;
return 999.;
}
if (A < amin || A > amax)
{
cout << "A is out of range" << endl;
return 999.;
}
double Erot = 0.0;
double JJ = (double)J/Jmax;
double pl[9];
lpoly (JJ,9,pl);
//srk Now calculate rotating ground-state energy
//if (J > Jmax) return 999.;
for (int k=0;k<5;k++)
for (int l = 0;l<7;l++)
for (int m=0;m<5;m++)
Erot += egscof[k][l][m]*pz[l]*pa[k]*pl[2*m];
if (Erot < 0.) Erot = 0.;
return (float)Erot;
}
//*****************************************************
/**
* Calculates the three principle moments of inertia
* associated with the saddle-point configuration in the model
* of Sierk.The function getJmaxSierk must be called beforehand.
\param J is the angular momentum
*/
float CYrast::getMomentOfInertiaSierk(float J)
{
double JJ = (double)J/Jmax;
double aizro = 0.0;
double ai70 = 0.0;
double aimax = 0.0;
double ai95 = 0.0;
//double aimin = 0.0;
double bizro = 0.0;
double bi70 = 0.0;
double bimax = 0.0;
double bi95 = 0.0;
double aimax2 = 0.0;
double ai952 = 0.0;
for (int l=0;l<6;l++)
{
for (int k=0;k<5;k++)
{
aizro += aizroc[k][l] *pz[l]*pa[k];
ai70 += ai70c[k][l] *pz[l]*pa[k];
ai95 += ai95c[k][l] *pz[l]*pa[k];
aimax += aimaxc[k][l] *pz[l]*pa[k];
ai952 += ai952c[k][l] *pz[l]*pa[k];
aimax2 += aimax2c[k][l]*pz[l]*pa[k];
}
for (int k=0;k<4;k++)
{
bizro += bizroc[k][l]*pz[l]*pa[k];
bi70 += bi70c[k][l]*pz[l]*pa[k];
bi95 += bi95c[k][l]*pz[l]*pa[k];
bimax += bimaxc[k][l]*pz[l]*pa[k];
}
}
double ff1 = 1.0;
double ff2 = 0.0;
double fg1 = 1.0;
double fg2 = 0.0;
double aimidh = 0.;;
if (Z > 70.)
{
double aimaxh = 0.0;
aimidh = 0.0;
for (int l=0;l<4;l++)
for (int k=0;k<4;k++)
{
aimaxh += aimax3c[k][l]*pz[l]*pa[k];
aimidh += aimax4c[k][l]*pz[l]*pa[k];
}
if (Z > 80) ff1 = 0.0;
if (Z >= 80) fg1 = 0.0;
if (bimax > 0.95) fg1 = 0.0;
if (aimaxh > aimax) ff1 = 0.0;
ff2 = 1.0 - ff1;
fg2 = 1.0 - fg1;
aimax = aimax*ff1 + ff2*aimaxh;
aimax2 = aimax2*ff1 + ff2*aimidh;
}
bimax = bimax*fg1 + aimidh*fg2;
double saizro = max(aizro,0.0);
double sai70 = max(ai70,0.0);
double sai95 = max(ai95,0.0);
double saimax = max(aimax,0.0);
double sai952 = max(ai952,0.0);
double simax2 = max(aimax2,0.0);
double sbimax = max(bimax,0.0);
double sbi70 = max(bi70,0.0);
double sbi95 = max(bi95,0.0);
double sbizro = max(bizro,0.0);
double q1 = -3.148849569;
double q2 = 4.465058752;
double q3 = -1.316209183;
double const q4 = 2.26129233;
double const q5 = -4.94743352;
double const q6 = 2.68614119;
double gam = - 20.0*log(fabs(saizro-sai95)/fabs(saizro-saimax));
double aa = q1*saizro + q2*sai70 + q3*sai95;
double bb = q4*saizro + q5*sai70 + q6*sai95;
double gam2 = - 20.0*log(fabs(saizro-sai952)/fabs(saizro-simax2));
double aa2 = q1*saizro + q2*sai70 + q3*sai952;
double bb2 = q4*saizro + q5*sai70 + q6*sai952;
double aa3 = q1*sbizro + q2*sbi70 + q3*sbi95;
double bb3 = q4*sbizro + q5*sbi70 + q6*sbi95;
double const gam3 = 60.0;
double alpha = pi*(JJ - 0.7);
double beta = 5.0*pi*(JJ- 0.9);
double silt = saizro + aa*pow(JJ,2) + bb*pow(JJ,4);
double sjlt = sbizro + aa3*pow(JJ,2) + bb3*pow(JJ,4);
double silt2 = saizro + aa2*pow(JJ,2) + bb2*pow(JJ,4);
if (JJ <= 0.70)
{
momInertiaMin = sjlt;
momInertiaMax = silt;
momInertiaMid = silt2;
}
else
{
double sigt = saizro + (saimax-saizro)*exp(gam*(JJ-1.0));
double sjgt = sbi95 + (sbimax-sbi95)*exp(gam3*(JJ-1.0));
double sigt2 = saizro + (simax2-saizro)*exp(gam2*(JJ-1.0));
if (JJ <= 0.95)
{
double f1 = silt*pow(cos(alpha),2) + sigt*pow(sin(alpha),2);
momInertiaMax = f1;
double f3 = sjlt*pow(cos(alpha),2) + sjgt*pow(sin(alpha),2);
momInertiaMin = f3;
double f1m = silt2*pow(cos(alpha),2) + sigt2*pow(sin(alpha),2);
momInertiaMid = f1m;
}
else
{
double f2 = silt*pow(cos(beta),2) + sigt*pow(sin(beta),2);
momInertiaMax = f2;
double f4 = sjlt*pow(cos(beta),2) + sjgt*pow(sin(beta),2);
momInertiaMin = f4;
double f2m = silt2*pow(cos(beta),2) + sigt2*pow(sin(beta),2);
momInertiaMid = f2m;
}
}
if (ff2 > 0.01 && fg2 > 0.01)
{
q1 = 4.001600640;
q2 = 0.960784314;
q3 = 2.040816327;
double aa3 = q1*sai70 - q2*saimax - (1.0+q3)*saizro;
double bb3 = -q1*sai70 + (1.0+q2)*saimax + q3*saizro;
double aa4 = q1*sai70 - q2*simax2 - (1.0+q3)*saizro;
double bb4 = -q1*sai70 + (1.0+q2)*simax2 + q3*saizro;
momInertiaMax = saizro + aa3*pow(JJ,2) + bb3*pow(JJ,4);
momInertiaMid = saizro + aa4*pow(JJ,2) + bb4*pow(JJ,4);
}
if (momInertiaMid > momInertiaMax) momInertiaMid = momInertiaMax;
momInertiaMid = max(momInertiaMid,(float)0.0);
//the inertia now are relative to the spherical, so
//multiple by this value
float momInertiaSphere = 0.4*pow(r0,2)*pow(A,5./3.);
momInertiaMax *= momInertiaSphere;
momInertiaMid *= momInertiaSphere;
momInertiaMin *= momInertiaSphere;
return momInertiaMax;
}
//*******************************************************************
/**
* Returns the fission barrier in MeV from the Rotating Liquid Drop
* Model.
\param iZ is the proton number.
\param iA is the mass number
\param fJ is the angular momentum
*/
float CYrast::getBarrierFissionRLDM(int iZ, int iA, float fJ)
{
float A = (float)iA;
float Z = (float)iZ;
float N = A - Z;
float paren=1.-1.7826*pow((N-Z)/A,2);
float eso=17.9439*paren*pow(A,(float)(2./3.));
float x=0.019655*Z*(Z/A)/paren;
float y=1.9254*pow(fJ,2)/(paren*pow(A,(float)(7./3.)));
int ix= (int) (20.*x+.999);
float cx= (float)ix;
float bx=20.*x+.999;
float dx=bx-cx;
float bf;
if (x <= 0.25)
{
float by=10.*y+.999;
if (by > 9.) by=9.;
if (by <1.) by=1.;
int iy= (int)by;
float cy= (float)iy;
float dy=by-cy;
float b2=(x1b[iy][ix]-x1b[iy][ix-1])*dx+x1b[iy][ix-1];
float b1=(x1b[iy-1][ix]-x1b[iy-1][ix-1])*dx+x1b[iy-1][ix-1];
bf=(b2-b1)*dy+b1;
}
else if (x <= .5)
{
float by=20.*y+.999;
if (by > 11.) by=11.;
if (by < 1.) by=1.;
ix = ix-5;
int iy= (int)by;
float cy= (float)iy;
float dy=by-cy;
float b1=(x2b[iy-1][ix]-x2b[iy-1][ix-1])*dx+x2b[iy-1][ix-1];
float b2=(x2b[iy][ix]-x2b[iy][ix-1])*dx+x2b[iy][ix-1];
bf=(b2-b1)*dy+b1;
}
else
{
if (x > 0.95) x=0.95;
ix=(int)(20.*x+.999);
ix=ix-10;
float by=100.*y+.999;
if (by > 19.) by=19.;
if (by < 1.) by=1.;
int iy= (int)by;
float cy= (float)iy;
float dy=by-cy;
float b1=(x3b[iy-1][ix]-x3b[iy-1][ix-1])*dx+x3b[iy-1][ix-1];
float b2=(x3b[iy][ix]-x3b[iy][ix-1])*dx+x3b[iy][ix-1];
bf=(b2-b1)*dy+b1;
}
return bf=bf*eso;
}
//*****************************************************
/**
* Cubic polynomial used in 2D cubic spline interpolation
*/
float CYrast::cubic(float a, float b, float c, float d, float e, float f)
{
return a + f*(e*c+f*(3.0*(b-a)-(d+2.0*c)*e+f*(2.0*(a-b)+(c+d)*e)));
}
//*****************************************************
/**
* Prepares for the calculation of conditional saddle-point
* energies in MeV
\param iZ0 is the proton number
\param iA0 is the mass number
\param fJ0 is the angular momentum in hbar
*/
void CYrast::prepareAsyBarrier(int iZ0, int iA0, float fJ0)
{
iZ = iZ0;
iA = iA0;
fJ = fJ0;
float A = (float)(iA);
float Z = (float)(iZ);
Narray = (int)(A/2.);
int ia = -1;
float ac = 0.6*hbarc/alfinv/srznw;
float rz = srznw*pow(A,(float)(1./3.));
float cs = asnw * (1.0-aknw*pow((A-2.0*Z)/A,2));
float delcs = 45.0*hbarc/(8.0*srznw*alfinv)*
(pow(bb/(1.4142*srznw),3))*pow(Z/A,2);
cs = cs + delcs;
float esz = cs*pow(A,(float)(2./3.));
float emz = um*A - elm*Z;
float zsqoa = pow(Z,2)/A;
float x = ac*zsqoa/(2.0*cs);
if (x > 0.61743)
{
if (first)
{
//cout << "No barriers available for this nucleus" << endl;
//cout << "Z= "<<Z<<" A= "<<A<< endl;
//cout << "using scaled 194Hg barriers" << endl;
first = 0;
}
x = 0.61743 ;
}
//----find y fissility parameter-------------------------
if (esz == 0.0)
{
cout << "esz=0 in sad, Z= " << Z << " A= " << A << endl;
abort();
}
if (emz/esz <= 0.0)
{
cout << "in yrast.PrepareAsyBar square root of negative for A= "
<< A << " Z=" << Z << endl;
cout << " emz= " << emz << " esz= " << esz << endl;
abort();
}
float tz = rz*sqrt(emz/esz)/spdlt;
float elz = esz*tz;
float elzohb = elz/6.582173e-22;
float y = 1.25*pow(fJ/elzohb,2);
//----------find normalization factor-------------------
float sadf;
if (Z >= 19.0)
{
float sad0 = -5.5286e-2 + 190.03*x + 235.189*pow(x,2)
- 2471.249*pow(x,3) + 4266.905*pow(x,4) - 2576.048*pow(x,5);
float bfis;
if (x>= 0.6174) bfis = 13.86; // more fissile than 194Hg
else
{
getJmaxSierk(iZ,iA); //initialize sierk sub
bfis = getBarrierFissionSierk((float)0.0);
}
sadf = bfis/sad0;
}
else
{
float ess = 2376.*x - 6062.4*pow(x,2) + 8418.3*pow(x,3);
sadf = pow(esz/ess,(float)2.12);
}
//-----select subroutines for cubic-spline interpolation--
//find nearest knots for interpolation//
int iy = 1;
bool yExtrapolation = 0;
float yy=0;
if(y > ky[5])
{
iy = 5;
yExtrapolation = 1;
yy = y;
y = ky[5];
}
else
{
for (;;)
{
if (y <= ky[iy]) break;
iy++;
if (iy > 5) break;
}
iy = iy - 1;
}
int ix = 1;
for (;;)
{
if (x <= kx[ix]) break;
ix++;
if (ix > 6) break;
}
ix = ix - 1;
// now y is between knots ky[iy-1] & ky[iy] and x is
// between knots kx[ix] & kx[ix+1]
float Dkx = kx[ix+1] - kx[ix];
float Rx = (x - kx[ix])/Dkx;
float Dky = ky[iy+1] - ky[iy];
float Ry = (y - ky[iy])/Dky;
float Dka = 0.;
float C0 = 0.;
float C1 = 0.;
float C2 = 0.;
float C3 = 0.;
//--- fill array with saddle point energies-------
for (int ii=Narray;ii>0;ii--)
{
float alpha = (A - 2.0 * float(ii))/A;
if (alpha >= ka[ia + 1])
{
for (;;)
{
if (alpha < ka[ia +1]) break;
ia++;
}
float k1 = cubic( c[iy][ix][0][ia][0], c[iy][ix+1][0][ia][0],
c[iy][ix][1][ia][0], c[iy][ix+1][1][ia][0],Dkx,Rx);
float k2 = cubic( c[iy][ix][0][ia+1][0], c[iy][ix+1][0][ia+1][0],
c[iy][ix][1][ia+1][0], c[iy][ix+1][1][ia+1][0],Dkx,Rx);
float k3 = cubic( c[iy][ix][0][ia][1], c[iy][ix+1][0][ia][1],
c[iy][ix][1][ia][1], c[iy][ix+1][1][ia][1],Dkx,Rx);
float k4 = cubic( c[iy][ix][0][ia+1][1], c[iy][ix+1][0][ia+1][1],
c[iy][ix][1][ia+1][1], c[iy][ix+1][1][ia+1][1],Dkx,Rx);
Dka = ka[ia+1] -ka[ia];
C0 = k1;
C1 = Dka*k3;
C2 = 3.0*(k2-k1) - (k4+2.0*k3)*Dka;
C3 = 2.0*(k1-k2) + (k3+k4)*Dka;
if (fJ > 0.1)
{
k1 = cubic( c[iy+1][ix][0][ia][0], c[iy+1][ix+1][0][ia][0],
c[iy+1][ix][1][ia][0], c[iy+1][ix+1][1][ia][0],Dkx,Rx);
k2 = cubic( c[iy+1][ix][0][ia+1][0],c[iy+1][ix+1][0][ia+1][0],
c[iy+1][ix][1][ia+1][0],c[iy+1][ix+1][1][ia+1][0],
Dkx,Rx);
k3 = cubic( c[iy+1][ix][0][ia][1], c[iy+1][ix+1][0][ia][1],
c[iy+1][ix][1][ia][1], c[iy+1][ix+1][1][ia][1],Dkx,Rx);
k4 = cubic( c[iy+1][ix][0][ia+1][1],c[iy+1][ix+1][0][ia+1][1],
c[iy+1][ix][1][ia+1][1],c[iy+1][ix+1][1][ia+1][1],
Dkx,Rx);
C0 = (k1-C0)*Ry + C0;
C1 = (Dka*k3-C1)*Ry + C1;
C2 = (3.0*(k2-k1) - (k4+2.*k3)*Dka - C2)*Ry + C2;
C3 = (2.0*(k1-k2) + (k3+k4)*Dka - C3)*Ry + C3;
}
}
float Ra = (alpha - ka[ia])/Dka;
sadArray[ii] = (C0 + C1*Ra + C2*pow(Ra,2) + C3*pow(Ra,3))*sadf;
// if the y value was beyound the last y knot, then we calculated the
//saddle point energy at the knot - we now extrapolate beyound this knot
// by assuming the shape doesn't change. We use two-touching spheres to
// estimate the moment of inertia
if (yExtrapolation)
{
float A1 = (float)ii;
float A2 = A - A1;
float r1 = pow(A1,(float)(1./3.))*r0;
float r2 = pow(A2,(float)(1./2.))*r0;
float Areduced = A1*A2/A;
float MomInertia = 0.4*A1*pow(r1,2) + 0.4*A2*pow(r2,2) +
Areduced*pow(r1+r2+sep,2);
sadArray[ii] += pow(fJ,2)*(1.-y/yy)/2./MomInertia*kRotate;
}
}
for (int ii=5;ii<=Narray;ii++)
{
float A1 = (float)ii;
float A2 = A - A1;
float Z1 = A1/A * Z;
float Z2 = Z - Z1;
int ia1 = (int)A1;
int ia2 = (int)A2;
int iz1 = (int)Z1;
if (iz1 < 2) continue;
int iz2 = (int)Z2;
float Mass1 = mass->getLiquidDropMass(iz1,ia1);
//turn off decays outside bounds
if (Mass1 == -1000)
{
sadArrayZA[ii] = 1000;
continue;
}
float x = mass->getLiquidDropMass(iz1+1,ia1);
Mass1 += (x-Mass1)*(Z1-(float)(iz1));
float Mass2 = mass->getLiquidDropMass(iz2,ia2);
//turn off decays outside bounds
if (Mass2 == -1000)
{
sadArrayZA[ii] = 1000;
continue;
}
x = mass->getLiquidDropMass(iz2+1,ia2);
Mass2 += (x-Mass2)*(Z2-(float)(iz2));
float r1 = r0*pow(A1,(float)(1./3.));
float r2 = r0*pow(A2,(float)(1./3.));
float Ecoul = Z1*Z2*1.44/(r1 + r2 + sep);
sadArrayZA[ii] = sadArray[ii] - Mass1 - Mass2 - Ecoul;
}
}
//*****************************************************************************
/**
* Prints out the array of conditional barriers
*/
void CYrast::printAsyBarrier()
{
//prints out calculated asymmerty dependent barriers
for (int i=0;i<Narray;i++)
cout << i << " " << sadArray[i] << endl;
}
//*****************************************************
/**
* Returns the conditioanl saddle-point energy when both nascient fragments
* have the same Z/A as the parent nucleus
/param A1 is the mass number of one of the nascient fragments
*/
float CYrast::getSaddlePointEnergy(float A1)
{
if (A1 > (float)iA/2.) A1 = (float)iA - A1;
int iA1 = (int)A1;
float Esaddle1 = sadArray[iA1];
if (2*iA1 +1 >= iA) return Esaddle1;
float Esaddle2 = sadArray[iA1+1];
return Esaddle1 + (Esaddle2-Esaddle1)*(A1-(float)iA1) + addBar;
}
//***********************************************
/**
* Returns the constrained saddle-point energy for channel
* where one of the fragmenst is iZ1,iA1
\param iZ1 is the proton number
\param iA1 is the mass number
*/
float CYrast::getSaddlePointEnergy(int iZ1, int iA1)
{
int iZ2 = iZ - iZ1;
int iA2 = iA - iA1;
int iAmin = iA1;
if (iA2 < iAmin) iAmin = iA2;
float mass1 = mass->getLiquidDropMass(iZ1,iA1);
float mass2 = mass->getLiquidDropMass(iZ2,iA2);
float r1 = r0*pow((float)iA1,(float)(1./3.));
float r2 = r0*pow((float)iA2,(float)(1./3.));
float Ecoul = 1.44*(float)iZ1*(float)iZ2/(r1+r2+sep);
return sadArrayZA[iAmin] + mass1 + mass2 + Ecoul + addBar;
}
//********************************************************
/**
* General call to get Yrast energy according to Nuclear models
* This handles probems if iA is too small or the angular momentum
* is too large in extrapolating the Yrast line.
\param iZ is the proton number
\param iA is the mass number
\param fJ is the angular momentum
*/
float CYrast::getYrastModel(int iZ, int iA, float fJ)
{
if (iZ < 19 || iZ > 102) return getYrastRLDM(iZ,iA,fJ);
getJmaxSierk(iZ,iA);
if ( fJ < Jmax-deltaJ) return getYrastSierk(fJ);
float MInertia = getMomentOfInertiaSierk(Jmax-deltaJ);
// The Sierk routine has given negative inertias for very
// exotic nuclei, so check if it is strange and, if so,
// set to the spherical value
if (MInertia <= 0.)
{
float R = r0*pow((float)iA,(float)(1./3.));
MInertia = 0.4 * (float)iA *pow(R,2);
}
return getYrastSierk(fJ-deltaJ)
+ 0.5*(pow(fJ,2)-pow(Jmax-deltaJ,2))/MInertia*kRotate;
}
//********************************************************
/**
* General call to get Yrast energy, includes a fix for light
* nuclear so that the Yrast line does not become to steep.
* At a spin JChange, the Yrast line continues with a constant
* slope.
*
\param iZ is the proton number
\param iA is the mass number
\param fJ is the angular momentum
*/
float CYrast::getYrast(int iZ, int iA, float fJ)
{
if (bForceSierk) return getYrastModel(iZ,iA,fJ);
//float fJChange = pow((float)iA/(float)16.22,(float)2.) + 5.5;
//float fJChange = 43.;
float fJChange = 0.319*(float)iA;
if (fJ < fJChange) return getYrastModel(iZ,iA,fJ);
float r1 = getYrastModel(iZ,iA,fJChange);
float r2 = getYrastModel(iZ,iA,fJChange+1.);
return r1 + (fJ-fJChange)*(r2-r1);
}
//*******************************************************
/**
* Returns the saddle-point energy for symmetric fission in units
* of MeV
\param iZ is the proton number
\param iA is the mass number
\param fJ is the angular momentum
*/
float CYrast::getSymmetricSaddleEnergy(int iZ, int iA, float fJ)
{
if (iZ > 102)
return getYrast(iZ,iA,fJ) + getBarrierFissionRLDM(iZ,iA,fJ);
else
return getYrast(iZ,iA,fJ) + getBarrierFissionSierk(fJ);
}
//**************************************************************
/**
* Forces the use of Sierk yrast energies. As Default GEMINI++
* uses a modified YRAST line for light nuclei so as to get
* the shape of the alpha-particle evaporation spectra correct.
*/
void CYrast::forceSierk(bool b/*=1*/)
{
bForceSierk = b;
}
//******************************************************************
/**
* Prints out the parameters used in the Yrast class
*/
void CYrast::printParameters()
{
cout << "forceSierk " << bForceSierk << endl;
}
//**********************************************
/**
* calculates the Wigner energy in the mass formula used by Sierk
\param iZ is the proton number
\param iA is the mass number
*/
float CYrast::WignerEnergy(int iZ, int iA)
{
//float absI = fabs((float)(iA-2*iZ)/(float)iA);
// return 10.*exp(-4.2*absI);
float const azero = 2.693;
float absI = fabs((float)(iA-2*iZ)/(float)iA);
if (absI > 0.35) return 6.716 + azero ;
return 38.38*absI*(1.-0.5*absI/0.35) + azero;
}
<file_sep>#ifndef sigCharged_
#define sigCharged_
#include <cmath>
#include <string>
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
using namespace std;
/**
*!\brief inverse xsections
*
* This class calculates \f$ \sum_{0}^{\infty} (2\ell+1) T_{\ell}(\varepsilon)\f$ which is the inverse xsection divided by \f$ \pi/k^2 \f$
*
*/
class CSigCharged
{
private:
string sName; //!< name of input file of coefficients
float rc0; //!< paramter to calculate radius for Coulomb barrier
float rc1; //!< paramter to calculate radius for Coulomb barrier
float rc2; //!< paramter to calculate radius for Coulomb barrier
float omega0; //!< paramter for omega
float omega1; //!< parameter for omega
float omega2; //!< parameter for omega
float omega3; //!< parameter for omega
float rI0; //!< paramter for radius for rotational energy
float rI1; //!< paramter for radius for rotational energy
float rI2; //!< paramter for radius for rotational energy
float aa0; //!< below barrier correction parameter
float aa1; //!< below barrier correction parameter
float a0; //!< above barrier correction parameter
float a1; //!< above barrier correction parameter
float Zp; //!< proton number of evaporated particle
float Ap; //!< mass number of evaporated particle
float barrier; //!< Coulomb barrier in MeV
float InvInertia; //!< inverse of the moment of inertia associated with rotateion
float omega; //!< amega parameter in MeV
float a; //!< above barrier correction
float aa; //!< below barrier correction
float offset; //!< offset
bool neutron; //!<bool to signify neutron calculation
float n0; //!< neutron parameter
float n1; //!< neutron parameter
float n2; //!< neutron parameter
public:
CSigCharged(string file, float Zp0, float Ap0); //!< constructor
void prepare(float Z,float A); //!< prepares for calculations of inverse xsections
float getInverseXsec(float energy); //!<calculates the inverse xsection
float getBarrier(); //!< calculates the barrier
};
#endif
<file_sep>// -*- mode: c++ -*-
//
#ifndef angle_
#define angle_
#include <cmath>
//******ROOT*********
//#include "Rtypes.h"
/**
*!\brief polar angles
*
* Class to deal with polar angles
*/
class CAngle
{
protected:
public:
static float const pi; //!< 3.14159
float theta; //!< polar angle in radians
float phi; //!< azimuth angle in radians
CAngle(float,float);
CAngle(){};
static CAngle transform(CAngle angle1,CAngle angle2);
//*****ROOT************
//ClassDef(CAngle,1) //Gemini CAngle
};
#endif
<file_sep>#include "CScission.h"
float const CScission::slopeViola = .1189;
float const CScission::constViola = 7.3;
float const CScission::e2=1.44;
float const CScission::r0=1.2;
float const CScission::kRotate = 41.563;
/**
* simple constructor
*/
CScission::CScission()
{
mass = CMass::instance();//mass singleton
}
/**
* constructor
/param iZ0 is proton number of fissioning nucleus
/param iA0 is mass number of fission nucleus
/param fJ0 is spin of fissioning nucleus
/param iChan =1 for imf, =2 symmetric fission
*/
CScission::CScission(int iZ0, int iA0, float fJ0, int iChan)
{
init(iZ0,iA0,fJ0,iChan);
}
//*******************************************************
/**
* initialized the calls for a given nucleus
/param iZ0 is the proton number of the nucleus
/param iA0 is the mass number of the nucleus
/param fJ0 is the spin of the nucleus
/param iChan =1 for imf, =2 symmetric fission
*/
void CScission::init(int iZ0, int iA0, float fJ0,int iChan,
float Z10/*=0.*/,float A10/*0.*/)
{
iA = iA0;
iZ = iZ0;
fJ = fJ0;
A = (float)iA;
Z = (float)iZ;
if (A10 == 0)
{
sym = 1;
A1 = A/2.;
Z1 = Z/2.;
}
else
{
sym = 0;
Z1 = Z10;
A1 = A10;
}
A2 = (float)iA - A1;
Z2 = (float)iZ - Z1;
R1 = pow(A1,(float)(1./3.))*r0;
momInertia1 = 0.4*A1*pow(R1,2);
R2 = pow(A2,(float)(1./3.))*r0;
momInertia2 = 0.4*A2*pow(R2,2);
Vc0 = Z1*Z2*e2;
mu0 = A1*A2/(A1+A2);
k1 = kRotate/2.*mu0*pow(fJ,2);
float Z2A13;
if (sym == 1)Z2A13 = pow((float)iZ,2)/pow((float)iA,(float)(1./3.));
else Z2A13= 6.349*Z1*Z2/(pow(A1,float(1./3.))+pow(A2,float(1./3.)));
float ekViola = 0.;
if (iChan == 1)
{
ekViola = slopeViola*Z2A13 + constViola;
ekViola += 0.004*pow(fJ0,2); // angular momentum Viola energy
}
else
{
//alternatibve from Rusanov et al
if (Z2A13 < 900.) ekViola = 0.131*Z2A13;
else ekViola = 0.104*Z2A13 + 24.3;
}
//in a two sphere approx, go find separation energy which gives desired
//fission kinetic energy
sep = getSep(ekViola);
sep0 = sep;
}
//******************************************************
/**
* approximates the scission configuration by two separated spheres.
* returns the separation between the surface of the sphere which
* is consistent with input fission total kinetic energy
/param ekViola is the total fission kinetic energy
*/
float CScission::getSep(float ekViola)
{
float R = R1+R2 + 4.;
for(;;)
{
float momInertiaTot = momInertia1+momInertia2+mu0*pow(R,2);
float ek = Vc0/R + k1*pow(R,2)/pow(momInertiaTot,2);
if (fabs(ek-ekViola) < 0.1) break;
float dek = -Vc0/pow(R,2) - 4.*mu0*k1*pow(R,3)/pow(momInertiaTot,3)
+ 2*R/pow(momInertiaTot,2);
float dR = -(ek-ekViola)/dek ;
if (R+dR < 0.) R=0.9*R;
else R += dR;
}
return R - R1 - R2;
}
//***************************************************
/**
* returns the symmetric fission scission energy
* from a two sphere approximation using the separation sep
* previously determined from init() to sigmaFissionSystematics
*/
float CScission::getScissionEnergy()
{
float R = sep + R1 + R2;
float momInertiaTot = momInertia1 + momInertia2 + mu0*pow(R,2);
float EE = Vc0/R + kRotate/2./momInertiaTot*pow(fJ,2);
float mass1 = mass->getFiniteRangeMass(Z1,A1);
float mass2 = mass->getFiniteRangeMass(Z2,A2);
return EE + mass1 + mass2;
}
//***************************************************
/**
* returns the asymmetric fission scission energy
* from a two sphere approximation using the separation sep
* previously determined from init() to sigmaFissionSystematics()
/param iZ1 is the proton number of one of the fission fragments
/param iA1 is the mass number of one of the fission fragments
*/
float CScission::getScissionEnergy(int iZ1, int iA1)
{
A1 = (float)iA1;
Z1 = (float)iZ1;
A2 = A-A1;
int iA2 = iA - iA1;
Z2 = Z - Z1;
int iZ2 = iZ - iZ1;
R1 = r0*pow(A1,(float)(1./3.));
R2 = r0*pow(A2,(float)(1./3.));
float R = sep + R1 + R2;
momInertia1 = 0.4*A1*pow(R1,2);
momInertia2 = 0.4*A2*pow(R2,2);
float mu = A1*A2/(A1+A2);
float momInertiaTot = momInertia1 + momInertia2 + mu*pow(R,2);
float EE = Z1*Z2*e2/R + kRotate/2./momInertiaTot*pow(fJ,2);
float massLD1 = mass->getFiniteRangeMass(iZ1,iA1);
float massLD2 = mass->getFiniteRangeMass(iZ2,iA2);
/* float massLD1 = mass->getLiquidDropMass(iZ1,iA1);
float massLD2 = mass->getLiquidDropMass(iZ2,iA2);*/
//float mass1 = mass->getExpMass(iZ1,iA1);
//float mass2 = mass->getExpMass(iZ2,iA2);
//Epair1 = mass->getPairing(iZ1,iA1);
//Epair2 = mass->getPairing(iZ2,iA2);
//Eshell1 = mass1 - Epair1 - massLD1;
//Eshell2 = mass2 - Epair2 - massLD2;
return massLD1 + massLD2 + EE;
}
//****************************************
/**
* returns the total fission kinetic energy from a two sphere approximation
* using the separation sep determined from either
* init() to sigmaFissionSystematics(), whichever was called last
/param iZ1 is the proton number of one of the fragments
/param iZ2 is the mass number of one of the fragments
*/
float CScission::getFissionKineticEnergy(int iZ1, int iA1)
{
float A1 = (float)iA1;
float A2 = A-A1;
float Z1 = (float)iZ1;
float Z2 = Z - Z1;
float R1 = r0*pow(A1,(float)(1./3.));
float R2 = r0*pow(A2,(float)(1./3.));
float R = sep + R1 + R2;
float momInertia1 = 0.4*A1*pow(R1,2);
float momInertia2 = 0.4*A2*pow(R2,2);
float mu = A1*A2/(A1+A2);
float momInertiaOrbit = mu*pow(R,2);
float momInertiaTot = momInertia1 + momInertia2 + momInertiaOrbit;
float fl = fJ*momInertiaOrbit/momInertiaTot;
EkCoul = Z1*Z2*e2/R;
EkRot = kRotate/2./momInertiaOrbit*pow(fl,2);
ekTot = EkCoul + EkRot;
Erotate1 = pow(fJ*momInertia1/momInertiaTot,2)*kRotate/2./momInertia1;
Erotate2 = pow(fJ*momInertia2/momInertiaTot,2)*kRotate/2./momInertia2;
return ekTot;
}
//**************************************************************
/**
* estimates the standard deviation of the fission mass distributions
* from the systematics of Rusanov et al. Physics of the Atomic Nucleus 60
* (1997) 683 assuming a scission-point logic.
* subsequentally, it approximates the scission configuration as two separated
* spheres, where the separation is adjusted to reproduce the mass distribution
\param iZ0 is the proton number
\param iA0 is the mass number
\param fJ is the angular momentum
\param fUScission is the thermal excitation energy at the scission-point in MeV
*/
float CScission::sigmaFissionSystematicsScission(int iZ0, int iA0, float fJ,
float fUScission)
{
if (fUScission < 0. || fUScission > 2000)
{
cout << "fUScission= " << fUScission << " sigmaFissionSystematics" << endl;
abort();
}
iZ = iZ0;
iA = iA0;
A = (float)iA;
Z = (float)iZ;
float A3 = pow(A,(float)(1./3.));
// on page 684, the temp is determined with a level-density parameter 0.093A
//we must do the same to be consistent
float temp = sqrt(fUScission/0.093/A);
float Z2A = pow(Z,2)/A;
//find stiffness from Fig8c
float d2Vdeta2;
if (Z2A < 23.49) d2Vdeta2 = 2.105;
else if (Z2A < 30.) d2Vdeta2 = 1.923*Z2A - 43.08;
else if (Z2A < 33.9) d2Vdeta2 = 3.643*Z2A - 94.224;
else d2Vdeta2 = -1.3144*Z2A + 73.45;
//use equation 1 to get the variance from the stiffness and temp
float sigma2 = pow(A,2)*temp/16./d2Vdeta2;
//correction for angular momentum from eq 17 and 18.
float d2sdl2;
if (Z2A >32.7) d2sdl2 = -0.1310*temp - 0.05147*Z2A +0.000766*pow(Z2A,2)
+0.00289*temp*Z2A + .970;
else if (Z2A > 31.) d2sdl2 = .2873*temp + 0.03687*Z2A
-0.00974*temp*Z2A -1.1143;
else d2sdl2 = 0.0111*Z2A - .334;
if(d2sdl2<0.)
d2sdl2 = 0.;
float correction = d2sdl2*pow(fJ,2)/2.;
//I find that use of the full correction - overestimartes the width
// so I have scaled it
// correction*= .75;
sigma2 += correction;
//now we determine d2VdA2
float d2VdA2 = temp/sigma2;
//this has a component of Coloumb energy of each fragment
float alpha = Z/A;
float Ec0 = 0.7053*pow(alpha,2)*pow(2.,1./3.)*20./9./A3;
// from the surface energy
float Es = -8.*pow(2.,1./3.)*17.9439*
(1.-1.7826*pow((A-2.*Z)/A,2))/9./
pow(A,(float)(4./3.));
//find unaccounted
d2VdA2 -= Ec0 + Es;
float fact1 = pow(2.,5./3.)*A3*e2*r0*pow(alpha,2)/9.;
float rr = pow(2.,2./3.)*A3*r0;
float fact2 = 2.*e2*pow(alpha,2);
float fact3 = (88.8945*A*A3 + 120.*pow(A,2) +67.5318*pow(A*A3,2) +
46.3521*pow(A,3)*A3 - 76.32*pow(A,4))*pow(r0,4);
float fact4 = (384.*A + 453.572*A*A3*A3+246.365*A*A*A3 + 64.8*pow(A,3))*
pow(r0,3);
float fact5 = (635.*A3*A3 + 609.562*A*A3 + 208.8*A*A)*pow(r0,2);
float fact6 = (482.57*A3 + 288 *A)*r0;
float fact7 = 144.;
float fact8 = pow(A,5)*pow(r0,6)*(144.+544.286*A3*A3 + 1131.5*A*A3 +
1411.2*A*A + 1167.49*pow(A*A3,2) + 579.465*pow(A,3)*A3 +
158.184*pow(A,4));
float fact9 = pow(A,4)*A3*A3*pow(r0,5)*(1088.57 + 3428.79*A3*A3 +
5702.4*A*A3 + 5334.*A*A + 2941.9*pow(A*A3,2) +
730.08*pow(A,3)*A3);
float fact10 = pow(A*r0,4)*A3*(3428.79 + 8640.*A3*A3 + 6720.42*A*A +
1853.28*pow(A*A3,2));
float fact11 = pow(A,4)*pow(r0,3)*(760. + 10885.7*A3*A3 + 9052.*A*A3 +
2822.4*A*A);
float fact12 = pow(A,3)*A3*A3*pow(r0,2)*(5442.86+6857.57*A3*A3 +
2851.2*A*A3);
float fact13 = r0*(2743.03*pow(A,3)*A3 + 1728*pow(A,4));
float fact14 = 576*pow(A,3);
float fact15 = fJ*(fJ+1)*kRotate*64.;
float s = 1.;
int tries = 0;
for(;;)
{
float y = fact1/pow(s+rr,2) - fact2/(s+rr);
//contribution from spin
float nom = fact3+fact4*s+fact5*s*s+fact6*pow(s,3)+fact7*pow(s,4);
float denom = fact8+fact9*s+fact10*s*s+fact11*pow(s,3)+fact12*pow(s,4)+
fact13*pow(s,5)+fact14*pow(s,6);
float extra = fact15*nom/denom;
y += extra;
float dy = -2.*fact1/pow(s+rr,3) + fact2/pow(s+rr,2);
//contribution from spin
extra= fact15*(fact4 +2.*fact5*s+3.*fact6*s*s +4.*fact7*pow(s,3))/denom -
fact15*nom/pow(denom,2)*(fact9+2.*fact10*s+3.*fact11*s*s+
4.*fact12*pow(s,3) + 5.*fact13*pow(s,4)+6.*fact14*pow(s,5));
dy += extra;
float delta = y - d2VdA2;
float deltaS = -delta/dy;
if (fabs(delta) < .0001) break;
s += deltaS;
if(s<0.)
s=1.E-3;
else if(s>50.)
s=50.;
tries++;
if (tries == 10 || isnan(s))
{
//cout << "iZ= " << iZ << " iA= " << iA << " Usciss= " << fUScission
// << " J= " << fJ << endl;
//cout << "sigma2= " << sigma2 << endl;
s = 5.;
break;
}
}
sep = s;
sep1 = sep;
Esymmetric = getScissionEnergy();
return sigma2;
}
//**************************************************************
/**
* estimates the standard deviation of the fission mass distributions
* from the systematics of Rusanov et al. Physics of the Atomic Nucleus 60
* (1997) 683 assuming a saddle-point logic.
* subsequentally, it approximates the scission configuration as two separated
* spheres, where the separation is adjusted to reproduce the mass distribution
\param iZ0 is the proton number
\param iA0 is the mass number
\param fJ is the angular momentum
\param fUScission is the thermal excitation energy at the scission-point in MeV
*/
float CScission::sigmaFissionSystematicsSaddle(int iZ0, int iA0, float fJ,
float fUScission)
{
if (fUScission < 0. || fUScission > 2000)
{
cout << "fUScission= " << fUScission << " sigmaFissionSystematics" << endl;
abort();
}
iZ = iZ0;
iA = iA0;
A = (float)iA;
Z = (float)iZ;
float A3 = pow(A,(float)(1./3.));
// on page 684, the temp is determined with a level-density parameter 0.093A
//we must do the same to be consistent
float temp = sqrt(fUScission/0.093/A);
float Z2A = pow(Z,2)/A;
//find stiffness from Fig8c
float d2Vdeta2;
if (Z2A < 23.49) d2Vdeta2 = 2.105;
else if (Z2A < 31.57) d2Vdeta2 = 1.923*Z2A - 43.08;
else if (Z2A < 34.2) d2Vdeta2 = 3.19*Z2A - 83.06;
else d2Vdeta2 = -1.7287*Z2A + 85.42;
//use equation 1 to get the variance from the stiffness and temp
float sigma2 = pow(A,2)*temp/16./d2Vdeta2;
//correction for angular momentum from eq 17 and 18.
float d2sdl2;
if (Z2A >32.7) d2sdl2 = -0.1310*temp - 0.05147*Z2A +0.000766*pow(Z2A,2)
+0.00289*temp*Z2A + .970;
else if (Z2A > 31.) d2sdl2 = .2873*temp + 0.03687*Z2A
-0.00974*temp*Z2A -1.1143;
else d2sdl2 = 0.0111*Z2A - .334;
if(d2sdl2<0.)
d2sdl2 = 0.;
float correction = d2sdl2*pow(fJ,2)/2.;
//I find that use of the full correction - overestimartes the width
// so I have scaled it
// correction*= .75;
sigma2 += correction;
//now we determine d2VdA2
float d2VdA2 = temp/sigma2;
//this has a component of Coloumb energy of each fragment
float alpha = Z/A;
float Ec0 = 0.7053*pow(alpha,2)*pow(2.,1./3.)*20./9./A3;
// from the surface energy
float Es = -8.*pow(2.,1./3.)*17.9439*
(1.-1.7826*pow((A-2.*Z)/A,2))/9./
pow(A,(float)(4./3.));
//find unaccounted
d2VdA2 -= Ec0 + Es;
float fact1 = pow(2.,5./3.)*A3*e2*r0*pow(alpha,2)/9.;
float rr = pow(2.,2./3.)*A3*r0;
float fact2 = 2.*e2*pow(alpha,2);
float fact3 = (88.8945*A*A3 + 120.*pow(A,2) +67.5318*pow(A*A3,2) +
46.3521*pow(A,3)*A3 - 76.32*pow(A,4))*pow(r0,4);
float fact4 = (384.*A + 453.572*A*A3*A3+246.365*A*A*A3 + 64.8*pow(A,3))*
pow(r0,3);
float fact5 = (635.*A3*A3 + 609.562*A*A3 + 208.8*A*A)*pow(r0,2);
float fact6 = (482.57*A3 + 288 *A)*r0;
float fact7 = 144.;
float fact8 = pow(A,5)*pow(r0,6)*(144.+544.286*A3*A3 + 1131.5*A*A3 +
1411.2*A*A + 1167.49*pow(A*A3,2) + 579.465*pow(A,3)*A3 +
158.184*pow(A,4));
float fact9 = pow(A,4)*A3*A3*pow(r0,5)*(1088.57 + 3428.79*A3*A3 +
5702.4*A*A3 + 5334.*A*A + 2941.9*pow(A*A3,2) +
730.08*pow(A,3)*A3);
float fact10 = pow(A*r0,4)*A3*(3428.79 + 8640.*A3*A3 + 6720.42*A*A +
1853.28*pow(A*A3,2));
float fact11 = pow(A,4)*pow(r0,3)*(760. + 10885.7*A3*A3 + 9052.*A*A3 +
2822.4*A*A);
float fact12 = pow(A,3)*A3*A3*pow(r0,2)*(5442.86+6857.57*A3*A3 +
2851.2*A*A3);
float fact13 = r0*(2743.03*pow(A,3)*A3 + 1728*pow(A,4));
float fact14 = 576*pow(A,3);
float fact15 = fJ*(fJ+1)*kRotate*64.;
float s = 1.;
int tries = 0;
for(;;)
{
float y = fact1/pow(s+rr,2) - fact2/(s+rr);
//contribution from spin
float nom = fact3+fact4*s+fact5*s*s+fact6*pow(s,3)+fact7*pow(s,4);
float denom = fact8+fact9*s+fact10*s*s+fact11*pow(s,3)+fact12*pow(s,4)+
fact13*pow(s,5)+fact14*pow(s,6);
float extra = fact15*nom/denom;
y += extra;
float dy = -2.*fact1/pow(s+rr,3) + fact2/pow(s+rr,2);
//contribution from spin
extra= fact15*(fact4 +2.*fact5*s+3.*fact6*s*s +4.*fact7*pow(s,3))/denom -
fact15*nom/pow(denom,2)*(fact9+2.*fact10*s+3.*fact11*s*s+
4.*fact12*pow(s,3) + 5.*fact13*pow(s,4)+6.*fact14*pow(s,5));
dy += extra;
float delta = y - d2VdA2;
float deltaS = -delta/dy;
if (fabs(delta) < .0001) break;
s += deltaS;
if(s<0.)
s=1.E-3;
else if(s>50.)
s=50.;
tries++;
if (tries == 10 || isnan(s))
{
//cout << "iZ= " << iZ << " iA= " << iA << " Usciss= " << fUScission
// << " J= " << fJ << endl;
//cout << "sigma2= " << sigma2 << endl;
s = 5.;
break;
}
}
sep = s;
sep1 = sep;
Esymmetric = getScissionEnergy();
return sigma2;
}
<file_sep>#include "CRunThick.h"
#include "CFus.h"
int main()
{
int numTot = 80000; //spectra
float const d0=4.; //diffuseness of CN spin distribution
string title0("fusionThick"); //name of output root file without extension
float Elab_max = 9.17*12.; // bombarding energy at front or target
float Elab_min = 8.74*12.; // bombarding energy at back of target
//the difference between these two is the
//energy loss of the projectile in the target
//define projectile
int iZp = 6;
int iAp = 12;
//define target
int iZt = 28;
int iAt = 58;
//use the Bass model to find critical angular momentum
//find critical spin for min bombarding energy
CFus fus_min(iZp,iAp,iZt,iAt,Elab_min,d0);
float l0_min = fus_min.getBassL();
//find critical spin for maximum bombaring energy
CFus fus_max(iZp,iAp,iZt,iAt,Elab_max,d0);
float l0_max = fus_max.getBassL();
cout << "Elab_min= " << Elab_min << " l0_min= " << l0_min
<< " plb_min = " << fus_min.plb << " mb " << endl;
cout << "iZ= " << fus_min.iZcn << " iAcn= " << fus_min.iAcn
<< " Ex_min= " << fus_min.Ex << endl;
cout << "Elab_max= " << Elab_max << " l0_max= " << l0_max
<< " plb_max = " << fus_max.plb << " mb " << endl;
cout << "iZ= " << fus_max.iZcn << " iAcn= " << fus_max.iAcn
<< " Ex_max= " << fus_max.Ex << endl;
//run gemini
CRunThick run(fus_min.iZcn,fus_min.iAcn,fus_min.Ex,fus_max.Ex,l0_min,l0_max,
d0,(int)(l0_max+4.*d0),
(fus_min.plb+fus_max.plb)/2.,10,numTot,title0);
}
<file_sep>#include "CNucleus.h"
#include <algorithm>
#include <numeric>
double const CNucleus::EkFraction = 0.01;
bool const Isig = 1; //in weisskopf, use parametrized Inverse Section
// otherwise calculated them from transmission coeff.
int CNucleus::iHF = 2; //1=Hauser Feshback,0= Weisskopf,2=switches from 0 to 1
bool const fissionMassScission = 0; //1=scission-point fission mass dist
//0=saddle-point fission mass dist
float const scaleImf = 1.;
bool const Isaddle = 0;
bool const Iscission = 1;
//float const WignerScaled = 0.; //scaling factor for the Wigner Energy
float const WignerAdd = 7.; //adding factor for the Wigner Energy
//the following line needed in the ROOT version
//ClassImp(CNucleus)
bool CNucleus::noIMF = 0;
bool CNucleus::BohrWheeler = 1;
CYrast *CNucleus::yrast;
CLevelDensity *CNucleus::levelDensity;
CAngleDist CNucleus::angleDist;
float CNucleus::de = 1.0;
CGdr * CNucleus::GDR;
vector<CNucleus*> CNucleus::allProducts;
vector<CNucleus*> CNucleus::stableProducts;
float const CNucleus::r0=1.16;
float const CNucleus::sep=2.;
float const CNucleus::pi=acos(-1.);
short unsigned CNucleus::Zshell = 2;
short unsigned const CNucleus:: lMaxQuantum = 50;
CEvap *CNucleus::evap;
float const CNucleus::gammaInhibition[3]={0.,.025,9.};
float const CNucleus::wue[3]={0.,6.8e-8,4.9e-14};//gives weisskopf units in MeV
float const CNucleus::viscosity_scission = 1.;
float const CNucleus::viscosity_saddle = 1.5;
float CNucleus::timeTransient = 0.;
//float CNucleus::fissionScaleFactor = 2.46;
float CNucleus::fissionScaleFactor = 1.00;
float CNucleus::sumGammaEnergy = 0.;
float CNucleus::barAdd = 0.;
float const CNucleus::kRotate = 41.563;
bool const CNucleus::noSymmetry = 1; // no symmetric fission calculated in
// asyFissionWidth if there is a fission peak
unsigned CNucleus::iPoint = -1;
float CNucleus::threshold = .001;
vector <float> CNucleus::GammaRayEnergy;
int CNucleus::nGammaRays = 0;
bool CNucleus::GDRParam = false; // switch on GDR parametrized version
template<typename T, typename X>
class CompareGammaToX {
public:
bool operator()(T const &t, X const &x) const { return t.gamma<x; }
};
//*****************************************************
CNucleus::CNucleus()
{
bStable = false;
saddleToSciss = false;
timeSinceSaddle = 0.;
velocity[0] = 0.;
velocity[1] = 0.;
velocity[2] = 0.;
spin = CAngle((float)0.,(float)0.);
daughterLight = NULL;
daughterHeavy = NULL;
parent = NULL;
abortEvent = 0;
evap = CEvap::instance();
yrast = CYrast::instance();
levelDensity = CLevelDensity::instance();
GDR = CGdr::instance();
}
//*******************************************
/**
* constructor specifies the isotope.
\param iZ0 is the proton number
\param iA0 is the mass number
*/
CNucleus::CNucleus(int iZ0, int iA0) : CNuclide(iZ0,iA0)
{
bStable = false;
saddleToSciss = false;
timeSinceSaddle = 0.;
velocity[0] = 0.;
velocity[1] = 0.;
velocity[2] = 0.;
spin = CAngle((float)0.,(float)0.);
daughterLight = NULL;
daughterHeavy = NULL;
parent = NULL;
abortEvent = 0;
evap = CEvap::instance();
yrast = CYrast::instance();
levelDensity = CLevelDensity::instance();
GDR = CGdr::instance();
}
//*******************************************************
/**
* destructor
*/
CNucleus::~CNucleus()
{
//destructor
if (daughterLight != NULL)
{
delete daughterLight;
daughterLight = NULL;
}
if (daughterHeavy != NULL)
{
delete daughterHeavy;
daughterHeavy = NULL;
}
GammaRayEnergy.clear();
}
//**************************************************
/**
* Constructor specifying more parameters
\param iZ0 is proton number
\param iA0 is mass number
\param fEx0 is excitation energy in MeV
\param fJ0 is spin in hbar
*/
CNucleus::CNucleus(int iZ0, int iA0, float fEx0, float fJ0)
: CNuclide(iZ0,iA0)
{
//alternative constructor
bStable = false;
saddleToSciss = false;
timeSinceSaddle = 0.;
velocity[0] = 0.;
velocity[1] = 0.;
velocity[2] = 0.;
spin = CAngle((float)0.,(float)0.);
daughterLight = NULL;
daughterHeavy = NULL;
parent = NULL;
abortEvent = 0;
evap = CEvap::instance();
yrast = CYrast::instance();
levelDensity = CLevelDensity::instance();
setCompoundNucleus(fEx0,fJ0);
}
//**************************************************
/**
* prints out the parameters of the nucleus
*/
void CNucleus::print()
{
//prints out paramters of nucleus
cout << strName << endl;
cout << "Z= " << iZ << " A= " << iA << endl;
cout << "mass excess = " << fExpMass << endl;
cout << strChemName << endl;
cout << "Ex= " << fEx << " J= " << fJ << endl;
cout << "velocity= " << velocity[0] << " " << velocity[1] << " "
<< velocity[2] << " cm/ns" << endl;
cout << "KE= " << getKE() << " MeV" << endl;
cout << "Ex = " << fEx << endl;
cout << "spin axis, theta = " << spin.theta*180./pi << " phi= "
<< spin.phi*180/pi << " deg" << endl;
if (origin2 == 0) cout << " preSaddle emission" << endl;
else if (origin2 == 1) cout << "saddle-to-scission emission" << endl;
else if (origin2 == 2) cout << "from light fission fragment" << endl;
else if (origin2 == 3) cout << "from heavy fission fragment" << endl;
cout << "emission time = " << timeSinceStart << " zs" << endl;
}
//******************************************************
/**
* produces a single binary decay of the nucleus from statistical-model widths
*/
void CNucleus::binaryDecay()
{
if (bStable) return; //decay not possible
if (notStatistical)
{
daughterLight = new CNucleus(evap->decay[notStatisticalMode].Z1,
evap->decay[notStatisticalMode].A1);
daughterHeavy = new CNucleus(iZ-evap->decay[notStatisticalMode].Z1,
iA-evap->decay[notStatisticalMode].A1);
daughterLight->origin = origin;
daughterHeavy->origin = origin;
daughterLight->origin2 = origin2;
daughterHeavy->origin2 = origin2;
daughterLight->parent = this;
daughterHeavy->parent = this;
float decayTime =
ran->expDecayTime(evap->decay[notStatisticalMode].gamma);
daughterLight->timeSinceStart = timeSinceStart + decayTime;
daughterHeavy->timeSinceStart = timeSinceStart + decayTime;
daughterLight->excite(0.,evap->decay[notStatisticalMode].S1);
daughterHeavy->excite(0.,evap->decay[notStatisticalMode].S2);
daughterLight->bStable = 1;
daughterLight->iWeight = 0;
daughterHeavy->iWeight = 0;
daughterLight->runningWeight = runningWeight;
daughterHeavy->runningWeight = runningWeight;
daughterLight->fact = fact;
daughterHeavy->fact = fact;
//make sure 8Be fragments decay
if (iZ-evap->decay[notStatisticalMode].Z1 == 4 &&
iA-evap->decay[notStatisticalMode].A1 == 8 )
{
daughterHeavy->notStatistical = 1;
daughterHeavy->notStatisticalMode = 20;
daughterHeavy->bStable = 0;
}
else daughterHeavy->bStable = 1;
EvapLPlusS = evap->decay[notStatisticalMode].lPlusS1;
EvapL = evap->decay[notStatisticalMode].L;
EvapS1 = evap->decay[notStatisticalMode].S1;
EvapS2 = evap->decay[notStatisticalMode].S2;
EvapEk = evap->decay[notStatisticalMode].Ek;
EvapA1 = evap->decay[notStatisticalMode].A1;
EvapA2 = iA - EvapA1;
angleEvap(); // find the emission angles of the two fragments
allProducts.push_back(daughterLight);
allProducts.push_back(daughterHeavy);
return;
}
//"statistical" decays into alpha plus ligher partner
if (fEx > 0. && (iZ == 3 || (iZ == 2&& iA == 5)))
{
int ejectileA, ejectileZ;
if(iZ == 2) { // He-5
ejectileA = 1;
ejectileZ = 0;
} else if(iA==4) { // Li-4
ejectileA = 1;
ejectileZ = 1;
} else { // for all the other Li isotopes, leave an alpha behind
ejectileA = iA - 4;
ejectileZ = iZ - 2;
}
daughterLight = new CNucleus(ejectileZ,ejectileA);
daughterHeavy = new CNucleus(iZ-ejectileZ,iA-ejectileA);
double Ek = fExpMass + fEx - daughterLight->fExpMass -
daughterHeavy->fExpMass;
if (Ek <= 0.)
{
delete daughterLight;
delete daughterHeavy;
daughterLight = NULL;
daughterHeavy = new CNucleus(iZ,iA);
daughterHeavy->origin = origin;
daughterHeavy->origin2 = origin2;
daughterHeavy->parent = this;
daughterHeavy->timeSinceStart = timeSinceStart;
daughterHeavy->excite(0.,0.);
daughterHeavy->iWeight = iWeight;
daughterHeavy->runningWeight = runningWeight;
daughterHeavy->fact = fact;
daughterHeavy->bStable = 1;
for (int i=0;i<3;i++) daughterHeavy->velocity[i] = velocity[i];
sumGammaEnergy += fEx;
allProducts.push_back(daughterHeavy);
return;
}
else
{
daughterLight->origin = origin;
daughterHeavy->origin = origin;
daughterLight->origin2 = origin2;
daughterHeavy->origin2 = origin2;
daughterLight->parent = this;
daughterHeavy->parent = this;
daughterLight->timeSinceStart = timeSinceStart;
daughterHeavy->timeSinceStart = timeSinceStart;
daughterLight->excite(0.,0.);
daughterHeavy->excite(0.,0.);
daughterLight->bStable = 1;
daughterHeavy->bStable = 1;
daughterLight->iWeight = 0;
daughterHeavy->iWeight = 0;
daughterLight->runningWeight = runningWeight;
daughterHeavy->runningWeight = runningWeight;
daughterLight->fact = fact;
daughterHeavy->fact = fact;
//randomise angle
float theta = acos(1.-2.*ran->Rndm());
float phi = 2.*pi*ran->Rndm();
float vrel = sqrt(2.*Ek*(float)iA/(((float)iA-ejectileA)*((float)ejectileA)))*0.9794;
float v1 = vrel*(float)(iA-ejectileA)/(float)iA;
daughterLight->velocity[0] = v1*sin(theta)*cos(phi);
daughterLight->velocity[1] = v1*sin(theta)*sin(phi);
daughterLight->velocity[2] = v1*cos(theta);
float v2 = vrel - v1;
theta = pi - theta;
phi += pi;
daughterHeavy->velocity[0] = v2*sin(theta)*cos(phi);
daughterHeavy->velocity[1] = v2*sin(theta)*sin(phi);
daughterHeavy->velocity[2] = v2*cos(theta);
for (int i=0;i<3;i++)
{
daughterLight->velocity[i] += velocity[i];
daughterHeavy->velocity[i] += velocity[i];
}
allProducts.push_back(daughterLight);
allProducts.push_back(daughterHeavy);
return;
}
}
// start change
float widthAsyFission = 0.;
needSymmetricFission = false;
// don;t call asymmetric fission if all asymmetries are handled
// by the evaporation folmalism
if (iZ/2 > evap->maxZ)
{
if (noIMF)
{
needSymmetricFission = true;
iZ1_IMF_Max = 0;
}
else widthAsyFission = asyFissionWidthZA();
}
float widthSymFission = 0.;
if (pow((float)iZ,2)/(float)iA < 20.) needSymmetricFission = false;
//end change
float widthEvaporation = evaporationWidth();
float widthGamma = gammaWidth();
float width = widthAsyFission + widthEvaporation + widthGamma;
float decayTime = timeSinceStart;
width = widthEvaporation + widthGamma;
decayTime += ran->expDecayTime(width);
if (decayTime < timeTransient)
{
widthAsyFission = 0.;
}
else {
width += widthAsyFission;
decayTime = timeTransient + ran->expDecayTime(width);
}
//transient delay for symmetry fission only
if(timeSinceStart < timeTransient && needSymmetricFission)
{
decayTime += ran->expDecayTime(width);
if (decayTime < timeTransient)
{
needSymmetricFission = 0;
}
else decayTime = timeTransient;
}
if (needSymmetricFission)
{
if (BohrWheeler)widthSymFission = BohrWheelerWidth();
else widthSymFission = LestoneFissionWidth();
width += widthSymFission;
decayTime += ran->expDecayTime(width);
}
//end transient delay
if (isnan(width))
{
cout << " a non valid decay with width (nan) was obtained for " <<
" Z= " << iZ << " A= " << iA << " Ex= " << fEx << " j= " << fJ << endl;
cout << "this event will be aborted " << endl;
cout << "please report this to <NAME> " << endl;
abortEvent = 1;
return;
}
if (width == 0)
{
bStable = 1;
return;
}
/*
if (widthGamma/width > 0.99) //terminate particle evaporation.
{
bStable = 1;
sumGammaEnergy += fEx;
return;
}
*/
float xran = ran->Rndm();
if (fEx/(float)iA > 6.) widthSymFission = 0.;
// I switch off fission at excitation
// energies above 6 MeV. Above
// this we get conceptable problems
// with most, or all, of the mass lost
// during the saddle-to-scission
// transition
int iChan = chooseChannel(widthEvaporation,widthAsyFission,widthSymFission,widthGamma,xran);
if (iChan == 0) //light particle evaporation
{
// choose light [particle channelchannel
float xran = ran->Rndm();
int i = 0;
for (;;)
{
float prob = evap->prob[i]/widthEvaporation;
if (prob >= xran) break;
if ( i == evap->nLight-1) break;
i++;
}
lightP = evap->lightP[i];
EvapZ1 = lightP->iZ;
EvapA1 = lightP->iA;
EvapZ2 = iZ - EvapZ1;
EvapA2 = iA - EvapA1;
EvapMode = i;
EvapEx1 = lightP->fEx;
EvapS1 = lightP->fJ;
getSpin((bool)0);
// find the sum of L + S1
float lPlusSMin1 = fabs((float)EvapL-EvapS1);
float lPlusSMin2 = fabs(fJ-EvapS2);
float lPlusSMin = max(lPlusSMin1,lPlusSMin2);
float lPlusSMax1 = (float)EvapL+EvapS1;
float lPlusSMax2 = fJ + EvapS2;
float lPlusSMax = min(lPlusSMax1,lPlusSMax2);
//the following two lines makes sure random!=1.000
float random = 1.5;
while(floor(random) > 0.5)random = ran->Rndm();
EvapLPlusS = lPlusSMin + floor(random*(lPlusSMax - lPlusSMin + 1));
daughterLight = new CNucleus(EvapZ1,EvapA1);
daughterHeavy = new CNucleus(EvapZ2,EvapA2);
daughterLight->origin = origin;
daughterHeavy->origin = origin;
daughterLight->origin2 = origin2;
daughterHeavy->origin2 = origin2;
daughterLight->iWeight = 0;
daughterHeavy->iWeight = iWeight;
daughterLight->runningWeight = runningWeight;
daughterHeavy->runningWeight = runningWeight;
daughterLight->fact = fact;
daughterHeavy->fact = fact;
daughterLight->parent = this;
daughterHeavy->parent = this;
daughterLight->timeSinceStart = timeSinceStart + decayTime;
daughterHeavy->timeSinceStart = daughterLight->timeSinceStart;
daughterLight->excite(EvapEx1,EvapS1);
daughterHeavy->excite(EvapEx2,EvapS2);
if (evap->decay[EvapMode].Ek > 0)
{
daughterLight->notStatistical = 1;
daughterLight->notStatisticalMode = EvapMode;
daughterLight->bStable = 0;
}
else daughterLight->bStable = 1;
angleEvap(); // find the emission angles of the two fragments
allProducts.push_back(daughterLight);
allProducts.push_back(daughterHeavy);
}
else if (iChan == 1) //complex fragment or asymmetric fission decay
{
CNucleus * com = getCompoundNucleus();
com->bResidue = false;
com->bAsymmetricFission = true;
daughterLight = new CNucleus(fissionZ,fissionA);
daughterHeavy = new CNucleus(iZ-fissionZ,iA-fissionA);
if (fissionZ == 14 && fissionA == 22)
cout << "here " << iZ<< " " << iA << " " << fEx << " " << fJ << endl;
daughterLight->origin = 2;
daughterHeavy->origin = 3;
daughterLight->origin2 = origin2;
daughterHeavy->origin2 = origin2;
daughterLight->iWeight = 0;
daughterHeavy->iWeight = 0;
daughterLight->runningWeight = runningWeight;
daughterHeavy->runningWeight = runningWeight;
daughterLight->fact = fact;
daughterHeavy->fact = fact;
daughterLight->parent = this;
daughterHeavy->parent = this;
daughterLight->timeSinceStart = timeSinceStart + decayTime;
daughterHeavy->timeSinceStart = daughterLight->timeSinceStart;
// Coulomb part of kinetic energy
scission.init(iZ,iA,fJ,iChan);
scission.getFissionKineticEnergy(fissionZ,fissionA);
float Ek = scission.ekTot;
levelDensity->getLogLevelDensitySpherical(iA,fissionU,(float)0.,(float)0.,
fJ,fMInertia,2);
//add in fluctuations to Coulomb barrier
float sigma = Ek*sqrt(levelDensity->getTemp())*.1;
//float sigma = 0.;
// fluctuations are in Coulomb energy are gaussian, but make sure the
//Coulomb energy is always positive
// and thermal excitation energy is positive
float Qvalue = fExpMass
- daughterLight->fExpMass - daughterHeavy->fExpMass
- scission.Erotate1 - scission.Erotate2; //Qvalue apart from EK
for (;;)
{
Ek = ran->Gaus(scission.ekTot,sigma);
fissionU = fEx + Qvalue - Ek;
if (Ek > 0. && fissionU > 0.) break;
}
//Qvalue -= Ek;
// add the thermal part of kinetic energy
int const nE=200;
float sumE[nE];
int ie = 0;
float probStart = levelDensity->
getLogLevelDensitySpherical(iA,fissionU,(float)0.,(float)0.,(float)0.,
fMInertia);
for (;;)
{
float de = (float)ie*0.5 + 0.25;
if (de >= fissionU) break;
float prob = exp(levelDensity->
getLogLevelDensitySpherical(iA,fissionU-de,0.,0.,0.,fMInertia)
- probStart);
sumE[ie] = prob;
if (ie > 0) sumE[ie] += sumE[ie-1];
ie ++;
if (prob < EkFraction) break;
if (ie >= nE) break;
}
float de = 0.;
if (ie > 0)
{
xran = ran->Rndm();
int iie = 0;
for (;;)
{
if (xran <= sumE[iie]/sumE[ie-1]) break;
iie++;
}
de = (float)iie*0.5 + 0.25;
Ek += de;
fissionU -= de;
}
scission.ekTot = Ek;
asyFissionDivide(); // find spin and excitation energy of two fragments
allProducts.push_back(daughterLight);
allProducts.push_back(daughterHeavy);
}
else if (iChan == 2) //fission decay
{
CNucleus * com = getCompoundNucleus();
com->bResidue = false;
com->bSymmetricFission = true;
// start saddle to scission transition
float Esaddle = yrast->getSymmetricSaddleEnergy(iZ,iA,fJ);
Esaddle -= fPairing + fShell;
scission.init(iZ,iA,fJ,2);
float Escission = scission.getScissionEnergy() - fExpMass;
daughterHeavy = new CNucleus(iZ,iA);
//if mass division is determined from energy at saddle point
if (fissionMassScission == 0)
{
//asyFissionWidthBW(); //try this instead of massAsymmetry()
//if you want
//mass distribution from Sierk's
//asymmetric barriers
massAsymmetry(Isaddle);
bool const notSym = 0;
daughterHeavy->fissionZ = fissionZ;
daughterHeavy->fissionA = fissionA;
daughterHeavy->fissioningA = iA;
daughterHeavy->fissioningZ = iZ;
daughterHeavy->sigma2 = sigma2;
daughterHeavy->iWeight = iWeight;
daughterHeavy->runningWeight = runningWeight;
daughterHeavy->fact = fact;
daughterHeavy->exciteScission(fEx,fJ,notSym);
if (Escission >= Esaddle) timeScission = 0.;
else timeScission = (Esaddle-Escission)*viscosity_saddle;
}
//else the mass division is determined at scission
else
{
daughterHeavy->exciteScission(fEx,fJ);
if (Escission >= Esaddle) timeScission = 0.;
else timeScission = (Esaddle-Escission)*viscosity_scission;
}
daughterHeavy->timeSinceSaddle = 0.;
daughterHeavy->timeSinceStart = timeSinceStart + decayTime;
daughterHeavy->origin = 1;
daughterHeavy->origin2 = 1;
daughterHeavy->parent = this;
daughterHeavy->setVelocityCartesian(velocity[0],velocity[1],velocity[2]);
daughterHeavy->setSpinAxis(spin);
daughterHeavy->timeScission = timeScission;
daughterLight = NULL;
allProducts.push_back(daughterHeavy);
}
else //gamma decay
{
sumGammaEnergy += fEx - GammaEx;
GammaRayEnergy.push_back(fEx - GammaEx);
nGammaRays +=1;
daughterLight = NULL;
daughterHeavy = new CNucleus(iZ,iA);
daughterHeavy->origin = origin;
daughterHeavy->origin2 = origin2;
daughterHeavy->parent = this;
daughterHeavy->timeSinceStart = timeSinceStart + decayTime;
daughterHeavy->excite(GammaEx,GammaJ);
daughterHeavy->iWeight = iWeight;
daughterHeavy->runningWeight = runningWeight;
daughterHeavy->fact = fact;
angleGamma();
allProducts.push_back(daughterHeavy);
if (daughterHeavy->bStable == 1)//for Yrast transitions
{
float GammaJ_temp = GammaJ;
while (GammaJ_temp> 2)
{
nGammaRays +=1;
float Yrast_gamma = yrast->getYrast(iZ,iA,GammaJ_temp)
- yrast->getYrast(iZ,iA,GammaJ_temp-2);
GammaRayEnergy.push_back(Yrast_gamma);
GammaJ_temp = GammaJ_temp -2;
sumGammaEnergy += Yrast_gamma;
}
}
}
}
//************************************************************
/**
* fission mass division - uses the Rusanov systemtics to
* determine the fission-fragment mass distribution.
* \param saddleOrScission is true then the third Rusanov systematics
* are used, i.e., variance is determined from the temperature at the
* scission point
* if false, the second Rusanov systematics is used, i.e, the
* variance is determined from the temperature at the saddle point
*/
void CNucleus::massAsymmetry(bool saddleOrScission)
{
// variance from systemacs
if (saddleOrScission == 1)//asymmetry determined at scission point
sigma2 = scission.sigmaFissionSystematicsScission(iZ,iA,fJ,fU0);
else //asymmetry determined at saddle point
{
sigma2
= scission.sigmaFissionSystematicsSaddle(iZ,iA,fJ,fEx-symSaddlePoint);
fU0 = fEx - symSaddlePoint;
}
//at this point fU0 is the thermal excitation energy above the
//configuration for symmetric division.
SStoreVector store;
int iZ1,iZ2,iA1,iA2;
iA1 = iA/2;
float Amax = 0.;
//float gammaAOld = 1e32;
double gammaTot = 0.;
for (;;)
{
iA2 = iA - iA1;
int iZ1Start= (int)((float)iA1/(float)iA*(float)iZ);
iZ1 = max(3,iZ1Start-8);
iZ1 = max(iZ1_IMF_Max+1,iZ1); //do not overlap with IMF emission
float Zmax = 0.;
float gammaA = 0.;
for (;;)
{
iZ2 = iZ - iZ1;
if (iZ2 <= (float)iZ/17.) break;
if (iA1 == iA2 && iZ1 > iZ2) break; //no double counting
//see if fragments are listed in mass table
if (mass->chart->getIndex(iZ1,iA1) < 0 ||
mass->chart->getIndex(iZ2,iA2) < 0)
{
iZ1++;
continue;
}
float scissionE = scission.getScissionEnergy(iZ1,iA1);
// fU0 has the asymmetric saddle or scission energy removed
float U = fU0 - scissionE + scission.Esymmetric;
if (U <= 0.)
{
if (iZ1 > iZ1Start) break;
iZ1++;
continue;
}
float logLevelDensitySciss =
levelDensity->getLogLevelDensityScission(iA,U,10.);
if (logLevelDensitySciss == 0)
{
if (iZ > iZ1Start) break;
iZ1++;
continue;
}
float gamma= exp(logLevelDensitySciss-logLevelDensity);
if (iA1 == iA2 && iZ1==iZ2 ) gamma /= 2.;
gammaA += gamma;
SStore aStore;
aStore.gamma = (double)gamma;
aStore.iZ = iZ1;
aStore.iA = iA1;
store.push_back(aStore);
Zmax = max(gamma,Zmax);
if (gamma < Zmax*.01) break;
iZ1++;
}
// rescale widths so the sum for each A has a gausiian distribution
//with the widths from systematics
if (gammaA > 0.)
{
float prob = exp(-pow((float)(iA1-iA2)/2.,2)/2./sigma2);
if (iA1 == iA2) prob /= 2.;
double scale = prob/gammaA;
int jj = store.size()-1;
for (;;)
{
if (jj < 0) break;
if (store[jj].iA != iA1) break;
store[jj].gamma *= scale;
jj--;
}
gammaTot += prob;
Amax = max(Amax,prob);
if (prob < Amax*0.001) break;
}
else break;
iA1--;
if (iA1 < (float)iA/17.) break;
}
if (store.empty())
{
//this shouldn't be possible, but this statement is here just in
//case or else the program would get stuck in the following loop
fissionZ = iZ/2;
fissionA = iA/2;
//cout << "iStore == 0 in saddle to scission" << endl;
//cout << " A = " << iA << " Z = " << iZ << " J= " << fJ <<
// " Ex= " << fEx << " U= " << fU0 << endl;
}
else
{
for(unsigned int i=1;i<store.size();i++) store[i].gamma += store.at(i-1).gamma;
double xran = ran->Rndm();
SStoreIter selectedChannel = std::lower_bound(store.begin(),
store.end(),
xran*store.back().gamma,
CompareGammaToX<SStore, float>());
fissionZ = selectedChannel->iZ;
fissionA = selectedChannel->iA;
}
iZ1 = fissionZ;
iZ2 = iZ - iZ1;
iA1 = fissionA;
iA2 = iA - iA1;
}
//************************************************************
/**
* Treats the saddle to scission evaporations
*/
void CNucleus::saddleToScission()
{
EvapEx2 = 0.;
float widthEvaporation = evaporationWidthSS();
float timeDecay = ran->expDecayTime(widthEvaporation);
float newTime;
if (widthEvaporation == 0) newTime = 100000.;
else newTime = timeSinceSaddle + timeDecay;
if (newTime < timeScission && EvapEx2 > 15.)
{
daughterLight = new CNucleus(EvapZ1,EvapA1);
daughterLight->origin = 1;
daughterLight->origin2 = 1;
daughterLight->saddleToSciss = false;
daughterLight->iWeight = 0;
daughterLight->runningWeight = runningWeight;
daughterLight->fact = fact;
daughterLight->timeSinceStart = timeSinceStart + timeDecay;
daughterLight->timeSinceSaddle = newTime;
daughterHeavy = new CNucleus(EvapZ2,EvapA2);
daughterHeavy->timeSinceSaddle = newTime;
daughterHeavy->origin = 1;
daughterHeavy->origin2 = 1;
daughterHeavy->iWeight = 0;
daughterHeavy->runningWeight = runningWeight;
daughterHeavy->fact = fact;
daughterHeavy->timeSinceStart = daughterLight->timeSinceStart;
daughterHeavy->timeScission = timeScission;
daughterLight->excite(EvapEx1);
daughterHeavy->sigma2 = sigma2;
daughterHeavy->fissionZ = fissionZ;
daughterHeavy->fissionA = fissionA;
daughterHeavy->fissioningZ = fissioningZ;
daughterHeavy->fissioningA = fissioningA;
daughterHeavy->exciteScission(EvapEx2,fJ,fissionMassScission);
daughterLight->parent = this;
daughterHeavy->parent = this;
if (evap->decay[EvapMode].Ek > 0)
{
daughterLight->notStatistical = 1;
daughterLight->notStatisticalMode = EvapMode;
daughterLight->bStable = 0;
}
angleIsotropic(); // find the emission angles of the two fragments
CAngle angle(0.,0.);
daughterLight->setSpinAxis(angle);
daughterHeavy->setSpinAxis(spin);
allProducts.push_back(daughterLight);
allProducts.push_back(daughterHeavy);
}
else
{
if(fissionMassScission)massAsymmetry(Iscission);
else
{
float Z = (float)fissionZ/(float)fissioningZ*(float)iZ;
float A = (float)fissionA/(float)fissioningA*(float)iA;
fissionZ = (int)Z;
fissionA = (int)A;
if (ran->Rndm() < Z - (float)fissionZ) fissionZ++;
if (ran->Rndm() < A - (float)fissionA) fissionA++;
}
// go back to the separation that gives us the correct
// fission kinetic energy
scission.sep = scission.sep0;
float scissionE = scission.getScissionEnergy(fissionZ,fissionA);
// for later us calculate fission kinetic energy and rotational
// energy of each fragment
scission.getFissionKineticEnergy(fissionZ,fissionA);
scissionE -= fExpMass;
fissionU = fEx - scissionE;
fissionU = max((float)0.,fissionU);
daughterLight = new CNucleus(fissionZ,fissionA);
daughterLight->origin = 2;
daughterLight->origin2 = 2;
daughterLight->parent = this;
daughterLight->iWeight = 0;
daughterLight->runningWeight = runningWeight;
daughterLight->fact = fact;
daughterLight->timeSinceStart = timeSinceStart
- timeSinceSaddle + timeScission;
daughterHeavy = new CNucleus(iZ-fissionZ,iA-fissionA);
daughterHeavy->origin = 3;
daughterHeavy->origin2 = 3;
daughterHeavy->parent = this;
daughterHeavy->iWeight = 0;
daughterHeavy->runningWeight = runningWeight;
daughterHeavy->fact = fact;
daughterHeavy->timeSinceStart = daughterLight->timeSinceStart;
asyFissionDivide();
allProducts.push_back(daughterLight);
allProducts.push_back(daughterHeavy);
}
}
//************************************************************
/**
* forces decay of 8Be
*/
void CNucleus::force8Be()
{
notStatistical = true;
daughterLight = new CNucleus(2,4);
daughterHeavy = new CNucleus(2,4);
daughterLight->origin = origin;
daughterHeavy->origin = origin;
daughterLight->origin2 = origin2;
daughterHeavy->origin2 = origin2;
daughterLight->parent = this;
daughterHeavy->parent = this;
daughterHeavy->notStatistical = false;
daughterLight->notStatistical = false;
daughterLight->excite(0.,0.);
daughterHeavy->excite(0.,0.);
daughterLight->bStable = 1;
daughterHeavy->bStable = 1;
float width;
if (fEx < 1.)width = 5e-6; // use ground state experimental width
else width = 1.53; //use first excited state experimental width
float decayTime = timeSinceStart+ran->expDecayTime(width);
daughterLight->timeSinceStart = decayTime;
daughterHeavy->timeSinceStart = decayTime;
EvapLPlusS = fJ;
EvapL = (int)fJ;
EvapS1 = 0.;
EvapS2 = 0.;
EvapEk = fEx + 0.0918;
EvapA1 = 4;
EvapA2 = 4;
angleEvap(); // find the emission angles of the two fragments
allProducts.push_back(daughterLight);
allProducts.push_back(daughterHeavy);
return;
}
//************************************************************
/**
* forces decay of 5Li
*/
void CNucleus::force5Li()
{
notStatistical = true;
daughterLight = new CNucleus(1,1);
daughterHeavy = new CNucleus(2,4);
daughterLight->origin = origin;
daughterHeavy->origin = origin;
daughterLight->origin2 = origin2;
daughterHeavy->origin2 = origin2;
daughterLight->parent = this;
daughterHeavy->parent = this;
daughterHeavy->notStatistical = false;
daughterLight->notStatistical = false;
daughterLight->excite(0.,0.5);
daughterHeavy->excite(0.,0.);
daughterLight->bStable = 1;
daughterHeavy->bStable = 1;
float const width = 1.23;
float decayTime = timeSinceStart+ran->expDecayTime(width);
daughterLight->timeSinceStart = decayTime;
daughterHeavy->timeSinceStart = decayTime;
EvapLPlusS = fJ;
EvapL = (int)(fJ-0.5);
EvapS1 = 0.;
EvapS2 = 0.;
EvapEk = fEx + 1.69;
EvapA1 = 1;
EvapA2 = 4;
angleEvap(); // find the emission angles of the two fragments
allProducts.push_back(daughterLight);
allProducts.push_back(daughterHeavy);
return;
}
//************************************************************
/**
* forces decay of 5He
*/
void CNucleus::force5He()
{
notStatistical = true;
daughterLight = new CNucleus(0,1);
daughterHeavy = new CNucleus(2,4);
daughterLight->origin = origin;
daughterHeavy->origin = origin;
daughterLight->origin2 = origin2;
daughterHeavy->origin2 = origin2;
daughterLight->parent = this;
daughterHeavy->parent = this;
daughterHeavy->notStatistical = false;
daughterLight->notStatistical = false;
daughterLight->excite(0.,0.5);
daughterHeavy->excite(0.,0.);
daughterLight->bStable = 1;
daughterHeavy->bStable = 1;
float const width = .648;
float decayTime = timeSinceStart+ran->expDecayTime(width);
daughterLight->timeSinceStart = decayTime;
daughterHeavy->timeSinceStart = decayTime;
EvapLPlusS = fJ;
EvapL = (int)(fJ-0.5);
EvapS1 = 0.;
EvapS2 = 0.;
EvapEk = fEx + 0.798;
EvapA1 = 1;
EvapA2 = 4;
angleEvap(); // find the emission angles of the two fragments
allProducts.push_back(daughterLight);
allProducts.push_back(daughterHeavy);
return;
}
//************************************************************
/**
* forces decay of 9B
*/
void CNucleus::force9B()
{
notStatistical = true;
daughterLight = new CNucleus(1,1);
daughterHeavy = new CNucleus(4,8);
daughterLight->origin = origin;
daughterHeavy->origin = origin;
daughterLight->origin2 = origin2;
daughterHeavy->origin2 = origin2;
daughterLight->excite(0.,0.5);
daughterHeavy->excite(0.,0.);
daughterLight->bStable = 1;
daughterHeavy->bStable = 1;
daughterLight->parent = this;
daughterHeavy->parent = this;
daughterHeavy->notStatistical = false;
daughterLight->notStatistical = false;
float const width = .54E-3;
float decayTime = timeSinceStart+ran->expDecayTime(width);
daughterLight->timeSinceStart = decayTime;
daughterHeavy->timeSinceStart = decayTime;
EvapLPlusS = fJ;
EvapL = (int)(fJ-0.5);
EvapS1 = 0.;
EvapS2 = 0.;
EvapEk = fEx + 0.1851;
EvapA1 = 1;
EvapA2 = 8;
angleEvap(); // find the emission angles of the two fragments
allProducts.push_back(daughterLight);
allProducts.push_back(daughterHeavy);
return;
}
//**********************************************************
/**
* recursive function does multiple binary decays until excitation energy
* is exhausted.
*
* After executation, the pointer vector allProducts- points to each of the
*intermediate and final products produced. The vector stableProducts points
* to just the final stable products. This vector can be accessed to get
* these fragments
*/
void CNucleus:: recursiveDecay()
{
if (!bStable)
{
if (saddleToSciss && fEx > 0.) saddleToScission();
else binaryDecay();
if (abortEvent) return;
}
if (bStable) {
//first force the decay of fragments that are unstable in their ground state
if (iZ==4 && iA == 8) force8Be();
else if (iZ==5 && iA == 9) force9B();
else if (iZ == 3 && iA == 5) force5Li();
else if (iZ == 2 && iA == 5) force5He();
else
{
stableProducts.push_back(this);
return;
}
}
//daughterLight->print();
if (daughterLight != NULL)
{
daughterLight->recursiveDecay();
if (daughterLight->abortEvent)
{
abortEvent = 1;
return;
}
}
//daughterHeavy->print();
//cout << daughterHeavy->iZ << " " << daughterHeavy->iA << " " << daughterHeavy->spin.theta << endl;
//if (daughterHeavy->iA > 180) cout << daughterHeavy->spin.theta << endl;
daughterHeavy->recursiveDecay();
if (daughterHeavy->abortEvent)
{
abortEvent = 1;
return;
}
}
//**********************************************************
/**
* reset the static vectors of products.
*
*/
void CNucleus::resetGlobal()
{
while(!allProducts.empty()) {
CNucleus *toDelete = allProducts.back();
toDelete->daughterLight = NULL;
toDelete->daughterHeavy = NULL;
delete toDelete;
allProducts.pop_back();
};
stableProducts.clear();
iPoint = -1;
}
//*********************************************************
/**
* This reset function should be used before starting another statistical
* decay.
*/
void CNucleus::reset()
{
//local reset
resetGlobal();
daughterLight = NULL;
daughterHeavy = NULL;
bStable = 0;
bResidue = true;
bSymmetricFission = false;
bAsymmetricFission = false;
nGammaRays = 0;
sumGammaEnergy = 0;
}
//***************************************************
/**
* Prints out the information on all the stable decay products
* produced in the statistical decay
*/
void CNucleus::printStableProducts()
{
for (unsigned int i=0;i<stableProducts.size();i++)
{
stableProducts.at(i)->print();
}
}
//*******************************************************************
/**
* Prints out information on all products (stable and intermediates)
* formed in the statistical decay
*/
void CNucleus::printAllProducts()
{
// prints out the information on qll of the decay products
for (unsigned int i=0;i<allProducts.size();i++)
{
allProducts[i]->print();
}
}
//****************************************************************
/**
* sets the excitation energy and spin of the compound nucleus.
\param fEx0 is the excitation energy in MeV
\param dJ0 is the spin in units of hbar
*/
void CNucleus::excite(float fEx0, double dJ0)
{
excite(fEx0,(float)dJ0);
}
//****************************************************************
/**
* sets the excitation energy and spin of the compound nucleus.
\param dEx0 is the excitation energy in MeV
\param dJ0 is the spin in units of hbar
*/
void CNucleus::excite(double dEx0, double dJ0)
{
excite((float)dEx0,(float)dJ0);
}
//****************************************************************
/**
* sets the excitation energy and spin of the compound nucleus.
\param dEx0 is the excitation energy in MeV
\param fJ0 is the spin in units of hbar
*/
void CNucleus::excite(double dEx0, float fJ0)
{
excite((float)dEx0,fJ0);
}
//*****************************************************************
/**
* sets the excitation energy and spin of the compound nucleus.
\param fEx0 is the excitation energy in MeV
\param fJ0 is the spin in units of hbar
*/
void CNucleus::excite(float fEx0, float fJ0)
{
//initialized the excitation of the nucleus
//calculates the level density
notStatistical = 0;
fEx = fEx0;
//make sure we have either interg spin for even mass or half interger
// spin for odd mass
fJ = floor(fJ0);
if (iA%2 == 1) fJ += 0.5;
if (fEx == 0.)
{
bStable = 1;
return;
}
EdefScission = 0.;
fPairing = mass->getPairing(iZ,iA);
fShell = mass->getShellCorrection(iZ,iA);
//fShell = fExpMass - mass.getLiquidDropMass(iZ,iA) - fPairing;
if (iZ <= Zshell)
{
fPairing = 0.;
fShell = 0.;
}
//note1
//old code with standard SM treatment of yrast line
Erot=yrast->getYrast(iZ,iA,fJ);
//new code
//spheroid.init(iZ,iA);
//deformation = spheroid.getDeformationProlate(fJ);
//Erot = spheroid.getRotatePlusDefEnergy(fJ);
//end change
fMInertia = 0.4*pow(r0,2)*pow((float)iA,(float)(5./3.));
fU0 = fEx - Erot;
if (fU0 < 0.)
{
bStable = 1;
return;
}
//decide if to use Hauser-Feshback calculation
HF = 0;
if ( (Erot > fU0/4. && fJ > 10) || iHF == 1) HF = 1;
if (HF == 1)
logLevelDensity = levelDensity->getLogLevelDensitySpherical(
iA,fU0,fPairing,fShell,fJ,fMInertia);
else logLevelDensity = levelDensity->getLogLevelDensitySpherical
(iA,fU0,fPairing,fShell,-fJ,fMInertia);
if (fU0 < 0. || fU0 > 2000.)
{
cout << "Ex= " << fEx << "Erot= " << Erot << " iZ = " << iZ
<< " iA= " << iA << " excite" << endl;
}
temp = levelDensity->getTemp();
if (logLevelDensity == 0.)
{
bStable = 1;
return;
}
}
//*****************************************************************
/**
* sets the excitation energy and of the compound nucleus
* for a Weisskopf calculation (Spin not considered).
\param fEx0 is the excitation energy in MeV
*/
void CNucleus::excite(float fEx0)
{
//initialized the excitation of the nucleus
//calculates the level density
HF = 0;
notStatistical = 0;
fEx = fEx0;
fJ = 0.;
fU0 = fEx;
if (fU0 < 0.)
{
bStable = 1;
return;
}
EdefScission = 0.;
fPairing = mass->getPairing(iZ,iA);
fShell = mass->getShellCorrection(iZ,iA);
//fShell = fExpMass - mass.getLiquidDropMass(iZ,iA) - fPairing;
if (iZ <= Zshell)
{
fPairing = 0.;
fShell = 0.;
}
Erot = 0.;
logLevelDensity =
levelDensity->getLogLevelDensitySpherical(iA,fU0,fPairing,fShell);
if (fU0 < 0. || fU0 > 2000.)
{
cout << "Ex= " << fEx << "Erot= " << Erot << " iZ = " << iZ
<< " iA= " << iA << " excite " << endl;
}
temp = levelDensity->getTemp();
if (logLevelDensity == 0.)
{
bStable = 1;
return;
}
}
//**********************************************************************
/**
* Initializes the excitation of the nucleus at its scission point
* and calculates the level density
*/
void CNucleus::exciteScission(float fEx0,float fJ0,bool sym/*=1*/)
{
saddleToSciss = true;
notStatistical = false;
HF = 0;
fEx = fEx0;
//make sure we have either interg spin for even mass or half interger
// spin for odd mass
fJ = floor(fJ0);
if (iA%2 == 1) fJ += 0.5;
if (sym)
{
scission.init(iZ,iA,fJ,2);
EdefScission = scission.getScissionEnergy();
}
else
{
float Z1 = (float)fissionZ/(float)fissioningZ*(float)iZ;
float A1 = (float)fissionA/(float)fissioningA*(float)iA;
scission.init(iZ,iA,fJ,2,Z1,A1);
EdefScission = scission.getScissionEnergy();
}
EdefScission -= fExpMass;
fPairing = 0.;
fShell = 0.;
Erot = 0.;
if (fEx -EdefScission <= 0.)
{
bStable = 1;
return;
}
//thermal excitation energy above the scission-point configuration
fU0 = fEx - Erot - EdefScission;
if (fU0 < 0.)
{
bStable = 1;
return;
}
logLevelDensity = levelDensity->getLogLevelDensityScission(iA,fU0);
if (fU0 < 0 || fU0 > 2000)
{
cout << "fU0 = " << fU0 << " fEx= " << fEx << " Erot= " << Erot <<
"EdefScission= " << EdefScission << " iZ = " << iZ << "iA= " <<
iA << " fJ= " << fJ << " exciteScission " << endl;
}
temp = levelDensity->getTemp();
if (logLevelDensity == 0.)
{
bStable = 1;
return;
}
}
//**********************************************************************
/**
* Returns the transition-state decay width.
\param saddlePoint is the saddle-point energy in MeV
\param iAfAn indicates that the saddle-point ld parameter is increased by afan
*/
/*
float CNucleus::getWidthZA(float saddlePoint,short iAfAn)
{
if (saddlePoint > fEx) return 0.;
float U = fEx - saddlePoint;
float saddleLD = levelDensity->
getLogLevelDensitySpherical(iA,U,(float)0.,(float)0.,
fJ,fMInertia,iAfAn);
if (saddleLD == 0.) return 0.;
if (saddleLD - logLevelDensity < -65.) return 0.;
float gamma = exp(saddleLD-logLevelDensity)
*levelDensity->getTemp()/2./pi;
return gamma;
}
*/
float CNucleus::getWidthZA(float saddlePoint,short iAfAn)
{
if (saddlePoint > fEx) return 0.;
float U = fEx - saddlePoint;
float const deltaEk = 0.2;
float gamma = 0.;
float gammaMax = 0.;
for(;;)
{
float saddleLD = levelDensity->
getLogLevelDensitySpherical(iA,U,(float)0.,(float)0.,
fJ,fMInertia,iAfAn);
if (saddleLD == 0.) break;
if (saddleLD - logLevelDensity < -65.) break;
float gamma0 = exp(saddleLD-logLevelDensity)/2./pi;
gammaMax = max(gammaMax,gamma0);
gamma += gamma0*deltaEk;
if (gamma0 < gammaMax/200.) break;
U -= deltaEk;
if (U <= 0.) break;
}
return gamma;
}
//*************************************************************************
/**
* Calculates the asymmetric decay width in MeV from the gammaZ formalism.
*
* if noSymmetry = 1 then it only includes channels outside of the fission peak
*/
float CNucleus::asyFissionWidth()
{
short iAfAn = 2;
SStoreVector store;
needSymmetricFission = 0;
float gammaTot = 0;
float saddlePointOld = -10000.;
yrast->prepareAsyBarrier(iZ,iA,fJ);
//float Wigner0 = yrast->WignerEnergy(iZ,iA);
scission.init(iZ,iA,fJ,1);
iZ1_IMF_Max = 400;
for (int iZ1=evap->maxZ+1;iZ1<=iZ/2;iZ1++)
{
int iZ2 = iZ - iZ1;
float A1 = (float)iZ1/(float)iZ*float(iA);
float saddlePoint = yrast->getSaddlePointEnergy(A1);
saddlePoint = (saddlePoint-Erot)*scaleImf + Erot;
//add on a Wigner energy
//saddlePoint += WignerScaled*Wigner0 + WignerAdd;
saddlePoint += WignerAdd;
if (iZ > Zshell) saddlePoint -= fPairing + fShell;
if (noSymmetry && saddlePoint < saddlePointOld && iZ1 > 8)
{
if (iZ/2 - iZ1 > 5 && iA > 120)
{
needSymmetricFission = 1;
iZ1_IMF_Max = iZ1 - 1;
break;
}
}
else saddlePointOld = saddlePoint;
float gammaZ0 = getWidthZA(saddlePoint,iAfAn);
if (iZ1 == iZ - iZ1) gammaZ0 /= 2.;
if (gammaZ0 <= 0.) continue;
int iaMin1 = mass->chart->getAmin(iZ1);
int iaMin2 = iA - mass->chart->getAmax(iZ-iZ1);
int iaMin = max(iaMin1,iaMin2);
int iaMax1 = mass->chart->getAmax(iZ1);
int iaMax2 = iA - mass->chart->getAmin(iZ-iZ1);
int iaMax = min(iaMax1,iaMax2);
if (iZ1 == iZ - iZ1) iaMax = min(iA/2,iaMax);
float gammaZ = 0;
int iStart = store.size();
for (int iA1 = iaMin;iA1<=iaMax;iA1++)
{
int iA2 = iA - iA1;
//make sure I can conserve energy latter
float mass1 = mass->getExpMass(iZ1,iA1);
float mass2 = mass->getExpMass(iZ2,iA2);
scission.getFissionKineticEnergy(iZ1,iA1);
float Qvalue = fExpMass - mass1 - mass2 - scission.ekTot
- scission.Erotate1 - scission.Erotate2;
if( fEx + Qvalue <= 0.) continue;
float saddlePoint = yrast->getSaddlePointEnergy(iZ1,iA1);
saddlePoint = (saddlePoint-Erot)*scaleImf + Erot;
//add on a congruence energy
//float Wigner1 = yrast->WignerEnergy(iZ1,iA1);
//float Wigner2 = yrast->WignerEnergy(iZ2,iA2);
//saddlePoint += WignerScaled*(Wigner1+Wigner2-Wigner0) + WignerAdd;
saddlePoint += WignerAdd;
if (iZ > Zshell) saddlePoint -= fPairing + fShell;
float gamma = getWidthZA(saddlePoint,iAfAn);
if (iZ1 == iZ - iZ1 && iA1 == iA - iA1) gamma /= 2.;
if (gamma <= 0.) continue;
SStore aStore;
aStore.gamma = gamma;
aStore.iZ = iZ1;
aStore.iA = iA1;
store.push_back(aStore);
gammaZ += gamma;
}
// normalize gamma
if (gammaZ != 0.)
{
for (unsigned int j=iStart;j<store.size();j++) store[j].gamma *= gammaZ0/gammaZ;
gammaTot += gammaZ0;
}
}
if (store.empty()) return 0.;
for (unsigned int j=0;j<store.size();j++)
{
store[j].gamma /= gammaTot;
if (j > 0) store[j].gamma += store.at(j-1).gamma;
}
//call random nummber
float x = ran->Rndm();
SStoreIter selectedChannel = std::lower_bound(store.begin(),
store.end(),
x,
CompareGammaToX<SStore, float>());
fissionZ = selectedChannel->iZ;
fissionA = selectedChannel->iA;
float saddlePoint = yrast->getSaddlePointEnergy(fissionZ,fissionA);
saddlePoint = (saddlePoint-Erot)*scaleImf + Erot;
/*
//add on a congruence energy
int iA2 = iA - fissionA;
int iZ2 = iZ - fissionZ;
float Wigner1 = yrast->WignerEnergy(fissionZ,fissionA);
float Wigner2 = yrast->WignerEnergy(iZ2,iA2);
saddlePoint += WignerScaled*(Wigner1+Wigner2-Wigner0) + WignerAdd;
*/
saddlePoint += WignerAdd;
if (iZ > Zshell) saddlePoint -= fPairing + fShell;
fissionU = fEx - saddlePoint;
return gammaTot;
}
//********************************************************************
/**
* Calculates the complex fragments decay widths in MeV where the total fission
* width all channels is normalised to the Bohr-Wheeler result.
*/
float CNucleus::asyFissionWidthBW()
{
short iAfAn = 1;
SStoreVector store;
needSymmetricFission = 0;
int iFission = -1;
float gammaTot = 0;
float saddlePointOld = -10000.;
yrast->prepareAsyBarrier(iZ,iA,fJ);
float A1 = (float)iA/2.;
//the following is the differece between the symmetric saddle points
//Sierk symmetric calculation and my interpolated and extrapolated
//asymmetric barriers using Sierk asymmetry calculations as input
// at J=0, they are garenteed to be identical
// I fill just shift down the asymmetric barrirs by delta now
float delta = yrast->getSaddlePointEnergy(A1) - symSaddlePoint;
for (int iZ1=evap->maxZ+1;iZ1<=iZ/2;iZ1++)
{
float A1 = (float)iZ1/(float)iZ*float(iA);
float saddlePoint = yrast->getSaddlePointEnergy(A1) - delta;
if (iZ > Zshell) saddlePoint -= fPairing + fShell;
float A2 = (float)(iZ1-1)/(float)(iZ)*float(iA);
float A3 = (float)(iZ1+1)/(float)(iZ)*float(iA);
float A4 = (float)(iZ1-2)/(float)(iZ)*float(iA);
float A5 = (float)(iZ1+2)/(float)(iZ)*float(iA);
float saddlePoint2 = yrast->getSaddlePointEnergy(A2) - delta;
float saddlePoint3 = yrast->getSaddlePointEnergy(A3) - delta;
float saddlePoint4 = yrast->getSaddlePointEnergy(A4) - delta;
float saddlePoint5 = yrast->getSaddlePointEnergy(A5) - delta;
saddlePoint = (saddlePoint+saddlePoint2+saddlePoint3
+saddlePoint4+saddlePoint5)/5.;
if (saddlePoint < saddlePointOld && iZ1 > 8 && iFission == -1)
{
if (iZ/2 - iZ1 > 5)
{
iFission = store.size();
}
}
else saddlePointOld = saddlePoint;
float gammaZ0 = getWidthZA(saddlePoint,iAfAn);
if (iZ1 == iZ - iZ1) gammaZ0 /= 2.;
if (gammaZ0 <= 0.) continue;
int iaMin1 = mass->chart->getAmin(iZ1);
int iaMin2 = iA - mass->chart->getAmax(iZ-iZ1);
int iaMin = max(iaMin1,iaMin2);
int iaMax1 = mass->chart->getAmax(iZ1);
int iaMax2 = iA - mass->chart->getAmin(iZ-iZ1);
int iaMax = min(iaMax1,iaMax2);
if (iZ1 == iZ - iZ1) iaMax = min(iA/2,iaMax);
float gammaZ = 0;
int iStart = store.size();
for (int iA1 = iaMin;iA1<=iaMax;iA1++)
{
float saddlePoint = yrast->getSaddlePointEnergy(iZ1,iA1);
if (iZ > Zshell) saddlePoint -= fPairing + fShell;
float gamma = getWidthZA(saddlePoint,iAfAn);
if (iZ1 == iZ - iZ1 && iA1 == iA - iA1) gamma /= 2.;
if (gamma <= 0.) continue;
SStore aStore;
aStore.gamma = gamma;
aStore.iZ = iZ1;
aStore.iA = iA1;
store.push_back(aStore);
gammaZ += gamma;
}
// normalize gamma
if (gammaZ != 0.)
{
for (unsigned int j=iStart;j<store.size();j++) store[j].gamma *= gammaZ0/gammaZ;
gammaTot += gammaZ0;
}
}
if (store.empty())
{
fissionZ = iZ/2;
fissionA = iA/2;
fissionU = 0.;
return 0.;
}
// to normalise fission peak to Bohr-wheeler width
if (iFission > 0)
{
float gammaFission = 0.;
for (unsigned int i=iFission;i<store.size();i++)
{
gammaFission += store.at(i).gamma;
}
float gammaBW = BohrWheelerWidth();
float ratio = gammaBW/gammaFission;
gammaTot = gammaBW;
for (unsigned int i=iFission;i<store.size();i++)
{
store[i].gamma *= ratio;
}
//set other imf's to zero
for (unsigned int i=0;i<(unsigned int)iFission;i++)
{
store[i].gamma = 0.;
}
}
for (unsigned int j=0;j<store.size();j++)
{
store[j].gamma /= gammaTot;
if (j > 0) store[j].gamma += store[j-1].gamma;
}
//call random nummber
float x = ran->Rndm();
SStoreIter selectedChannel = std::lower_bound(store.begin(),
store.end(),
x,
CompareGammaToX<SStore, float>());
fissionZ = selectedChannel->iZ;
fissionA = selectedChannel->iA;
float saddlePoint = yrast->getSaddlePointEnergy(fissionZ,fissionA);
if (iZ > Zshell) saddlePoint -= fPairing + fShell;
fissionU = fEx - saddlePoint;
return gammaTot;
}
//*************************************************************************
/**
* Uses the GammaZA formalism to get complex fragment decay widths as in the
* original GEMINI.
*
* The asymmetric fission width are in MeV.
*/
float CNucleus::asyFissionWidthZA()
{
short iAfAn = 2;
SStoreVector store;
needSymmetricFission = 0;
float gammaTot = 0;
float saddlePointOld = -10000.;
yrast->prepareAsyBarrier(iZ,iA,fJ);
//yrast->printAsyBarrier();
//float Wigner0 = yrast->WignerEnergy(iZ,iA);
scission.init(iZ,iA,fJ,1);
iZ1_IMF_Max = 400;
for (int iZ1=evap->maxZ+1;iZ1<=iZ/2;iZ1++)
{
int iZ2 = iZ - iZ1;
float A1 = (float)iZ1/(float)iZ*float(iA);
float saddlePoint = yrast->getSaddlePointEnergy(A1);
saddlePoint = (saddlePoint-Erot)*scaleImf + Erot;
//add on a congruence energy
//saddlePoint += WignerScaled*Wigner0+WignerAdd;
saddlePoint += WignerAdd;
if (iZ > Zshell) saddlePoint -= fPairing + fShell;
if (noSymmetry && saddlePoint < saddlePointOld && iZ1 > 8
&& iZ/2 - iZ1 > 5)
{
needSymmetricFission = 1.;
iZ1_IMF_Max = iZ1 - 1;
break;
}
else saddlePointOld = saddlePoint;
int iaMin1 = mass->chart->getAmin(iZ1);
int iaMin2 = iA - mass->chart->getAmax(iZ-iZ1);
int iaMin = max(iaMin1,iaMin2);
int iaMax1 = mass->chart->getAmax(iZ1);
int iaMax2 = iA - mass->chart->getAmin(iZ-iZ1);
int iaMax = min(iaMax1,iaMax2);
if (iZ1 == iZ - iZ1) iaMax = min(iA/2,iaMax);
for (int iA1 = iaMin;iA1<=iaMax;iA1++)
{
int iA2 = iA - iA1;
//make sure I can conserve energy latter
float mass1 = mass->getExpMass(iZ1,iA1);
float mass2 = mass->getExpMass(iZ2,iA2);
scission.getFissionKineticEnergy(iZ1,iA1);
float Qvalue = fExpMass - mass1 - mass2 - scission.ekTot
- scission.Erotate1 - scission.Erotate2;
if( fEx + Qvalue <= 0.) continue;
float saddlePoint = yrast->getSaddlePointEnergy(iZ1,iA1);
saddlePoint = (saddlePoint-Erot)*scaleImf + Erot;
//add on a congruence energy
/*
float Wigner1 = yrast->WignerEnergy(iZ1,iA1);
float Wigner2 = yrast->WignerEnergy(iZ2,iA2);
saddlePoint += WignerScaled*(Wigner1+Wigner2-Wigner0)+WignerAdd;
*/
saddlePoint += WignerAdd;
if (iZ > Zshell) saddlePoint -= fPairing + fShell;
float gamma = getWidthZA(saddlePoint,iAfAn);
if (iZ1 == iZ - iZ1 && iA1 == iA - iA1) gamma /= 2.;
if (gamma <= 0.) continue;
/*
// the following paragraph of code corrects the Moretto
//decay width such that a Lestone like logic is used.
//This was tried at
//some point, but for symmetric fission we obtained better agreement
//for fusion and splattion reactions with the standard
//Bohr-Wheeler value. It therefore was inconsistent to used
//the Lestone logical for asymmetric fission
//
// start Lestone correction
//float R1 = pow((float)iA1,(float)(1./3.))*r0;
//float R2 = pow((float)(iA-iA1),(float)(1./3.))*r0;
//float momInertia1 = 0.4*(float)iA*pow(R1,2);
//float momInertia2 = 0.4*(float)(iA-iA1)*pow(R2,2);
//float Areduced = (float)(iA1*(iA-iA1))/float(iA);
//float momInertiaPerp = momInertia1 + momInertia2 +
// Areduced*(R1+R2+sep);
//float momInertiaPara = momInertia1 + momInertia2;
//float momInertiaEff = 1./(1./momInertiaPara - 1./momInertiaPerp);
//float corr = LestoneCorrection(fEx-saddlePoint,momInertiaEff,iAfAn);
//gamma *= corr;
//end lestone correction
*/
gammaTot += gamma;
SStore aStore;
aStore.gamma = gamma;
aStore.iZ = iZ1;
aStore.iA = iA1;
store.push_back(aStore);
}
}
if (store.empty()) return 0.;
for (unsigned int j=0;j<store.size();j++)
{
store[j].gamma /= gammaTot;
if (j > 0) store[j].gamma += store.at(j-1).gamma;
}
//call random nummber
float x = ran->Rndm();
SStoreIter selectedChannel = std::lower_bound(store.begin(),
store.end(),
x,
CompareGammaToX<SStore, float>());
fissionZ = selectedChannel->iZ;
fissionA = selectedChannel->iA;
float saddlePoint = yrast->getSaddlePointEnergy(fissionZ,fissionA);
saddlePoint = (saddlePoint-Erot)*scaleImf + Erot;
//add on a congruence energy
/*
int iA2 = iA - fissionA;
int iZ2 = iZ - fissionZ;
float Wigner1 = yrast->WignerEnergy(fissionZ,fissionA);
float Wigner2 = yrast->WignerEnergy(iZ2,iA2);
saddlePoint += WignerScaled*(Wigner1+Wigner2-Wigner0) + WignerAdd;
*/
saddlePoint += WignerAdd;
if (iZ > Zshell) saddlePoint -= fPairing + fShell;
fissionU = fEx - saddlePoint;
return gammaTot;
}
//********************************************************************
float CNucleus::LestoneFissionWidth()
/**
* Gives the fission decay width from Lestone in units of MeV.
* Lestone gives an extention of the BohrWheeler width with the inclusion
* of one of the angular momentum degrees of freedom (tilting mode).
* See PRC 59 (1999) 1540.
*/
{
float gamma = BohrWheelerWidth();
if (gamma <= 0.) return gamma;
short iAfAn = 1;
float momInertiaPerp = yrast->getMomentOfInertiaSierk(fJ);
float momInertiaPara = yrast->momInertiaMin;
float momInertiaEff = 1.0/(1.0/momInertiaPara-1.0/momInertiaPerp);
float U = fEx - symSaddlePoint;
float corr = LestoneCorrection(U,momInertiaEff,iAfAn);
return gamma*corr;
}
//*************************************************************************
float CNucleus::BohrWheelerWidth()
/**
* Gives the Bohr-Wheeler decay width for fission in units of MeV
*/
{
symSaddlePoint = yrast->getSymmetricSaddleEnergy(iZ,iA,fJ) + barAdd;
if (iZ > Zshell) symSaddlePoint -= fPairing + fShell;
/*float fJJ = fJ;
if (fJ > yrast->Jmax) fJJ = yrast->Jmax;*/
short iAfAn = 1;
float gamma = getWidthZA(symSaddlePoint,iAfAn)*fissionScaleFactor;
return gamma;
}
//************************************************
/**
* Responsible for subdividing spin and excitation energy for
* asymmetry fission.
*
* its uses a two-sphere approximation to get collective modes
*/
void CNucleus::asyFissionDivide()
{
//first a statement to handle a bad case
if (fissionU <= 0.)
{
daughterLight->excite(0.,0.);
daughterHeavy->excite(0.,0.);
float phi= 2.*pi*ran->Rndm();
float theta = acos(1.0-2.0*ran->Rndm());
CAngle symmetryCM(theta,phi);
split(symmetryCM);
return;
}
float A1 = (float)fissionA;
float A2 = (float)(iA-fissionA);
float Ared = A1*A2/(A1+A2);
float U1 = fissionU*A1/(A1+A2);
float U2 = fissionU - U1;
float r1 = scission.r0*pow(A1,(float)(1./3.));
float r2 = scission.r0*pow(A2,(float)(1./3.));
float MInertia1 = 0.4*A1*pow(r1,2);
float MInertia2 = 0.4*A2*pow(r2,2);
float MInertiaOrbit = Ared*pow(r1+r2+scission.sep,2);
float MInertia12 = MInertia1 + MInertia2;
float MInertiaSaddle = MInertia12 + MInertiaOrbit;
float aden1 = levelDensity->getLittleA(fissionA,U1);
//float entropy1 = levelDensity->getEntropy();
float aden2 = levelDensity->getLittleA(iA-fissionA,U2);
//float entropy2 = levelDensity->getEntropy();
float aden = aden1 + aden2;
//float entropy0 = entropy1 + entropy2;
float temp = sqrt(fissionU/aden);
float entropy0 = 2.*sqrt(aden*fissionU);
float fact10 = MInertiaOrbit*(MInertia2-MInertia1)
/(2.0*MInertia1*MInertia2);
float fact1 = sqrt(pow(fact10,2)+1);
float theta = atan(fact10+fact1);
float fact3 = MInertia12/(MInertia1*MInertia2);
float c = cos(theta);
float s = sin(theta);
float cc = pow(c,2);
float ss = pow(s,2);
float fact4 = 2.0*s*c/MInertiaOrbit;
float aBending = (cc/MInertia1+ss/MInertia2
+1.0/MInertiaOrbit-fact4)*kRotate;
float aWriggling = (ss/MInertia1+cc/MInertia2
+1.0/MInertiaOrbit+fact4)*kRotate;
float aTilting = MInertiaOrbit/MInertia12/MInertiaSaddle*kRotate;
float aTwisting = fact3*kRotate;
float K,JTwisting,JBendingX,JBendingZ,JWrigglingX,JWrigglingZ;
float deltaE;
int tries = 0;
for (;;)
{
//choose K tilting
K = selectJ(aTilting,aden,entropy0,fJ);
//choose twisting
float sig = 5.*sqrt(temp/aTwisting);
JTwisting = selectJ(aTwisting,aden,entropy0,sig);
//choose bending for X direction
sig = 5.0*sqrt(temp/aBending);
JBendingX = selectJ(aBending,aden,entropy0,sig);
//choose Jbending for Z direction
JBendingZ = selectJ(aBending,aden,entropy0,sig);
//choose Jwriggling for x direction
sig = 5.0*sqrt(temp/aWriggling);
JWrigglingX=selectJ(aWriggling,aden,entropy0,sig);
//choose Jwriggling for Z direction
JWrigglingZ=selectJ(aWriggling,aden,entropy0,sig);
deltaE = 0.5*(aTilting*pow(K,2) + aTwisting*pow(JTwisting,2)
+ aBending*(pow(JBendingX,2)+pow(JBendingZ,2))
+ aWriggling*(pow(JWrigglingX,2)+pow(JWrigglingZ,2)));
if (deltaE <= fissionU) break;
tries++;
if (tries == 15)
{
// not able to find a solution for some reason.
//so just turn off the depolarization modes.
//cout << "tries too big in asyFissionDivide" << endl;
//abort();
K = 0.;
JTwisting = 0.;
JBendingX = 0.;
JBendingZ = 0.;
JWrigglingX = 0.;
JWrigglingZ = 0.;
deltaE = 0.;
break;
}
}
//calculate components of r1, depolarizing mode of fragment 1
float R1x = JBendingX*c + JWrigglingX*s;
float R1y = JTwisting;
float R1z = JBendingZ*c + JWrigglingZ*s;
// calculate components of r2
float R2x = JWrigglingX*c - JBendingX*s;
float R2y = -JTwisting;
float R2z = JWrigglingZ*c - JBendingZ*s;
float omega_t = ran->Rndm()*2.*pi;
float J0xz = sqrt(pow(fJ,2)-pow(K,2));
float J0x = J0xz*sin(omega_t);
float J0z = J0xz*cos(omega_t);
//calculate components of s1
float ratio1 = MInertia1/MInertiaSaddle;
float S1x = J0x*ratio1 + R1x;
float S1y = MInertia1/MInertia12*K + R1y;
float S1z = J0z*ratio1 + R1z;
float S1 = sqrt(pow(S1x,2) + pow(S1y,2) + pow(S1z,2));
//calculate components of s2
float ratio2 = MInertia2/MInertiaSaddle;
float S2x = J0x*ratio2 + R2x;
float S2y = MInertia2/MInertia12*K + R2y;
float S2z = J0z*ratio2 + R2z;
float S2 = sqrt(pow(S2x,2) + pow(S2y,2) + pow(S2z,2));
//note that fissionU was calculated as the thermal energy above
//a rigidly rotation configuration. The rotational energy of the
//individual frgament's in that configuration has already been
//subtracted. As we now about to assign new rotational energies
//to these fragment, this component must be corrected for
//old rotational energies
float Erotate10 = scission.Erotate1;
float Erotate20 = scission.Erotate2;
float Erotate1 = pow(S1,2)*kRotate/2./MInertia1;
float Erotate2 = pow(S2,2)*kRotate/2./MInertia2;
fissionU += Erotate10 + Erotate20 - Erotate1 - Erotate2;
if (fissionU <= 0.)
{
daughterLight->excite(0.,0.);
daughterHeavy->excite(0.,0.);
float phi= 2.*pi*ran->Rndm();
float theta = acos(1.0-2.0*ran->Rndm());
CAngle symmetryCM(theta,phi);
split(symmetryCM);
return;
}
float de = 0.5;
float deltaP1 = mass->getPairing(daughterLight->iZ,daughterLight->iA);
float deltaP2 = mass->getPairing(daughterHeavy->iZ,daughterHeavy->iA);
float deltaW1 = mass->getShellCorrection(daughterLight->iZ,daughterLight->iA);
float deltaW2 = mass->getShellCorrection(daughterHeavy->iZ,daughterHeavy->iA);
const int Nuu_max = 1000;
float uu[Nuu_max];
float probuu[Nuu_max];
float U10 = U1;
float U20 = U2;
float probuu_max = 0.;
int Nuu = 0;
bool eject = false;
int count = 0;
for (;;)
{
count++;
if (count == 1000)
{
cout << "too many tries " << fissionU << endl;
abort();
}
float uu1 = U10;
float uu2 = U20;
aden1 = levelDensity->getLittleA(daughterLight->iA,uu1,deltaP1,deltaW1);
aden2 = levelDensity->getLittleA(daughterHeavy->iA,uu2,deltaP2,deltaW2);
if (uu1 > 0. && uu2 > 0.)
{
if (Nuu ==0)
{
probuu[Nuu] = 1.;
entropy0 = 2.*(sqrt(aden1*uu1)+sqrt(aden2*uu2));
}
else
{
float entropy = 2.*(sqrt(aden1*uu1)+sqrt(aden2*uu2));
float pr = exp(entropy - entropy0);
probuu[Nuu] = pr;
}
probuu_max = max(probuu[Nuu],probuu_max);
if (probuu[Nuu] < .01*probuu_max) eject = true;
uu[Nuu] = U10;
if (Nuu > 0) probuu[Nuu] += probuu[Nuu-1];
Nuu++;
if (Nuu > Nuu_max)
{
cout << " incrase Nuu_max" << endl;
abort();
}
}
else eject = true;
if (eject)
{
if (de < 0.) break;
de = -de;
U10 = U1 + de;
U20 = U2 - de;
eject = false;
}
else
{
U10 += de;
U20 -= de;
if (U10 <=0.) break;
if (U20 <=0.)
{
de = -de;
U10 = U1 + de;
U20 = U2 - de;
eject = false;
}
}
}
if (Nuu == 0)
{
cout << " Nuu = 0 " << fissionU << " " <<
daughterLight->iZ << " " << daughterLight->iA << " " <<
daughterHeavy->iZ << " " << daughterHeavy->iA << endl;
daughterLight->excite(0.,0.);
daughterHeavy->excite(0.,0.);
float phi= 2.*pi*ran->Rndm();
float theta = acos(1.0-2.0*ran->Rndm());
CAngle symmetryCM(theta,phi);
split(symmetryCM);
return;
}
float prob = ran->Rndm();
int i = 0;
for (;;)
{
if (prob <= probuu[i]/probuu[Nuu-1]) break;
i++;
}
float Ex1 = uu[i] + Erotate1;
float Ex2 = fissionU - uu[i] + Erotate2;
if (Ex1 <0.) Ex1 = 0.;
if (Ex2 <0.) Ex2 = 0.;
/*
temp = sqrt(fissionU/aden);
float sig = sqrt(2.0*pow(temp,3)*aden1*aden2/aden);
U1 = fissionU*A1/(A1+A2);
U2 = fissionU - U1;
entropy0 = 2.0*sqrt(aden*fissionU);
float demax = min((float)5.0*sig,U1);
float demin = min((float)5.0*sig,U2);
tries = 0;
for (;;)
{
deltaE = (demin+demax)*ran->Rndm() - demax;
float y = exp(2.0*sqrt(aden1*(U1+deltaE))
+2.0*sqrt(aden2*(U2-deltaE))-entropy0);
float yy = ran->Rndm();
// cout << deltaE << " " << y << " " << yy << endl;
if (yy <= y) break;
tries++;
if (tries == 10)
{
//cout << "2nd tries too big in asyFissionDivide" << endl;
deltaE = 0.;
break;
}
}
float Ex1 = U1 + deltaE + Erotate1;
float Ex2 = U2 - deltaE + Erotate2;
*/
// the following should be zero if energy is conserved
//cout << fEx + fExpMass - daughterLight->fExpMass - daughterHeavy->fExpMass
//- scission.ekTot -Ex1 - Ex2 << endl;
float fJ1,fJ2;
if (fissionA%2 == 0)
{
fJ1 = round(S1);
}
else
{
fJ1 = round(S1+.5) - .5;
}
daughterLight->excite(Ex1,fJ1); //rjc
//daughterLight->excite(0.,0.);
if ((iA-fissionA)%2 == 0)
{
fJ2 = round(S2);
}
else
{
fJ2 = round(S2+.5) - .5;
}
daughterHeavy->excite(Ex2,fJ2);
// this part of the subroutines calculates the final
// centre-of-mass velocity vectors of the complex fragments and
// their spin vectors. vectors are specified as:
// x_y_z
// x is polar angular coordinate for vector (theta or phi)
// y identifies the vector
// options : V1 - velocity of fragment 1
// S1 - spin of fragment 1
// V2 - velocity of fragment 2
// S2 - spin of fragment 2
// symmetry - specifies the symmetry axis of
// saddle-scission point configuration
// J0 - spin vector of fragment 0 (decaying system)
// V0 - velocity vector of fragment 0
// Z is frame in which polar coordinates are specified
// r - rotation frame of saddle point configuration
// see Schmitt and Pacheco Nucl Phys. A379 (1982) 313
// J0 - frame with Vector J0 as Z axis
// cm - centre of mass frame of reaction.
// in the frame of the di-nuclear complex the total angular
// momentum vector processes. The theta and phi angles at
// scission are. see schmitt and pacheco for coordinate system.
CAngle J0r;
if (fJ == 0.0)
{
J0r.phi= 2.*pi*ran->Rndm();
J0r.theta = -acos(1.0-2.0*ran->Rndm());
}
else
{
J0r.theta = -acos(J0z/fJ);
J0r.phi = atan2(K,J0x);
}
// the symmetry axis occurs at x=0,z=0 in the above coordinate
// system i.e. theta_symmetry_r=90., phi_symmetry_r =90. degrees, find
// angles of the symmetry axis relative to the j0 vector
// (.i.e. rotate everything so that J0 is parallel to z axis)
CAngle symmetryJ0;
CAngle perp(pi/2.,pi/2.); //rjc
symmetryJ0 = CAngle::transform(perp,J0r);
// randomize the phi coordinate.
float dphi = 2.*pi*ran->Rndm();
symmetryJ0.phi += dphi;
if (symmetryJ0.phi > 2.*pi) symmetryJ0.phi -= 2.*pi;
// find symmetry axis in lab frame
CAngle symmetryCM;
symmetryCM = CAngle::transform(symmetryJ0,spin);
// in the rotating frame of dinuclear system, the spin vector of
// fragment 1 is s1X,s1Y,s1Z, relative to di nuclear coordinate system
// mentioned above
CAngle S1r;
if (S1 == 0.)
{
S1r.theta = acos(1.0-2.0*ran->Rndm());
S1r.phi = 2.*pi*ran->Rndm();
}
else
{
S1r.theta = acos(S1z/S1);
S1r.phi = atan2(S1y,S1x);
}
// rotate to frame of J0 vector (.i.e. z axis parallel to J0)
CAngle S1J0;
S1J0 = CAngle::transform(S1r,J0r);
S1J0.phi += dphi;
if (S1J0.phi > 2.*pi) S1J0.phi -= 2.*pi;
// rotate to lab frame
daughterLight->spin = CAngle::transform(S1J0,spin);
// do the same for fragment 2
CAngle S2r;
if (S2 == 0.0)
{
S2r.theta = acos(1.0-2.0*ran->Rndm());
S2r.phi = 2.*pi*ran->Rndm();
}
else
{
S2r.theta = acos(S2z/S2);
S2r.phi = atan2(S2y,S2x);
}
// rotate to frame of J0 vector (.i.e. z axis parallel to J0)
CAngle S2J0;
S2J0 = CAngle::transform(S2r,J0r);
S2J0.phi += dphi;
if (S2J0.phi > 2.*pi) S2J0.phi -= 2.*pi;
// rotate to lab frame
daughterHeavy->spin = CAngle::transform(S2J0,spin);
// calculate velocities in frame of emitting system
// first find the kinetic energy of separation
//Ek = 1.44*(float)fissionZ*(float)(iZ-fissionZ)/(r1+r2+sep)
//generlization of Viola see Hinde Nucl Phys A472, 318 (1987).
//float Ek = yrast->viola((float)fissionZ,A1,(float)(iZ-fissionZ),A2);
//float Ek = 0.755*(float)fissionZ*(float)(iZ-fissionZ)/
// (pow(A1,(float)(1./3.))+pow(A2,(float)(1./3.)))
// + 7.3;
// find orbital angular momentum
//float ratio_l = MInertiaOrbit/MInertiaSaddle;
//float lx = J0x*ratio_l - R1x - R2x;
//float lz = J0z*ratio_l - R1z - R2z;
//float l = sqrt(pow(lx,2) + pow(lz,2));
//ek = ek + 20.8993*l**2.0/M_inertia_orbit
split(symmetryCM);
}
//************************************************
/**
* Randomly selects the spin associated with a fission normal modes such as
* wriggling, twisting, etc.
*/
float CNucleus::selectJ(float ac, float aden, float entropy0,float Jmax)
{
float Jmax1 = sqrt(2.0*fissionU/ac);
float Jmax2 = min(Jmax,Jmax1);
float J;
int tries = 0;
for (;;)
{
J = Jmax2*(1.0-2.0*ran->Rndm());
float diff = max( fissionU-0.5*ac*J*J, 0.0 );
float y1 = exp(2.0*sqrt(aden*diff)-entropy0);
float y2 = ran->Rndm();
if (y2 < y1) break;
tries++;
if (tries == 15)
{
//after 15 tries, return zero
//cout << "tries too big in selectJ" << endl;
//abort();
return 0.;
}
}
return J;
}
//****************************************
/**
* Sets the angle of the compound nucleus spin axis.
*
\param spin0 is the (theta,phi) angles in radians
*/
void CNucleus::setSpinAxis(CAngle spin0)
{
spin = spin0;
}
//****************************************
/**
* Sets the angle of the compound nucleus spin axis.
*
\param spin0 is the (theta,phi) angles in degrees
*/
void CNucleus::setSpinAxisDegrees(CAngle spin0)
{
spin = spin0;
spin.theta *= CAngle::pi/180.;
spin.phi *= CAngle::pi/180.;
}
//***************************************
/**
* Sets the velocity of the fragment in polar coordinates
*
/param vel is velocity in units of cm/ns
/param theta is theta angle in radians
/param phi is phi angle in radians
*/
void CNucleus::setVelocityPolar(float vel/*=0.*/,
float theta/*=0.*/, float phi/*=0.*/)
{
//default values are zero
velocity[0] = vel*sin(theta)*cos(phi);
velocity[1] = vel*sin(theta)*sin(phi);
velocity[2] = vel*cos(theta);
}
//***************************************
/**
* Sets the velocity of the fragment in cartesian coordinates.
*
* with no input parameter, all components are set to zero.
\param vx is x component of velocity in cm/ns
\param vy is y component of velocity in cm/ns
\param vz is z component of velocity in cm/ns
*/
void CNucleus::setVelocityCartesian(float vx/*=0.*/, float vy/*=0.*/,
float vz/*=0.*/)
{
//default values are zero
velocity[0] = vx;
velocity[1] = vy;
velocity[2] = vz;
}
//*****************************************
/**
* Calculates the total decay widths in MeV for light particle evaporation.
* using the Hauser-Feshbach or Weiskopf formulism
*/
float CNucleus::evaporationWidth()
{
float width = 0.;
EcostMin = 1000.;
for (int i=0;i<evap->nLight;i++)
{
lightP = evap->lightP[i];
if (HF) evap->prob[i] = hauserFeshbach(i);
else evap->prob[i] = weiskopf((bool)0);
evap->prob[i] *= lightP->suppress;//user-given suppression factor
width += evap->prob[i];
if (i > 0) evap->prob[i] += evap->prob[i-1];
}
if (width <= 0.)
{
return 0.;
}
return width;
}
//*****************************************
/**
* Calculated the Hauser-Feshbach decay width in MeV for a given channel
\param iChannel is the channel of the evaporated particle
*/
float CNucleus::hauserFeshbach(int iChannel)
{
//returns the Hauser-Feshbach evaporation width for a given channel
//width is in units of MeV
if (exp(-lightP->fEx/temp) < 0.01 && iChannel > 1) return 0.;
lightP->residue.iZ = iZ - lightP->iZ;
if (lightP->iZ >= lightP->residue.iZ) return 0.;
lightP->residue.iA = iA - lightP->iA;
if (lightP->iA >= lightP->residue.iA) return 0.;
if (lightP->residue.iZ >= lightP->residue.iA) return 0.;
//products must lie on the chart of nuclides used by gemini
if (lightP->residue.iA < mass->chart->getAmin(lightP->residue.iZ)) return 0.;
if (lightP->residue.iA > mass->chart->getAmax(lightP->residue.iZ)) return 0.;
//note1, new treament of yrast line
//spheroid.init(lightP->residue.iZ,lightP->residue.iA);
//spheroid.setDeformationProlate(deformation);
//odd A nuclei have 1/2 integer spin
lightP->odd =0;
if (lightP->residue.iA%2 == 1) lightP->odd = 1;
if (lightP->residue.iZ > Zshell)
lightP->fPair = mass->getPairing(lightP->residue.iZ,lightP->residue.iA);
else lightP->fPair = 0.;
lightP->residue.fExpMass = mass->getExpMass(lightP->residue.iZ,lightP->residue.iA);
lightP->fShell = 0.;
if (lightP->residue.iZ > Zshell) lightP->fShell =
mass->getShellCorrection(lightP->residue.iZ,lightP->residue.iA);
lightP->separationEnergy = lightP->residue.fExpMass + lightP->fExpMass - fExpMass;
rResidue = r0*pow((float)lightP->residue.iA,(float)(1./3.));
lightP->fMInertia = 0.4*(float)lightP->residue.iA*pow(rResidue,2);
lightP->fMInertiaOrbit = (float)(lightP->residue.iA*lightP->iA)/
(float)(lightP->residue.iA+lightP->iA)*pow(rResidue+lightP->rLight+2.,2);
// decide if decay mode is too costly` (very rare) if so abort calculation
Ecoul = 1.44*(float)(lightP->iZ*lightP->residue.iZ)/(rResidue+lightP->rLight+2.);
float Ecost = lightP->separationEnergy + Ecoul;
if (Ecost < EcostMin) EcostMin = Ecost;
if (exp(-(Ecost-EcostMin)/temp) < threshold && lightP->iA > 1) return 0.;
S2Start = roundf(lightP->fMInertia/
(lightP->fMInertia+lightP->fMInertiaOrbit)*fJ);
if (lightP->odd) S2Start += 0.5;
//prepare transmission coeff
lightP->tlArray->prepare(lightP->residue.iZ);
lightP->width = S2Loop(-1.);
return lightP->width;
}
//***************************************************************
/**
* Calculates \f$\sum_{\ell=\ell_{min}}^{\ell_{max}} T_{\ell}(\varepsilon)\f$
\param ek is \f$\varepsilon\f$, the kinetic energy in MeV
\param temp is the temperature on the residue in MeV
*/
float CNucleus::getSumTl(float ek,float temp)
{
//function used by hauserFeshbach
float sumTl = 0.;
float tlWeightMax = 0.;
SStoreSubVector storeSub;
int iL = lMin;
float scale = 1.;
if (lightP->iA == 1 && lightP->iZ == 1)
{
//mass at the attractor line
float Aeal = 2.045*(float)lightP->residue.iZ
+ 3.57e-3*pow((float)lightP->residue.iZ,2);
float r_eal = 1.2*pow(Aeal,float(1./3.)) + 1.167;
float r = 1.2*pow((float)lightP->residue.iA,(float)(1./3.)) + 1.167;
scale = r/r_eal; //rjc
}
else if (lightP->iA == 4)
{
//mass at the attractor line
float Aeal = 2.045*(float)lightP->residue.iZ
+ 3.57e-3*pow((float)lightP->residue.iZ,2);
float deltaA = (float)lightP->residue.iA - Aeal;
scale = 1.+deltaA*(-5.412976E-04-9.176213E-02/(float)lightP->residue.iZ
+ 3.916151E-06*(float)lightP->residue.iZ);
scale = 1./scale;
}
for (;;)
{
float tl = lightP->tlArray->getTl(iL,ek*scale,temp);
//cout << iL << " " << ek << " " << lightP->residue.iZ << " " << tl << endl;
float maxLplusS = min(iL+lightP->fJ,lPlusSMax);
float minLplusS = max(fabs(iL-lightP->fJ),lPlusSMin);
float tlWeight = tl*(maxLplusS - minLplusS + 1.);
SStoreSub aStoreSub;
aStoreSub.gamma = tlWeight;
if (!storeSub.empty()) aStoreSub.gamma += storeSub.back().gamma;
aStoreSub.L = iL;
storeSub.push_back(aStoreSub);
sumTl += tlWeight;
tlWeightMax = max(tlWeight,tlWeightMax);
if (tlWeight < 0.01*tlWeightMax) break;
iL++;
if (iL > lMax) break;
}
float xran = ran->Rndm();
if(sumTl<=0.) {
return 0.;
}
SStoreSubIter selectedChannel = std::lower_bound(storeSub.begin(),
storeSub.end(),
xran*sumTl,
CompareGammaToX<SStoreSub, float>());
EvapL = selectedChannel->L;
return sumTl;
}
//**************************************************************************
/**
* Selects the angle and velocity of an evaporated product
*/
void CNucleus::angleEvap()
{
//chooses the angles of evaporated particles
// find orientation of residue spin vector with respect to s0
// vector (i.e. z axis parallel to s0)
CAngle residueCM;
if (EvapLPlusS > 0.0 && fJ > 0.0)
residueCM.theta = acos((pow(fJ,2) + pow(EvapLPlusS,2)
- pow(EvapS2,2))/(2.0*EvapLPlusS*fJ));
else if (EvapLPlusS == 0) residueCM.theta = 0;
else residueCM.theta = acos(1.-2.*ran->Rndm());
residueCM.phi = 2.*pi*ran->Rndm();
// rotate to lab frame
daughterHeavy->spin = CAngle::transform(residueCM,spin);
// find direction of emitted fragment
// first the orientation of the vector l_plus_s with respect to s0
// (i.e. z axis parallel to s0)
CAngle lPlusSCM;
if (EvapS2 > 0.0 && fJ > 0.0)
lPlusSCM.theta = acos((pow(fJ,2) + pow(EvapS2,2) - pow(EvapLPlusS,2))
/(2.0*EvapS2*fJ));
if (EvapS2 == 0) lPlusSCM.theta = 0.;
else lPlusSCM.theta = acos(1.0-2.0*ran->Rndm());
lPlusSCM.phi = pi + residueCM.phi;
if (lPlusSCM.phi > 2.*pi) lPlusSCM.phi -= 2.*pi;
//rotate to lab frame
CAngle lPlusSLab = CAngle::transform(lPlusSCM,spin);
//angle of L vector - orbital angular momentum
CAngle LLLab;
if (EvapS1 > 0.0)
{
// find orientation of L vector with respect to l_plus_s vector
// (i.e. z axis parallel to l_plus_s)
CAngle LL;
if (EvapLPlusS > 0.0 && EvapL > 0.0)
LL.theta = acos((pow(EvapLPlusS,2) + pow((float)EvapL,2) - pow(EvapS1,2))
/(2.0*EvapLPlusS*(float)EvapL));
else LL.theta = acos(1.-2.*ran->Rndm());
LL.phi = 2.*pi*ran->Rndm();
// rotate to lab frame
LLLab = CAngle::transform(LL,lPlusSLab);
// orientation of s1 vector with respect to l_plus_s
// (i.e. z axis parallel to l_plus_s)
CAngle SS;
if (EvapLPlusS > 0.0 && EvapL > 0)
SS.theta = acos((pow(EvapLPlusS,2) + pow((float)EvapL,2) -
pow((float)EvapS1,2))/(2.0*EvapLPlusS*(float)EvapL));
else if (EvapL == 0) SS.theta = 0.;
else SS.theta = acos(1.-2.*ran->Rndm());
SS.phi = LL.phi+pi;
if (SS.phi > 2.*pi) SS.phi -= 2.*pi;
// rotate to lab frame
daughterLight->spin = CAngle::transform(SS,lPlusSLab);
}
else // spin zero particle
{
LLLab.theta = lPlusSLab.theta;
LLLab.phi = lPlusSLab.phi;
CAngle S1Lab(0.,0.);
daughterLight->spin = S1Lab;
}
// emission vector is perpendicular to l vector for classical mechanics
// a good approximation can be obtained if theta
// is chosen from the legendre distribution sqaured for m=l
CAngle emitL;
emitL.theta = angleDist.getTheta(EvapL);
emitL.phi = 2.*pi*ran->Rndm();
// rotate into the lab frame
CAngle emitLab= CAngle::transform(emitL,spin);
if (EvapEk < 0.0)
{
cout << "EvapEk < 0" << " " << EvapEk << " " << iZ << " " << iA
<< " " << fEx << " " << fJ << " " << daughterLight->iZ << " "
<< daughterLight->iA << " " << daughterLight->fEx << " " <<
daughterLight->fJ << " " << daughterHeavy->iZ << " " <<
daughterHeavy->iA << " " << daughterHeavy->fEx << " " <<
daughterHeavy->fJ << endl;
CNucleus * parent;
parent = getParent();
if(parent) {
cout << parent->iZ << " " << parent->iA << " " << parent->fEx << " " << parent->fJ << endl;
parent = parent->getParent();
if(parent)
cout << parent->iZ << " " << parent->iA << " " << parent->fEx << " " << parent->fJ << endl;
}
abort();
}
// get velocities
float vrel = sqrt(2.0*EvapEk*(float)(EvapA1+EvapA2)/
(float)(EvapA1*EvapA2))*0.9794;
float v1 = (float)EvapA2/(float)(EvapA2+EvapA1)*vrel;
daughterLight->velocity[0] = v1*sin(emitLab.theta)*cos(emitLab.phi);
daughterLight->velocity[1] = v1*sin(emitLab.theta)*sin(emitLab.phi);
daughterLight->velocity[2] = v1*cos(emitLab.theta);
float v2 = vrel - v1;
emitLab.theta = pi - emitLab.theta;
emitLab.phi += pi;
if (emitLab.phi > 2.*pi) emitLab.phi -= 2.*pi;
daughterHeavy->velocity[0] = v2*sin(emitLab.theta)*cos(emitLab.phi);
daughterHeavy->velocity[1] = v2*sin(emitLab.theta)*sin(emitLab.phi);
daughterHeavy->velocity[2] = v2*cos(emitLab.theta);
for (int i=0;i<3;i++)
{
daughterLight->velocity[i] += velocity[i];
daughterHeavy->velocity[i] += velocity[i];
}
}
//*********************************************************
/**
* selects the velocity of evaporated particles, the emission angles
* is assumed isotropic
*/
void CNucleus::angleIsotropic()
{
//chooses angles and velocities of evaporated particles from isotropic
//distribution - used with Weiskopf formalism
float theta = acos(1.-2.*ran->Rndm());
float phi = 2.*pi*ran->Rndm();
float vrel = sqrt(2.0*EvapEk*(float)(EvapA1+EvapA2)/
(float)(EvapA1*EvapA2))*0.9794;
float v1 = (float)EvapA2/(float)(EvapA2+EvapA1)*vrel;
daughterLight->velocity[0] = v1*sin(theta)*cos(phi);
daughterLight->velocity[1] = v1*sin(theta)*sin(phi);
daughterLight->velocity[2] = v1*cos(theta);
float v2 = vrel - v1;
theta = pi - theta;
phi += pi;
if (phi > 2.*pi) phi -= 2.*pi;
daughterHeavy->velocity[0] = v2*sin(theta)*cos(phi);
daughterHeavy->velocity[1] = v2*sin(theta)*sin(phi);
daughterHeavy->velocity[2] = v2*cos(theta);
for (int i=0;i<3;i++)
{
daughterLight->velocity[i] += velocity[i];
daughterHeavy->velocity[i] += velocity[i];
}
}
//*********************************************************
/**
* used to check momentum conservation
*
* prints out the center-of-mass velocity of all decay products
*/
void CNucleus::vCMofAllProducts()
{
float momTot[3] = {0.,0.,0.};
for (unsigned int i=0;i<stableProducts.size();i++)
{
for (int j=0;j<3;j++)
momTot[j] += stableProducts[i]->velocity[j]*(float)stableProducts[i]->iA;
}
float vcm[3];
for (int j=0;j<3;j++) vcm[j] = momTot[j]/(float)iA;
cout << "Vcm= " << vcm[0] << " " << vcm[1] << " " << vcm[2] << endl;
}
//************************************************************************
/**
* Returns the total gamma-ray decay width in MeV
*
* Contributions from E1's and E2's only
*/
float CNucleus::gammaWidth()
{
float widthTot = 0;
float width[3];
float Ex[3];
float S0[3];
for (int iMode =1;iMode<=2;iMode++)
{
if (iMode == 1) width[iMode]=gammaWidthE1GDR();
else width[iMode] = gammaWidthMultipole(iMode);
Ex[iMode] = GammaEx;
S0[iMode] = GammaJ;
widthTot += width[iMode];
}
if (widthTot <= 0.) return 0.;
int iMode;
if (ran->Rndm() < width[1]/widthTot)iMode = 1 ;
else iMode = 2;
GammaEx = Ex[iMode];
GammaJ = S0[iMode];
GammaL = iMode;
return widthTot;
}
//**************************************************************
/**
* Returns the gamma-ray decay width in MeV for a specified multipole.
* The width is from Blatt and Weisskopf, "Theoretical Nuclear Physics"
* (Wiley, New York, 1958) Page=649 scaled by the factors gammaInhibition[]
* Values of the latter are taken from Phys. Rev. C39, 516 (1989).
\param iMode 1 is E1, 2 is E2
*/
float CNucleus::gammaWidthMultipole(int iMode)
{
//iMode =1 is E1 and Imode=2 is E2
//width given in units of MeV
SStoreEvapVector storeEvap;
float deltaE = 1;
if (fEx-Erot <= 15.0) deltaE = 0.2;
float exponent = (float)(2.*iMode)/3.;
float constant = pow((float)(iA),exponent)*wue[iMode]*pi*2.0;
constant *= gammaInhibition[iMode];
float S0 = fJ;
float S0Min = fabs(S0-(float)iMode);
float S0Max = S0 + (float)iMode;
S0 = S0Min;
float sumGammaMax = 0.0;
float width = 0.;
for (;;) //loop over S0 nucleus spin
{
float Erotation = yrast->getYrast(iZ,iA,S0);
float U2Max = fEx - Erotation;
if (U2Max < 0.01) break;
float e = 0.1;
float sumGamma = 0.0;
float gammaMax = 0.0;
for (;;) //loop over excitation energy
{
float U2 = U2Max - e;
if (U2 < 0.01) break;
float logLevelDensityDaughter =
levelDensity->getLogLevelDensitySpherical
(iA,U2,fPairing,fShell,S0,fMInertia);
if (logLevelDensityDaughter == 0) break;
float gamma = pow(e,2*iMode+1)*constant*deltaE*
exp(logLevelDensityDaughter-logLevelDensity)/2./pi;
SStoreEvap aStoreEvap;
aStoreEvap.gamma = gamma;
aStoreEvap.spin = (int)S0;
aStoreEvap.energy = e;
gammaMax = max(gamma,gammaMax);
sumGamma += gamma;
if (!storeEvap.empty()) aStoreEvap.gamma += storeEvap.back().gamma;
storeEvap.push_back(aStoreEvap);
if (gamma < 0.01*gammaMax) break;
e+=deltaE;
}
sumGammaMax = max(sumGamma,sumGammaMax);
if (sumGamma < 0.01*sumGammaMax) break;
width += sumGamma;
S0++;
if (S0 > S0Max) break;
}
if (storeEvap.empty() || width <= 0.)
{
return 0.;
}
float xran = ran->Rndm();
SStoreEvapIter selectedChannel = std::lower_bound(storeEvap.begin(),
storeEvap.end(),
xran*width,
CompareGammaToX<SStoreEvap, float>());
//choose gamma energy and excitation energy of residual
float e; // gamma ray energy
GammaEx = -1.;
int iTry = 0;
for (;;)
{
e = selectedChannel->energy + deltaE*(0.5*ran->Rndm());
GammaEx = fEx - e;
if (e > 0. && GammaEx > 0.) break;
iTry++;
if (iTry > 10)
{
e = selectedChannel->energy;
GammaEx = fEx - e;
break;
}
}
GammaJ = selectedChannel->spin;
if (iA%2 == 1) GammaJ += 0.5;
return width;
}
//*****************************************************************
/**
* Returns the gamma-ray decay width in MeV for statistical E1
* taking into acount GDR strength function
* see see <NAME> et al. Phys Rev. C36 (1987) 1886
*/
float CNucleus::gammaWidthE1GDR()
{
//gives the statistical E1 gamma width in units of MeV
SStoreEvapVector storeEvap;
float deltaE = 1;
if (fEx-Erot <= 15.0) deltaE = 0.2;
float Fe1 = 0.0;
float gammaGDR = 0.0;
float gamma = 0.0;
//EGDR from systematics
float EGDR = 77.0/pow((float)iA,(float)(1./3.));
if(GDRParam == false)
{
//giant dipole strength function
//see <NAME> et al. Phys Rev. C36 (1987) 1886
//for details
gammaGDR = 4.8+0.0026*pow(fEx-Erot,(float)1.6);
Fe1 = 2.09e-5*(float)iZ*(float)(iA-iZ)/(float)(iA)*gammaGDR;
}
else // giant dipole strenght function, parametrized up to 5 lorentzian
{
Fe1 = 2.09e-5*(float)iZ*(float)(iA-iZ)/(float)(iA);
}
float S0 = fJ;
float S0Min = fabs(S0-1.);
float S0Max = S0 + 1.;
S0 = S0Min;
float sumGammaMax = 0.0;
float width = 0.;
for (;;) //loop over S0 nucleus spin
{
float Erotation = yrast->getYrast(iZ,iA,S0);
float U2Max = fEx - Erotation;
if (U2Max < 0.01) break;
float e = 0.1;
float sumGamma = 0.0;
float gammaMax = 0.0;
for (;;) //loop over excitation energy
{
float U2 = U2Max - e;
if (U2 < 0.01) break;
float logLevelDensityDaughter =
levelDensity->getLogLevelDensitySpherical
(iA,U2,fPairing,fShell,S0,fMInertia);
if (logLevelDensityDaughter == 0) break;
if (GDRParam == false)
{
gamma = Fe1*pow(e,4)/
(pow(pow(e,2)-pow(EGDR,2),2)+pow(gammaGDR*e,2))
*deltaE*exp(logLevelDensityDaughter-logLevelDensity)/2./pi;
}
else
{
gamma = Fe1*GDR->getLineShape(e)*deltaE*
exp(logLevelDensityDaughter-logLevelDensity)/2./pi;
}
SStoreEvap aStoreEvap;
aStoreEvap.gamma = gamma;
aStoreEvap.spin = (int)S0;
aStoreEvap.energy = e;
gammaMax = max(gamma,gammaMax);
sumGamma += gamma;
if (!storeEvap.empty()) aStoreEvap.gamma += storeEvap.back().gamma;
storeEvap.push_back(aStoreEvap);
if (gamma < 0.01*gammaMax) break;
e+=deltaE;
}
sumGammaMax = max(sumGamma,sumGammaMax);
if (sumGamma < 0.01*sumGammaMax) break;
width += sumGamma;
S0++;
if (S0 > S0Max) break;
}
if (storeEvap.empty() || width <= 0.)
{
return 0.;
}
float xran = ran->Rndm();
SStoreEvapIter selectedChannel = std::lower_bound(storeEvap.begin(),
storeEvap.end(),
xran*width,
CompareGammaToX<SStoreEvap, float>());
float e = selectedChannel->energy;
e += deltaE*(0.5*ran->Rndm());
if (e < 0.) e=0.;
GammaEx = fEx - e;
GammaJ = selectedChannel->spin;
if (iA%2 == 1) GammaJ += 0.5;
return width;
}
//*****************************************************************
/**
* Selects the angle and sin axis of a daughter product after gamma
* emission
*/
void CNucleus::angleGamma()
{
for (int i=0;i<3;i++) daughterHeavy->velocity[i] = velocity[i];
// find orientation of residue spin vector with respect to s0
// vector (i.e. z axis parallel to s0)
CAngle residueCM;
if (GammaL > 0 && fJ > 0.0)
residueCM.theta = acos((pow(fJ,2) + pow((float)GammaL,2)
- pow(GammaJ,2))/(2.0*(float)GammaL*fJ));
else if (GammaL == 0) residueCM.theta = 0;
else residueCM.theta = acos(1.-2.*ran->Rndm());
residueCM.phi = 2.*pi*ran->Rndm();
// rotate to lab frame
daughterHeavy->spin = CAngle::transform(residueCM,spin);
}
//*******************************************************************
/**
* Return the theta angle of the fragments in radians
*/
float CNucleus::getTheta()
{
float V = 0.;
for (int i=0;i<3;i++) V += pow(velocity[i],2);
return acos(velocity[2]/sqrt(V));
}
//*******************************************************************
/**
* Returns the theta and phi angle of the fragments in radians
*/
CAngle CNucleus::getAngle()
{
float V = 0.;
for (int i=0;i<3;i++) V += pow(velocity[i],2);
float theta;
float phi;
if (V > 0.)
{
theta = acos(velocity[2]/sqrt(V));
phi = atan2(velocity[1],velocity[0]);
}
else
{
theta = 0.0;
phi = 0.0;
}
return CAngle(theta,phi);
}
//*******************************************************************
/**
* Return the theta angle of the fragments in degrees
*/
float CNucleus::getThetaDegrees()
{
//get the theta angle of a fragments in degrees
return getTheta()*180./pi;
}
//************************************************
/**
* returns the theta and phi angles in degrees
*/
CAngle CNucleus::getAngleDegrees()
{
CAngle angle = getAngle();
angle.theta *= 180./pi;
angle.phi *= 180./pi;
return angle;
}
//*****************************************
/**
* Calculated the evaporation decay width of a channel in MeV using
* the Weisskopf formulism
\param saddle bool true=saddleToScission decay false=normal evaporation
*/
float CNucleus::weiskopf( bool saddle)
{
//calculates the evaporation decay width with the Weiskopf formalism
lightP->width = 0.;
lightP->storeEvap.clear();
if (exp(-lightP->fEx/temp) < 0.01) return 0.;
lightP->residue.iZ = iZ - lightP->iZ;
if (lightP->iZ >= lightP->residue.iZ) return 0.;
lightP->residue.iA = iA - lightP->iA;
if (lightP->iA >= lightP->residue.iA) return 0.;
if (lightP->residue.iZ >= lightP->residue.iA) return 0.;
//products must lie on the chart of nuclides used by gemini
if (lightP->residue.iA < mass->chart->getAmin(lightP->residue.iZ)) return 0.;
if (lightP->residue.iA > mass->chart->getAmax(lightP->residue.iZ)) return 0.;
rResidue = r0*pow((float)lightP->residue.iA,(float)(1./3.));
lightP->fMInertia = 0.4*(float)lightP->residue.iA*pow(rResidue,2);
lightP->fMInertiaOrbit = (float)(lightP->residue.iA*lightP->iA)/
(float)(lightP->residue.iA+lightP->iA)*pow(rResidue+lightP->rLight+2.,2);
if (saddle)
{
if (fissionMassScission)scission.init(lightP->residue.iZ,lightP->residue.iA,fJ,2);
else
{
float Z1 = (float)fissionZ/(float)fissioningZ*(float)lightP->residue.iZ;
float A1 = (float)fissionA/(float)fissioningA*(float)lightP->residue.iA;
scission.init(lightP->residue.iZ,lightP->residue.iA,fJ,2,Z1,A1);
}
}
//odd A nuclei have 1/2 integer spin
lightP->odd =0;
if (lightP->residue.iA%2 == 1) lightP->odd = 1;
if (lightP->residue.iZ > Zshell)
lightP->fPair = mass->getPairing(lightP->residue.iZ,lightP->residue.iA);
else lightP->fPair = 0.;
lightP->residue.fExpMass = mass->getExpMass(lightP->residue.iZ,lightP->residue.iA);
lightP->fShell = 0.;
if (lightP->residue.iZ > Zshell) lightP->fShell = mass->getShellCorrection(lightP->residue.iZ,lightP->residue.iA);
lightP->separationEnergy = lightP->residue.fExpMass + lightP->fExpMass - fExpMass;
float Edef = 0.;
if (saddle)
{
Edef = scission.getScissionEnergy();
Edef -= lightP->residue.fExpMass;
}
else Edef = yrast->getYrast(iZ,iA,fJ);
float maxGamma = 0.;
float constant = (2.*lightP->fJ+1.)*de/(2.*pi);
if (!saddle) constant *= (2*fJ+1.);
//prepare transmission coeff
float Ecoul;
if (Isig)
{
lightP->sigBarDist->prepare((float)lightP->residue.iZ,(float)lightP->residue.iA);
Ecoul = lightP->sigBarDist->getBarrier();
}
else
{
lightP->sigBarDist->prepare((float)lightP->residue.iZ,(float)lightP->residue.iA);
Ecoul = lightP->sigBarDist->getBarrier();
lightP->tlArray->prepare(lightP->residue.iZ);
}
float fEk = Ecoul;
bool up = 1;
for (;;)
{
float U = fEx - lightP->separationEnergy - fEk - Edef;
if (U <= 0.) break;
float logLevelDensity2 = 0.;
if (saddle) logLevelDensity2 =
levelDensity->getLogLevelDensityScission(iA,U);
else logLevelDensity2 = levelDensity->getLogLevelDensitySpherical
(lightP->residue.iA,U,lightP->fPair,lightP->fShell,-fJ,lightP->fMInertia);
if (logLevelDensity2 == 0.) break;
float temp = levelDensity->getTemp();
float sigmaInverse;
if (Isig) sigmaInverse = lightP->sigBarDist->getInverseXsec(fEk,temp);
else sigmaInverse =
lightP->tlArray->getInverseXsec(fEk,temp);
float gamma = sigmaInverse*exp(logLevelDensity2-logLevelDensity)
*constant;
lightP->width += gamma;
SStoreEvap aStoreEvap;
aStoreEvap.gamma = gamma;
if (lightP->storeEvap.size() > 0) aStoreEvap.gamma += lightP->storeEvap.back().gamma;
aStoreEvap.energy = fEk;
aStoreEvap.L = 0;
lightP->storeEvap.push_back(aStoreEvap);
maxGamma = max(maxGamma,gamma);
if (gamma < maxGamma*EkFraction)
{
if (up)
{
up = 0;
fEk = Ecoul - de;
if (fEk <= 0.) break;
else continue;
}
else break;
}
if (up) fEk += de;
else
{
fEk -= de;
if (fEk <- 0.) break;
}
}
// float del = 0.;
//if (lightP->residue.iA%2 == 1)del = 0.5;
return lightP->width;
}
//*****************************************
/**
* Calculates the decay width for evaporation at the scission point using
* the Weiskopf formalism
*
* The width is given in units of MeV
*/
float CNucleus::evaporationWidthSS()
{
float width = 0.;
EcostMin = 1000.;
bool isaddle = 1;
for (int i=0;i<evap->nLight;i++)
{
lightP = evap->lightP[i];
evap->prob[i] = weiskopf(isaddle);
width += evap->prob[i];
if (i > 0) evap->prob[i] += evap->prob[i-1];
}
if (width <= 0.) return 0.;
//if decay possible choose channel
float xran = ran->Rndm();
int i = 0;
for (;;)
{
float prob = evap->prob[i]/width;
if (prob >= xran) break;
if ( i == evap->nLight-1) break;
i++;
}
lightP = evap->lightP[i];
EvapZ1 = lightP->iZ;
EvapA1 = lightP->iA;
EvapZ2 = iZ - EvapZ1;
EvapA2 = iA - EvapA1;
EvapMode = i;
EvapEx1 = lightP->fEx;
EvapS1 = lightP->fJ;
getSpin(bool(1));
return width;
}
//*****************************************
/**
* Initializes the compound nucleus excitation and spin.
\param fEx0 is the compound nucleus excitation energy in MeV
\param fJ0 is the compound nucleus spin in hbar
*/
void CNucleus::setCompoundNucleus(float fEx0, float fJ0)
{
//initialize as a compound nucleus ready for decay
excite(fEx0,fJ0);
origin = 0;
origin2 = 0;
timeSinceStart = 0.;
sumGammaEnergy = 0.;
nGammaRays = 0;
iPoint = -1;
runningWeight = 1.;
iWeight = 0;
bResidue = true;
bSymmetricFission = false;
bAsymmetricFission = false;
}
//*****************************************
/**
* Initializes the compound nucleus excitation and spin.
\param dEx0 is the compound nucleus excitation energy in MeV
\param fJ0 is the compound nucleus spin in hbar
*/
void CNucleus::setCompoundNucleus(double dEx0, float fJ0)
{
setCompoundNucleus((float)dEx0,fJ0);
}
//********************************************
/**
* Initializes the compound nucleus excitation and spin.
\param fEx0 is the compound nucleus excitation energy in MeV
\param dJ0 is the compound nucleus spin in hbar
*/
void CNucleus::setCompoundNucleus(float fEx0, double dJ0)
{
setCompoundNucleus(fEx0,(float)dJ0);
}
//**********************************************
/**
* Initializes the compound nucleus excitation and spin.
\param dEx0 is the compound nucleus excitation energy in MeV
\param dJ0 is the compound nucleus spin in hbar
*/
void CNucleus::setCompoundNucleus(double dEx0, double dJ0)
{
setCompoundNucleus((float)dEx0,(float)dJ0);
}
//*************************************************
/**
* Returns a pointer to a stable decay product.
*
* if no input given, the first or next product is pointed to.
/param i is the index of the product (0-getNumberOfProducts-1)
*/
CNucleus * CNucleus::getProducts(int i/*=-1*/)
{
//returns pointer to array of stable products
if (i >= 0) iPoint = i;
else iPoint++;
return (iPoint<stableProducts.size()) ? stableProducts.at(iPoint) : NULL;
}
//*************************************************
/**
* Returns a pointer to the parent nucleus,
* i.e. the nucleus which emitted this product.
* This is useful to see if there was secondary decay.
* If the NULL pointer is returned, then the
* initial compound nucleus did not decay presumably
* because there was not enough excitation energy.
* Obveriously in this case the final product is the same
* as the initial nucleus and there is no parent.
*
*/
CNucleus * CNucleus::getParent()
{
return parent;
}
//*****************************************
/**
*Returns a pointer to the heavy daughter nucleus.
*If NULL is returned, then this fragment was stable
*/
CNucleus * CNucleus::getHeavyDaughter()
{
return daughterHeavy;
}
//*****************************************
/**
* Returns a pointer to the light daughter nucleus.
* If NULL is returned, then this fragment was stable
* or a fission event stated, in which case the
* heavy daughter pointer will not be NULL
*/
CNucleus * CNucleus::getLightDaughter()
{
return daughterLight;
}
//**************************************************
/**
* Returns the number of stable decay products produced in the
*the statistical decay
*/
int CNucleus::getNumberOfProducts()
{
return stableProducts.size();
}
//**************************************************************
/**
* Causes the nucleus to undergo statistical decay
*/
void CNucleus::decay()
{
unsigned int iProductsOld = allProducts.size();
unsigned int iStableOld = stableProducts.size();
int tries = 0;
for (;;)
{
recursiveDecay();
if (abortEvent == 0) break;
//cout << "aborted event, try again" << endl;
// valid event could not be generated
// set arrays points back to NULL and try again
abortEvent = 0;
if (allProducts.size() > iProductsOld)
{
while(allProducts.size()>iProductsOld) {
delete allProducts.back();
allProducts.pop_back();
};
}
if (stableProducts.size() > iStableOld)
stableProducts.resize(iStableOld);
daughterLight = NULL;
daughterHeavy = NULL;
tries++;
if (tries > 3)
{
cout << "given up trying to decay this nucleus" << endl;
cout << " Z = " << iZ << " A= " << iA << " Ex = " << fEx <<
" J= " << fJ << endl;
abortEvent = 1;
return;
}
}
multPostLight = 0;
multPostHeavy = 0;
multSaddleToScission = 0;
multPreSaddle = 0;
for (unsigned int i=0;i<stableProducts.size();i++)
{
if (stableProducts.at(i)->iZ == 0 && stableProducts.at(i)->iA == 1)
{
if (stableProducts.at(i)->origin2 == 2) multPostLight++;
if (stableProducts.at(i)->origin2 == 3) multPostHeavy++;
if (stableProducts.at(i)->origin2 == 1) multSaddleToScission++;
if (stableProducts.at(i)->origin2 == 0) multPreSaddle++;
}
}
}
//************************************************************
bool CNucleus::isSymmetricFission()
/**
* Returns a true value if a symmetric fission occurred
* Only use this function for the compound nucleus object, otherwise
* the output is garbage.
*/
{
return bSymmetricFission;
}
//**********************************************
bool CNucleus::isAsymmetricFission()
/**
* Returns a true value if an asymmetyric fission occurred
* Only use this function for the compound nucleus object, otherwise
* the output is garbage.
*/
{
return bAsymmetricFission;
}
//**************************************************************
/**
* Returns a true value if the event doesn't fission and has an
* evaporation residue.
* Only use this function for the compound nucleus object, otherwise
* the output is garbage.
*/
bool CNucleus::isResidue()
{
return bResidue;
}
//*****************************************************************
/**
* returns a true value if the fragment does not undergo
* statistical decay, for example a particular excited state of
* a nucleus. These nuclei are produced in evaporation processes.
*/
bool CNucleus::isNotStatistical()
{
return notStatistical;
}
//****************************************************************
/**
* returns true if the nucleus is undergoing a saddle to scission
* transition. All symmetric fission events, pass thought this
* stage and some emit light particles during this stage.
*/
bool CNucleus::isSaddleToScission()
{
return saddleToSciss;
}
//****************************************************************
int CNucleus::getMultPost()
/**
* Returns the number of neutrons emitted from both fission fragments
*/
{
return multPostLight + multPostHeavy;
}
//****************************************************************
int CNucleus::getMultPre()
/**
* Returns the number of neutrons emitted before the scission point
*/
{
return multPreSaddle + multSaddleToScission;
}
//***************************************************************
int CNucleus::getMultPostLight()
/**
* returns the multiplicity of neutrons emitted from the lighter
* fission fragment.
*/
{
return multPostLight;
}
//*****************************************************************
int CNucleus::getMultPostHeavy()
/**
* returns the multiplicity of neutrons emitted from the heavier
* fission fragment.
*/
{
return multPostHeavy;
}
//****************************************************************
/**
* Returns the multiplicity of neutrons emitted before the saddle-point
*/
int CNucleus::getMultPreSaddle()
{
return multPreSaddle;
}
//************************************************************
/**
* Returns the multiplicity of neutrons emitted between saddle
* and scission
*/
int CNucleus::getMultSaddleToScission()
{
return multSaddleToScission;
}
//************************************************************
/**
* used to check for conservation of energy.
*
* this is a debugging tool. Prints out the various contributions
* to the final energy and the energy difference between inital and final
* states. The latter should be zero is energy is conserved.
*/
void CNucleus::energyConservation()
{
float sumKE = 0.;
float sumMass = 0.;
float sumEx = 0.;
for (unsigned int i=0;i<stableProducts.size();i++)
{
sumKE += stableProducts.at(i)->getKE();
sumMass += stableProducts.at(i)->getExcessMass();
sumEx += stableProducts.at(i)->fEx;
}
float Qvalue = fExpMass - sumMass;
cout << sumKE << " " << Qvalue << " " << sumEx << " " <<
sumKE-Qvalue+sumEx+sumGammaEnergy
<< " " << fEx - sumKE + Qvalue - sumEx - sumGammaEnergy<< endl;
}
//**********************************************************
float CNucleus::getKE()
/**
* Returns the fragments kinetic energy in MeV.
*/
{
float KE = 0.;
for (int i=0;i<3;i++) KE += pow(velocity[i]/.9784,2);
KE *= 0.5*(float)iA;
return KE;
}
//**********************************************************
/**
* Returns the magnitude of the fragment's velocity in cm/ns
*/
float CNucleus::getVelocity()
{
float vel = 0.;
for (int i=0;i<3;i++) vel += pow(velocity[i],2);
vel = sqrt(vel);
return vel;
}
//**********************************************************
/**
* Returns the magnitude of the fragment's momentum in MeV/c
*/
float CNucleus::getMomentum()
{
return getVelocity()*(float)iA/30.*931.5016;
}
//********************************************************
/**
* Determines the angles and velocities of the daughter fragments
* when the decay was determined by the transition-state formulism
*/
void CNucleus::split(CAngle symmetryCM)
{
//angles and velocity of fragments after binary decay (not evaporation)
float A1 = (float)fissionA;
float A2 = (float)(iA-fissionA);
float Ared = A1*A2/(A1+A2);
//float Ek = yrast->viola((float)fissionZ,A1,
// (float)(iZ-fissionZ),A2);
float Ek = scission.ekTot;
float Vrel = sqrt(2.0*Ek/Ared)*0.9794;
float V1CM = A2/(A1+A2)*Vrel;
float V2CM = Vrel-V1CM;
// in the c-o-m frame the velocity vectors are
daughterLight->velocity[0] = V1CM*sin(symmetryCM.theta)
*cos(symmetryCM.phi);
daughterLight->velocity[1] = V1CM*sin(symmetryCM.theta)
*sin(symmetryCM.phi);
daughterLight->velocity[2] = V1CM*cos(symmetryCM.theta);
// fragment 2 get emitted 180 degrees away.
symmetryCM.theta = pi - symmetryCM.theta;
symmetryCM.phi += pi;
if (symmetryCM.phi > 2.*pi) symmetryCM.phi -= 2.*pi;
daughterHeavy->velocity[0] = V2CM*sin(symmetryCM.theta)
*cos(symmetryCM.phi);
daughterHeavy->velocity[1] = V2CM*sin(symmetryCM.theta)
*sin(symmetryCM.phi);
daughterHeavy->velocity[2] = V2CM*cos(symmetryCM.theta);
for (int i=0;i<3;i++)
{
daughterLight->velocity[i] += velocity[i];
daughterHeavy->velocity[i] += velocity[i];
}
return;
}
//**********************************************************
/**
* can be used to initialize another compound nucleus
\param iZ0 is the proton number
\param iA0 is the mass number
\param fEx0 is the excitation energy in MeV
\param fJ0 is the spin in hbar
*/
void CNucleus::setNewIsotope(int iZ0, int iA0, float fEx0, float fJ0)
{
init(iZ0,iA0);
setCompoundNucleus(fEx0,fJ0);
}
//*******************************************************
/**
* sets the transient time (fission delay) in zs different from the default
* value. This is a static function.
*/
void CNucleus::setTimeTransient(float time)
{
timeTransient = time;
}
//*******************************************************
/**
* returns the transient time (fission delay) in zs different from the default
* value. This is a static function.
*/
float CNucleus::getTimeTransient()
{
return timeTransient;
}
//**************************************************************
/**
* returns a pointer to the array containing the velocity vector.
* units are in cm/ns
*/
float* CNucleus::getVelocityVector()
{
return velocity;
}
//**************************************************************
/**
* returns a pointer to the arrays containing the momentum vector.
* units are in MeV/c
*/
float* CNucleus::getMomentumVector()
{
for (int i=0;i<3;i++) momentum[i] = velocity[i]*(float)iA/30.*931.5016;
return momentum;
}
//****************************************************
/**
* sets the fission scale factor
\param factor is the scale factor
*/
void CNucleus::setFissionScaleFactor(float factor)
{
fissionScaleFactor = factor;
}
//***********************************************
/**
* returns the fission scale factor
*/
float CNucleus::getFissionScaleFactor()
{
return fissionScaleFactor;
}
//**************************************************
/**
* set the parameter controlling the width of the barrier distribution
\param width - width is \f$ \sqrt(T)* width \f$
*/
void CNucleus::setBarWidth(float width)
{
CTlBarDist::setBarWidth(width);
CSigBarDist::setBarWidth(width);
}
//***************************************************
/**
* returns the paramter controlling the width of the barrier dist
*/
float CNucleus::getBarWidth()
{
return CTlBarDist::getBarWidth();
}
//****************************************************
/**
* set the width of the energy bins for integating the Hauser-Feshbach
*formulism
\param de0 with of the energy bin
*/
void CNucleus::setDeltaE(float de0)
{
de = de0;
}
//*******************************************************
/**
* returns the energy bin width used for integrating the Hauser-Feshbach
* formulism
*/
float CNucleus::getDeltaE()
{
return de;
}
//********************************************************
/**
* sets the threshold used to cut out low probability evaporation
* channels. All channels will be included if set to zero.
\param threshold0 is the threshold
*/
void CNucleus::setThreshold(float threshold0)
{
threshold = threshold0;
}
//*******************************************************
/**
* returns the threshold used to cut out low probability evaporation
* channels
*/
float CNucleus::getThreshold()
{
return threshold;
}
//***********************************************************
/**
* the symmetric fission barrier is modified by adding this quantity
\param barAdd0 barrier adjestment in MeV
*/
void CNucleus::setAddToFisBarrier(float barAdd0)
{
barAdd = barAdd0;
}
//***********************************************************
/**
* returns the quantity by which the symmerty fission is added to.
*/
float CNucleus::getAddToFisBarrier()
{
return barAdd;
}
//************************************************************
/**
* prints out the values of the statistical model parameters
*/
void CNucleus::printParameters()
{
CLevelDensity::printParameters();
CTlBarDist::printParameters();
CYrast::printParameters();
cout << "barAdd = " << barAdd << endl;
cout << "fissionScaleFactor = " << fissionScaleFactor << endl;
if (fissionMassScission)cout << " viscosity= " << viscosity_scission << endl;
else cout << " viscosity= " << viscosity_saddle << endl;
cout << " fission delay = " << timeTransient <<" e-21 s" << endl;
if (noIMF) cout << " IMF emissions turned off" << endl;
else cout << " IMF turned on" << endl;
if (fissionMassScission)
cout << " fission mass dist determined at scission" << endl;
else cout << " fission mass dist determined at saddle" << endl;
if (BohrWheeler) cout << " Bohr-Wheeler decay width" << endl;
else cout << " Lestone Decay width" << endl;
if (barAdd != 0.) cout << barAdd << " added to barriers" << endl;
// cout << "WignerAdd= " << WignerAdd << " WignerScaler= " << WignerScaled << endl;
cout << "WignerAdd= " << WignerAdd << endl;
if (iHF == 1) cout << "<NAME> for evaporation" << endl;
else if (iHF ==0)
{
cout << "Weisskopf for evaporation with" << endl;
if (Isig) cout << " parameterized inverse xsections" << endl;
else cout <<
" inverse xsection from sum of parameterized transmission coef" << endl;
}
else if (iHF ==2)
{
cout << "switches from HF to Weisskopf with" << endl;
if (Isig) cout << " parameterized inverse xsections" << endl;
else cout <<
" inverse xsection from sum of parameterized transmission coef" << endl;
}
if (GDRParam)
{
cout << "using user-defined GDR line shape from sum of up to 5 Lorentzians" << endl;
}
else cout <<"standard GDR line shape" << endl;
}
//************************************************************
/**
* Gives a correction to either the Bohr-Wheeler or Morreto formalism
* when the tilting angular momentum bearing mode is considered.
* See J. Lestone PRC 59 (1999) 1540
* the saddle-point shape is assumed constant as a function of K,
* the projection of the spin on the symmetry axis.
\param Usaddle is saddle point excitation energy in Mev
\param momInertiaEff is the effective moment of inertia for tilting
\param iAfAn switch to allow af/an value.
*/
float CNucleus::LestoneCorrection( float Usaddle, float momInertiaEff,
short iAfAn)
{
float saddleLD = levelDensity->getLogLevelDensitySpherical
(iA,Usaddle,(float)0.,(float)0.,fJ,fMInertia,iAfAn);
float saddleTemp = levelDensity->getTemp();
float K = fJ - roundf(fJ);
float tot = 0.;
for (;;)
{
if (K > fJ) break;
if (K < 0.1) tot = 1.;
else
{
float ErotK = kRotate/2.*pow(K,2)/momInertiaEff;
float U = Usaddle - ErotK;
if (U <= 0.) break;
float LD = levelDensity->
getLogLevelDensitySpherical(iA,U,(float)0.,(float)0.,
fJ,fMInertia,iAfAn);
float yield = exp(LD-saddleLD)*2.*levelDensity->getTemp()/saddleTemp;
if (yield < 1.e-3) break;
tot += yield;
}
K++;
}
return tot/(2.*fJ+1.);
}
//************************************************************************
/**
* returns a pointer to the Compound nucleus
*/
CNucleus* CNucleus::getCompoundNucleus()
{
CNucleus * parent = this;
for(;;)
{
CNucleus * parentNew = parent->getParent();
if (parentNew == NULL) break;
parent = parentNew;
}
return parent;
}
//***********************************************************
/**
* Hauser-Feshbach routine to sum of the spin of the residual nucleus
\param Ekvalue if < 0, then loop over Ek, other for the specificed Ekvalue
*/
float CNucleus::S2Loop(float Ekvalue)
{
lightP->storeEvap.clear();
S2 = S2Start;
float width0 = S2Width(Ekvalue);
S2 += 1.;
float width1 = S2Width(Ekvalue);
float width = width0 + width1;
if (width <= 0.) return 0.;
float sign = 1.;
if (width1 < width0) sign = -1.;
float gammaMax = max(width0,width1);
//increase or decrease S2
if (sign > 0.) S2++;
else S2 = S2Start - 1;
for (;;)
{
if (S2 < 0.) break;
float gamma = S2Width(Ekvalue);
gammaMax = max(gammaMax,gamma);
width += gamma;
if (gamma <= EkFraction*gammaMax) break;
S2 += sign;
}
//now go the other direction
if (sign < 0.) S2 = S2Start + 2;
else S2 = S2Start - 1;
sign *= -1.;
for (;;)
{
if (S2 < 0.) break;
float gamma = S2Width(Ekvalue);
gammaMax = max(gammaMax,gamma);
width += gamma;
if (gamma <= EkFraction*gammaMax) break;
S2 += sign;
}
return width;
}
//********************************************************************
/**
* calculates the Hauser-Feshbach decay width for a single S2 values,
* but integrated over l and ek
\param Ekvalue if < 0, then loop over Ek, other for the specificed Ekvalue
*/
float CNucleus::S2Width(float Ekvalue)
{
// consider particle"s spin in determining
// the l (orbital angular momentum limits)
lPlusSMin = fabs(fJ-S2); //minimum value of (l+s) vector
lPlusSMax = fJ + S2; //maximum value of (l+s) vector
lMax = (int)round(lPlusSMax+lightP->fJ); //maximum value of l vector
if (lMax > lMaxQuantum) lMax = lMaxQuantum;
lMin = (int)round(lPlusSMin-lightP->fJ); // minimum value of l
if (lMin < 0) lMin = (int)round(lightP->fJ-lPlusSMax);
if (lMin < 0) lMin = 0;
EYrast2 = yrast->getYrast(lightP->residue.iZ,lightP->residue.iA,S2);
UMin = fEx - lightP->separationEnergy - EYrast2;
if (UMin < 0) return 0;
if (Ekvalue < 0)return EkLoop();
else return EkWidth(Ekvalue);
}
//********************************************************************
/**
* Calculates the Hauser-Feshbach decay width for a single S2 and ek,
* but integrated over l
*/
float CNucleus::EkWidth(float ek)
{
float U2 = UMin-ek;
float daughterLD = levelDensity->
getLogLevelDensitySpherical(lightP->residue.iA,U2,lightP->fPair,lightP->fShell
,S2,lightP->fMInertia);
if (daughterLD == 0 ) return 0.;
float temp = levelDensity->getTemp();
float sumTl = getSumTl(ek,temp);
if (sumTl == 0) return 0.;
float gamma = de*sumTl*exp(daughterLD-logLevelDensity)/2./pi;
if (gamma <= 0.) return 0.;
SStoreEvap aStoreEvap;
aStoreEvap.gamma = gamma;
aStoreEvap.spin = (int)S2;
aStoreEvap.energy = ek;
aStoreEvap.L = EvapL;
if (lightP->storeEvap.size() > 0) aStoreEvap.gamma += lightP->storeEvap.back().gamma;
lightP->storeEvap.push_back(aStoreEvap);
/*
if (lightP->iA == 1 && lightP->iZ == 1)
{
cout << fEx - lightP->separationEnergy - ek << " " << S2 << " " << gamma <<
" " << daughterLD << " " << sumTl << " " << ek << endl;
}
*/
return gamma;
}
//******************************************
/**
*Hauser-Feshbach function to sum over kinetic energy for a given S2
*/
float CNucleus::EkLoop()
{
//find energy at which tl=0.5 approximately
float ekMin = (float)((lMin+1)*lMin)*20.454/
lightP->fMInertiaOrbit + Ecoul;
if( ekMin > UMin) ekMin = UMin;
//start just below the barrier
ekMin *= 0.8;
ekMin = round(ekMin+de/2.0) - de/2.0;
if (ekMin < de/2.) ekMin = de/2.;
float ek = ekMin;
float width0 = EkWidth(ek);
ek += de;
float width1 = EkWidth(ek);
float width = width0 + width1;
if (width <= 0.) return 0.;
float sign = 1.;
if (width1 < width0) sign = -1.;
float gammaMax = max(width0,width1);
//increase or decrease S2
if (sign > 0.) ek+= de;
else ek = ekMin - de;
for (;;)
{
if (ek < 0.) break;
float gamma = EkWidth(ek);
gammaMax = max(gammaMax,gamma);
width += gamma;
if (gamma <= EkFraction*gammaMax) break;
ek += sign*de;
}
//now go the other direction
if (sign < 0.) ek = ekMin + 2.*de;
else ek = ekMin - de;
sign *= -1.;
for (;;)
{
if (ek < 0.) break;
float gamma = EkWidth(ek);
gammaMax = max(gammaMax,gamma);
width += gamma;
if (gamma <= EkFraction*gammaMax) break;
ek += sign*de;
}
return width;
}
//****************************************************
/**
* Turns off imf emissions. The default option is
* IMF emsiion on.
*/
void CNucleus::setNoIMF()
{
noIMF = 1;
}
//****************************************************
/**
* Turns on imf emissions. This is the default option.
*/
void CNucleus::setYesIMF()
{
noIMF = 0;
}
//****************************************************
/**
* Calculations use Lestone fission width.
* the default is the BohrWheeler decay width
*/
void CNucleus::setLestone()
{
BohrWheeler = 0;
}
//****************************************************
/**
* Calculations use BohrWheeler fission width
* This is the default. Alternative is setLestone()
*/
void CNucleus::setBohrWheeler()
{
BohrWheeler = 1;
}
//********************************************
/**
* Set one of the parameter sets
\param isol solution number
*/
void CNucleus::setSolution(int isol)
{
if (isol == 0)
{
setBohrWheeler();
setTimeTransient(0.);
CLevelDensity::setAfAn(1.036);
CLevelDensity::setLittleA(7.3,.00517,.0345,12.);
CTlBarDist::setBarWidth(1.);
}
else if (isol == 1)
{
setLestone();
setTimeTransient(1.);
CLevelDensity::setAfAn(1.057);
CLevelDensity::setLittleA(7.3,.00517,.0345,12.);
CTlBarDist::setBarWidth(1.);
}
else
{
cout << "this solution not defined" << endl;
}
}
//***********************************************
/**
* returns the total energy removed by gamma rays in MeV
*/
float CNucleus::getSumGammaEnergy()
{
return sumGammaEnergy;
}
//***********************************************
/**
* returns gamma ray energy in MeV
*/
float CNucleus::getGammaRayEnergy(int number)
{
return GammaRayEnergy[number];
}
//***********************************************
/**
* returns number of emitted gamma rays
*/
int CNucleus::getnGammaRays()
{
return nGammaRays;
}
//*************************************************
/**
* returns the time in zs at which the particle was created after
* the formation of the CN
*/
float CNucleus::getTime()
{
return timeSinceStart;
}
//*****************************************************************
/**
* determined the spin of the residue (for Weisskopf)
\param saddle bool true=saddleToScission decay false=normal evaporation
*/
void CNucleus::getSpin(bool saddle)
{
if (HF && !saddle)
{
//choose the residue spin and evaporated particles energy;
float xran = 1.5;
while(floor(xran) > 0.5)xran = ran->Rndm();
SStoreEvapIter selectedChannel = std::lower_bound(lightP->storeEvap.begin(),
lightP->storeEvap.end(),
xran*lightP->width,
CompareGammaToX<SStoreEvap, float>());
float Ek,Ex;
int iTry = 0;
for (;;)
{
Ek = selectedChannel->energy + (1.-2.*ran->Rndm())*de/2.;
const float S2MinRes = (lightP->residue.iA%2==0 ? 0.0 : 0.5);
const float EYrastRes = yrast->getYrast(lightP->residue.iZ,lightP->residue.iA,S2MinRes);
Ex = fEx - lightP->separationEnergy - Ek;
if ( Ek >= 0. && Ex >= EYrastRes) break;
if (iTry ==4)
{
if(Ek>0.) { // all goes into kinetic energy -- assume maximum L and minimum S2
EvapEk = fEx - lightP->separationEnergy - EYrastRes;
if(EvapEk<0.) {
cout << "EvapEk < 0 in corner case for evaporation, resetting it to 0." << endl
<< "iZ=" << iZ << " iA=" << iA << " fEx=" << fEx << " fJ=" << fJ << endl
<< "lightP->iZ=" << lightP->iZ << " lightP->iA=" << lightP->iA << " separation energy=" << lightP->separationEnergy << endl
<< "EYrastRes=" << EYrastRes << " EvapEk=" << EvapEk << endl;
EvapEk = 0.;
}
EvapEx2 = EYrastRes;
EvapS2 = S2MinRes;
lPlusSMax = fJ + S2MinRes; //maximum value of (l+s) vector
lMax = (int)round(lPlusSMax+lightP->fJ); //maximum value of l vector
if (lMax > lMaxQuantum) lMax = lMaxQuantum;
EvapL = lMax;
} else { // all goes into excitation energy -- assume L=0 and S2=fJ-lightP->fJ
EvapEk = 0.;
EvapEx2 = fEx - lightP->separationEnergy;
if(EvapEx2<0.) {
cout << "EvapEx2 < 0 in corner case for evaporation, resetting it to 0." << endl
<< "iZ=" << iZ << " iA=" << iA << " fEx=" << fEx << " fJ=" << fJ << endl
<< "lightP->iZ=" << lightP->iZ << " lightP->iA=" << lightP->iA << " separation energy=" << lightP->separationEnergy << endl
<< "EYrastRes=" << EYrastRes << " EvapEx2=" << EvapEx2 << endl;
EvapEx2 = 0.;
}
EvapL = 0;
EvapS2 = fabs(fJ - lightP->fJ);
}
return;
}
iTry++;
}
EvapEx2 = Ex;
EvapS2 = selectedChannel->spin;
if (lightP->odd) EvapS2 += 0.5;
EvapEk = Ek;
EvapL = selectedChannel->L;
return;
}
//now for HF == 0
//choose the residue spin and evaporated particles energy;
float xran = ran->Rndm();
SStoreEvapIter selectedChannel = std::lower_bound(lightP->storeEvap.begin(),
lightP->storeEvap.end(),
xran*lightP->width,
CompareGammaToX<SStoreEvap, float>());
float Ek,Ex;
int iTry = 0;
for (;;)
{
Ek = selectedChannel->energy + (1.-2.*ran->Rndm())*de/2.;
const float S2MinRes = (lightP->residue.iA%2==0 ? 0.0 : 0.5);
const float EYrastRes = yrast->getYrast(lightP->residue.iZ,lightP->residue.iA,S2MinRes);
Ex = fEx - lightP->separationEnergy - Ek;
//for saddle-point, excitation energy can be less than zero,
//as we are evaporing from the scission point which can be below
//the ground state
if (!saddle && Ek >= 0. && Ex >= EYrastRes) break;
if (saddle) break;
if (iTry ==4)
{
if(Ek>0.) { // all goes into kinetic energy -- assume maximum L and minimum S2
EvapEk = fEx - lightP->separationEnergy - EYrastRes;
if(EvapEk<0.) {
cout << "EvapEk < 0 in corner case for evaporation, resetting it to 0." << endl
<< "iZ=" << iZ << " iA=" << iA << " fEx=" << fEx << " fJ=" << fJ << endl
<< "lightP->iZ=" << lightP->iZ << " lightP->iA=" << lightP->iA << " separation energy=" << lightP->separationEnergy << endl
<< "EYrastRes=" << EYrastRes << " EvapEk=" << EvapEk << endl;
EvapEk = 0.;
}
EvapEx2 = EYrastRes;
EvapS2 = S2MinRes;
lPlusSMax = fJ + S2MinRes; //maximum value of (l+s) vector
lMax = (int)round(lPlusSMax+lightP->fJ); //maximum value of l vector
if (lMax > lMaxQuantum) lMax = lMaxQuantum;
EvapL = lMax;
} else { // all goes into excitation energy -- assume L=0 and S2=fJ-lightP->fJ
EvapEk = 0.;
EvapEx2 = fEx - lightP->separationEnergy;
if(EvapEx2<0.) {
cout << "EvapEx2 < 0 in corner case for evaporation, resetting it to 0." << endl
<< "iZ=" << iZ << " iA=" << iA << " fEx=" << fEx << " fJ=" << fJ << endl
<< "lightP->iZ=" << lightP->iZ << " lightP->iA=" << lightP->iA << " separation energy=" << lightP->separationEnergy << endl
<< "EYrastRes=" << EYrastRes << " EvapEx2=" << EvapEx2 << endl;
EvapEx2 = 0.;
}
EvapL = 0;
EvapS2 = fabs(fJ - lightP->fJ);
}
return;
}
iTry++;
}
EvapEx2 = Ex;
EvapEk = Ek;
if (saddle)
{
EvapS2 = fJ - lightP->fJ;
EvapL = 0;
}
else
{
lightP->storeEvap.clear();
S2Start = roundf(lightP->fMInertia/
(lightP->fMInertia+lightP->fMInertiaOrbit)*fJ);
if (lightP->odd) S2Start += 0.5;
//prepare transmission coeff
lightP->tlArray->prepare(lightP->residue.iZ);
float width = S2Loop(Ek);
if(width<=0.) {
// problematic corner case, it probably means that shell and pairing
// corrections made the thermal excitation energy negative
// in this case just set L=0 and S2=|fJ-EvapS1|
EvapL = 0;
EvapS2 = fabs(fJ-EvapS1);
return;
}
//choose the residue spin and evaporated particles energy;
float xran = 1.5;
while(floor(xran) > 0.5)xran = ran->Rndm();
SStoreEvapIter selectedChannel = std::lower_bound(lightP->storeEvap.begin(),
lightP->storeEvap.end(),
xran*width,
CompareGammaToX<SStoreEvap, float>());
EvapS2 = selectedChannel->spin;
if (lightP->odd) EvapS2 += 0.5;
EvapL = selectedChannel->L;
}
}
//********************************************
/**
* Sets the mode use for evaporation
* 1 = Hauser-Feshach formalism as in the original GEMINI
* 0 = widths calculated from Weisskopf, then kinetic energy
* of particle also from Weisskopf, but spin and orbital
* angular momentum from Hauser-Feshbach
* 2 = Switches bewteen options 0 and 1 dependeing of the ratio of
* rotational to thermal energy. (default)
*
\param iHF0 =0,1,2
*/
void CNucleus::setEvapMode(int iHF0/*=2*/)
{
iHF = iHF0;
}
//*****************************************************
/**
* returns the max Z for evaporation
*/
int CNucleus::getZmaxEvap()
{
return evap->maxZ;
}
//****************************************************
/**
* returns the saddle-crossing time in zs for symmetric fission.
* In addition, the scission time is stored in timeScission.
* If no symmetric fission occurs, then -1 is returned.
* If more than one symmetric fission, then the time of the first
* is returned. the fusction decay() must be run before using this function
\param timeScission scission time in zs (outpot)
*/
float CNucleus::getFissionTimeSymmetric(float & timeScission)
{
float timeFission = -1.;
timeScission = -1.;
if (!isSymmetricFission()) return timeFission;
CNucleus * prod = daughterHeavy;
int i = 0;
for (;;)
{
if (prod == NULL) return 0.; // no fission found
if (prod->origin == 1 && timeFission == -1.)
timeFission = prod->timeSinceStart;
if (prod->origin > 1 && timeScission == -1.)
{
timeScission = prod->timeSinceStart;
break;
}
prod = prod->daughterHeavy;
i++;
if (i == 100) break; // just in case provide an exit to the "for" loop
}
return timeFission;
}
//**************************************************************
/**
* returns the time in zs when an asymmetric fission occured
* in the decay. Must be called only after decay() is called.
* If not asymmetric fission, then returns -1., if more than one
* asymmetric fission, the is returns the time of the first
*/
float CNucleus::getFissionTimeAsymmetric()
{
float timeFission = -1.;
if (!isAsymmetricFission()) return timeFission;
CNucleus * prod = daughterHeavy;
int i = 0;
for (;;)
{
if (prod == NULL) return 0.; // no fission found
if (prod->origin > 1 && prod->origin2 == 0 &&timeFission == -1.)
{
timeFission = prod->timeSinceStart;
break;
}
prod = prod->daughterHeavy;
i++;
if (i == 100) break; // just in case provide an exit to the "for" loop
}
return timeFission;
}
//*************************************************************
//*********************************************************
/**
* returns the evaporation plu gamma decay width in MeV
* Can easily be changed to give the toal decay with by
* also adding the symmetric and asymmetric fission
*/
float CNucleus::getDecayWidth()
{
float widthEvaporation = evaporationWidth();
float widthGamma = gammaWidth();
float sum = widthEvaporation + widthGamma;
return sum;
}
//******************************************************
/**
* returns the natural log of the level density in MeV-1
*/
float CNucleus::getLogLevelDensity()
{
return logLevelDensity;
}
//********************************************
/**
* Sets the GDR mode for gamma-ray width calculations
* for true, a uder-defined GDR line shape consisting of
* the sum of 5 Lorentzians is used.
* for false (this is the defalut)
* a single Lorentztian based on systematics is used.
\param mode =true or false
*/
void CNucleus::setUserGDR(bool mode/*=true*/)
{
GDRParam = mode;
}
<file_sep>#include "CNucleus.h"
#include "TFile.h"
#include "TH1F.h"
#include "TH2F.h"
/**
*!\brief example of fusion with root histograms
*
* class that I use to simulate statistical decay in fusion
* reactions where there is a thick target.
* It produces a number of histograms, such a mass, charge
* and evaporation spectra - The output is stored in root file
*/
class CRunThick
{
public:
CRunThick(int iZ, int iA, float fEx_min,float fEx_max, float l0_min,
float l0_Max,float d0, int lmax, float plb,int nBins,
int numTot,string title0,float vcm=0.,float thetaDetMin=0.,
float thetaDetMax = 360.);
};
<file_sep>#ifndef potpara_
#define potpara_
#include <cmath>
//**********************************************************************
//give potential as a function of r
class CPotPara
{
public:
CPotPara(){};
CPotPara(double,double,double);
void init(double,double,double); //initialization
CPotPara copy();
double woodSaxon (double);
double derWoodSaxon (double);
double gauss (double); // alternative form for surface potential
void print();
double V;
double R;
double a;
};
#endif
<file_sep>#include "CRun.h"
#include "CFus.h"
int main()
{
int numTot = 8000; //spectra
float const d0=4.; //diffuseness of CN spin distribution
string title0("fusion"); //name of output root file without extension
float Elab = 9.17*12.; // bombarding energy of projectile in the lab frame
//define projectile
int iZp = 6;
int iAp = 12;
//define target
int iZt = 28;
int iAt = 58;
//use the Bass model to find critical angular momentum
CFus fus(iZp,iAp,iZt,iAt,Elab,d0);
float l0 = fus.getBassL();
cout << "Elab= " << Elab << " l0= " << l0
<< " plb = " << fus.plb << " mb " << endl;
cout << "iZ= " << fus.iZcn << " iAcn= " << fus.iAcn
<< " Ex= " << fus.Ex << endl;
//run gemini
CRun run(fus.iZcn,fus.iAcn,fus.Ex,l0,
d0,(int)(l0+4.*d0),fus.plb,numTot,title0);
}
<file_sep>#include "CScatter.h"
#include "CAvrigeanu.h"
class CAlphaOM
{
private:
//CAlpha alpha;
CAvrigeanu alpha;
CScatter scatter;
double sl[200]; //!< reaction cross section for each ell value
double prob[200]; //!< cumulative probability for ell value
double xsec; //!< total reaction cross section
int lmax; //!< maximum ell wave considered
public:
CAlphaOM(double iZtar, double Atar, double Elab);
double getSigL(int l);
double getXsec();
int getLmax();
int getL(double random);
};
<file_sep>#ifndef yrast_
#define yrast_
#include <iostream>
#include <fstream>
#include "CMass.h"
using namespace std;
/**
*!\brief fission barriers, rotational energies, etc
*
* Class to return barriers and rotational energies. It is constructed
* from bits of code such as <NAME> - which gives his Finite-range
*fission barrier, rotational energies, moments of inertia, surface areas.
* Also I have used code from the RLDM model. In addition I enclude a
* interpolation of conditional fission barriers, using barriers calculated
* by Sierk
*/
class CYrast
{
private:
CYrast();
static CYrast *fInstance; //!< instance member to make this class a singleton
static double const pi; //!< 3.14159
//needed by getYrastRLDM
static float const x1h[11][6]; //!< number for RLDM
static float const x2h[11][6]; //!< numbers for RLDM
static float const x3h[20][10]; //!< number for RLDM
static float const x1b[11][6]; //!<numbers for RLDM
static float const x2b[11][6]; //!<numbers for RLDM
static float const x3b[20][10]; //!<numbers for RLDM
//needed by Sierk functions
static double const emncof[4][5]; //!< used in Sierk functions
static double const elmcof[4][5]; //!<used in Sierk functions
static double const emxcof[5][7];//!<used in Sierk functions
static double const elzcof[7][7];//!<used in Sierk functions
static double const egscof[5][7][5];//!<used in Sierk functions
static double const aizroc[5][6];//!<used in Sierk functions
static double const ai70c[5][6];//!<used in Sierk functions
static double const ai95c[5][6];//!<used in Sierk functions
static double const aimaxc[5][6];//!<used in Sierk functions
static double const ai952c[5][6];//!<used in Sierk functions
static double const aimax2c[5][6];//!<used in Sierk functions
static double const aimax3c[4][4];//!<used in Sierk functions
static double const aimax4c[4][4];//!<used in Sierk functions
static double const bizroc[4][6];//!<used in Sierk functions
static double const bi70c[4][6];//!<used in Sierk functions
static double const bi95c[4][6];//!<used in Sierk functions
static double const bimaxc[4][6];//!<used in Sierk functions
static double const b[8][5][5];//!<used in Sierk functions
void lpoly(double,int,double*);
double A; //!< mass number
double Z; //!< proton number
double zz; //!< used in Sierk functions
double amin; //!< lower limits of application of Sierk routine
double amax; //!< upper limits of application of Sierk routine
double pa[7]; //!<used in Sierk routines
double pz[7]; //!<used in Sierk routines
//needed by saddlefit
float c[6][8][2][11][2]; //!< coeff for sadfits
float cubic(float,float,float,float,float,float);
static bool first; //!< only write out barrier warning once
int Narray; //!< number of elements in array of asymmetric barriers
static float const hbarc; //!< used for asymmetric barriers
static float const alfinv;//!< used for asymmetric barriers
static float const srznw;//!< used for asymmetric barriers
static float const aknw;//!< used for asymmetric barriers
static float const bb;//!< used for asymmetric barriers
static float const um;//!< used for asymmetric barriers
static float const elm;//!< used for asymmetric barriers
static float const spdlt;//!< used for asymmetric barriers
static float const asnw;//!< used for asymmetric barriers
static float const kx[8];//!< used for asymmetric barriers
static float const ky[6];//!< used for asymmetric barriers
static float const ka[11];//!< used for asymmetric barriers
static float const r0; //!< radius parameter
static float const sep; //!<separation id fm between fragments
static bool bForceSierk; //!<separation id fm between fragments
static double addBar; //!<extrapolated Sierk barrier increase by this amount
float sadArray[300]; //!< array stores the conditional saddle energies
float sadArrayZA[300]; //!< array stores saddle energies after correction
CMass * mass; //!< class for mass defects
static float const deltaJ; //!< used to extend sierk barrier to higher J
static float const kRotate; //!< constant for rotional energy
int iZ; //!< proton number
int iA; //!<mass number
float fJ; //!< spin
public:
static CYrast *instance(); //!< instance member to make this class a singleton
double Jmax; //!< max spin where the fission barrier exists
float getYrast(int,int,float);
float getYrastModel(int,int,float);
float getYrastRLDM(int,int,float);
float getYrastSierk(float);
float getJmaxSierk(int,int);
float getBarrierFissionSierk(float);
float getSymmetricSaddleEnergy(int,int,float);
float getBarrierFissionRLDM(int,int,float);
float getBsSierk(float);
static void forceSierk(bool=1);
static void printParameters();
void prepareAsyBarrier(int, int, float);
void printAsyBarrier();
float getSaddlePointEnergy(int,int);
float getSaddlePointEnergy(float);
float getMomentOfInertiaSierk(float);
float WignerEnergy(int iZ, int iA);
float momInertiaMin; //!< minimum saddle-point moment of inertia
float momInertiaMid; //!< intermediate saddle-point moment of inertia
float momInertiaMax; //!< maximum saddle-point moment of inertia
// float sumPair;
//float sumShell;
//float viola(float,float,float,float);
};
#endif
<file_sep>#include "CRunThick.h"
/**
* this constructor is everything at the moment.
/param iZcn - CN proton number
/param iAcn is the mass number
/param fEx is the excitation energy in MeV
/param l0 is the critical spin , specifying the max spin in fusion (unit hbar)
/param d0 is the diffuseness of the spin distribution (units hbar)
/param lmax is the maximum spin value considered. (<l0 for just er info)
/param plb is pi-lambda-bar squared in mb
/param numTot is number of Monte Carlo simulations
/param title0 is name of output root file (without ".root" extension)
*/
CRunThick::CRunThick(int iZcn, int iAcn, float fEx_min,float fEx_max,float l0_min,
float l0_max, float d0, int lmax, float plb,int nBins,
int numTot,string title0,float vcm/*=0.*/, float thetaDetMin/*=0.*/,
float thetaDetMax/*=360*/)
{
cout << title0 << endl;
string title = title0 + ".root";
bool residue;
bool residueDet;
float ExArray[nBins];
for (int i=0;i<nBins;i++) ExArray[i] = fEx_min + (fEx_max-fEx_min)/
((float) nBins)*((float)i+0.5);
float prob[nBins][lmax+1];
for (int i=0;i<nBins;i++)
{
float l0 = l0_min + (l0_max-l0_min)/((float)nBins)*((float)i+0.5);
float sum = 0.;
for (int l=0;l<=lmax;l++)
{
prob[i][l] = (float)(2*l+1);
if (d0 > 0.) prob[i][l] /= (1.+exp(((float)l-l0)/d0));
else if ( l > l0) prob[i][l] = 0.;
sum += prob[i][l];
}
for (int l=0;l<=lmax;l++)
{
prob[i][l] /= sum;
if (l > 0) prob[i][l] += prob[i][l-1];
}
}
float sum = 0.;
for (int l=0;l<=lmax;l++)
{
float fact = (float)(2*l+1);
if (d0 > 0.) fact /= (1.+exp(((float)l-(l0_min+l0_max)/2.)/d0));
else if ( l > (l0_min+l0_max)/2.) fact = 0.;
sum += fact;
}
TFile *f = new TFile(title.c_str(),"RECREATE");
CNucleus CN(iZcn,iAcn);
//CNucleus::setSolution(1);
//CNucleus::setFissionScaleFactor(7.38);
//CNucleus::setAddToFisBarrier(-1.);
//CNucleus::setNoIMF();
// CNucleus::setAddToFisBarrier(4.);
//CNucleus::setLestone();
//CLevelDensity::setAfAn(1.036);
//CLevelDensity::setAimfAn(1.05);
//CNucleus::setTimeTransient(1.);
//CTlBarDist::setBarWidth(1.);
//CTlBarDist::setBarWidth(0.);
//CYrast::forceSierk();
CN.setVelocityCartesian((float)0.,(float)0.,(float)0.);
CAngle spin((float)0.,(float)0.);
CN.setSpinAxis(spin);
CN.printParameters();
float asy[20]={0.};
float asyMultPre[20] = {0.};
float asyMultPost[20] = {0.};
float asyMultTot[20] = {0.};
float Nres = 0.;
float NresDet = 0.;
float sumAres = 0.;
float sumAresDet = 0.;
float Nfiss = 0.;
float NfissLost = 0.;
float LfissLost = 0.;
float NpreSad = 0.;
float NpreScis = 0.;
float Npost = 0.;
float Nalpha = 0.;
float Nproton = 0.;
float Nneutron = 0.;
float NLi6 = 0.;
float NLi7 = 0.;
float NBe7 = 0.;
float Mfis = 0;
float M2fis = 0.;
float M0fis = 0.;
double numberA = 0;
double averageA = 0;
TH1F histEgamma("Egamma","",100,0,50);
histEgamma.GetXaxis()->SetTitle("E_{#gamma} [MeV]");
histEgamma.GetYaxis()->SetTitle("#sigma(E_{#gamma}) [mb]");
histEgamma.SetTitle("distribution of total gamma energy for all events");
TH1F histER("histER","",91,-0.5,90.5);
histER.GetXaxis()->SetTitle("J_{CN} [hbar]");
histER.GetYaxis()->SetTitle("#sigma(J) [mb]");
histER.SetTitle("spin distribution of events that form residues");
TH1F histERxn("histERxn","",91,-0.5,90.5);
histERxn.GetXaxis()->SetTitle("J_{CN} [hbar]");
histERxn.GetYaxis()->SetTitle("#sigma(J) [mb]");
histERxn.SetTitle("spin distribution of residue that decay by neutrons only");
TH1F histFis("histFis","",91,-0.5,90.5);
histFis.GetXaxis()->SetTitle("J_{CN} [hbar]");
histFis.GetYaxis()->SetTitle("#sigma(J) [mb]");
histFis.SetTitle("spin distribution of events that fission");
TH1F histFus("histFus","",91,-0.5,90.5);
histFus.GetXaxis()->SetTitle("J [hbar]");
histFus.GetYaxis()->SetTitle("#sigma(J) [mb]");
histFus.SetTitle("spin distribution of all fusion events");
TH1F histA("histA","",231,-0.5,230.5);
histA.GetXaxis()->SetTitle("A");
histA.GetYaxis()->SetTitle("#sigma(A) [mb]");
histA.SetTitle(" inclusive mass distribution");
TH2F histAA("histAA","",200,0,200,200,0,200);
TH1F histAFis("histAFis","",231,-0.5,230.5);
TH1F histAFisPrimary("histAFisPrimary","",231,-0.5,230.5);
TH1F histAFisPrimaryVel("histAFisPrimaryVel","",231,-0.5,230.5);
TH1F histZ("histZ","",93,-0.5,92.5);
histZ.GetXaxis()->SetTitle("Z");
histZ.GetYaxis()->SetTitle("#sigma(Z) [mb]");
histZ.SetTitle(" inclusive charge distribution");
TH1F histZ_fis("histZ_fis","",93,-0.5,92.5);
histZ_fis.GetXaxis()->SetTitle("Z");
histZ_fis.GetYaxis()->SetTitle("#sigma(Z) [mb]");
histZ_fis.SetTitle("charge distribution for fission events");
TH1F histZ_nofis("histZ_nofis","",93,-0.5,92.5);
TH1F histN("histN","",133,-0.5,132.5);
histN.GetXaxis()->SetTitle("N");
histN.GetYaxis()->SetTitle("#sigma(N) [mb]");
histN.SetTitle(" inclusive neutron-number distribution");
TH1F angle("angle","",180,0,180);
TH2F histZN("histZN","",152,-0.5,151.5,152,-0.5,151.5);
TH1F keFF("keFF","",150,0,150);
TH1F kePreSad("kePreSad","",100,0,30);
TH1F kePreSS("keSS","",100,0,30);
TH1F kePreSc("kePreSc","",100,0,30);
TH1F kePost("kePost","",100,0,30);
TH1F keEvap("keEvap","",100,0,30);
TH1F velFF("velFF","",100,0,4.);
TH1F keAlpha("keAlpha","",50,0,50);
TH1F keProton("keProton","",50,0,50);
TH1F keNeutron("keNeutron","",50,0,50);
TH1F keLi6("keLi6","",60,0,60);
TH1F keLi7("keLi7","",60,0,60);
TH1F keBe7("keBe7","",60,0,60);
TH1F histFis2("histFis2","",100,0,7000);
TH2F histAL("histAL","",251,-0.5,250.5,101,-0.5,100.5);
histAL.GetXaxis()->SetTitle("A");
histAL.GetYaxis()->SetTitle("J_{CN} [hbar]");
histAL.SetTitle("inclusive mass and CN spin distribution");
TH2F histxnEx("histxnEx","",50,0,50,50,0,20);
TH2F histxnExA("histxnExA","",16,200,216,50,0,20);
bool f14=1;
bool f12=1;
bool f34=1;
for (int i=0;i<numTot;i++)
{
float weight = 1.;
//cout <<"event= " << i << endl;
if (i > numTot*.25 && f14)
{
cout << " 25%" << flush;
f14 = 0;
}
if (i > numTot*.5 && f12)
{
cout << '\xd' << " 50%" << flush;
f12 = 0;
}
if (i > numTot*.75 && f34)
{
cout << '\xd' << " 75%" << endl;
f34 = 0;
}
int mbin = nBins+1;
for (;;)
{
mbin= (int)floor(CN.ran->Rndm()*(float)nBins);
if (mbin < nBins) break;
}
float fEx = ExArray[mbin];
float ran = CN.ran->Rndm();
int l = 0;
for (;;)
{
if (ran < prob[mbin][l]) break;
l++;
}
//l = 2; //rjc
//fEx = 77.83;
/*
if (i==60) //rjc
{
cout << "here" << endl;
}
*/
CN.setCompoundNucleus(fEx,(float)l);
{
//if (i%100==0)cout << "l= "<< l << " i= " << i << endl;
CN.setWeightIMF();
CN.decay();
if (CN.abortEvent)
{
CN.reset();
continue;
}
histEgamma.Fill(CN.getSumGammaEnergy());
int iStable = CN.getNumberOfProducts();
CNucleus *productER = CN.getProducts(iStable-1);
weight *= productER->getWeightFactor();
if(productER->iZ == iZcn)
{
averageA += (double)productER->iA*(double)weight;
numberA += (double)weight;
}
int iZres = productER->iZ;
float resEx = productER->fEx;
float resJ = productER->fJ;
int iAres = productER->iA;
int multTot = 0;
int iZ, iA;
CNucleus * product = CN.getProducts(0);
histFus.Fill(l,weight);
if (CN.isResidue())
{
float * vv;
vv = productER->getVelocityVector();
vv[2] += vcm;
float vvv = sqrt(pow(vv[0],2)+pow(vv[1],2)+pow(vv[2],2));
float AngleDeg = acos(vv[2]/vvv)*180./3.14159;
if (AngleDeg > thetaDetMin && AngleDeg < thetaDetMax)
residueDet = 1;
else residueDet = 0;
residue = 1;
histER.Fill(l,weight);
if (iZres == iZcn)
{
histERxn.Fill(l,weight);
histxnEx.Fill(resJ,resEx,weight);
histxnExA.Fill(iAres,resEx,weight);
}
Nres += weight;
sumAres += weight*(float)productER->iA;
if (residueDet)
{
NresDet += weight;
sumAresDet += weight*(float)productER->iA;
}
}
else
{
residue = 0;
residueDet = 0;
Nfiss += weight;
histFis.Fill(l,weight);
histFis2.Fill(l*l,weight);
}
int iAmax = 0;
int iAnext = 0;
float vmax = 0.;
float vnext = 0.;
float emax = 0.;
float enext = 0.;
for (int j=0;j<iStable;j++)
{
iZ = product->iZ;
iA = product->iA;
//if (CN.SymmetricisFission())cout << iZ << " " << iA << endl; //rjc
if (iA > iAmax)
{
iAnext = iAmax;
vnext = vmax;
enext = emax;
iAmax = iA;
emax = product->getKE();
vmax = product->getVelocity();
}
else if (iA > iAnext)
{
iAnext = iA;
enext = product->getKE();
vnext = product->getVelocity();
}
//cout << iZ << " " << iA << endl;
if (product->getTime() < 0.)
{
cout << "negative time" << endl;
cout << iZ << " " << iA << " " <<
product->getParent()->iZ << " " <<
product->getParent()->iA << " "
<< product->getParent()->fEx << " "
<< product->getParent()->fJ << endl;
}
histZ.Fill(iZ,weight);
if (CN.isSymmetricFission())histZ_fis.Fill(iZ,weight);
else histZ_nofis.Fill(iZ,weight);
histA.Fill(iA,weight);
histAL.Fill(iA,l,weight);
histN.Fill(iA-iZ,weight);
histZN.Fill(iA-iZ,iZ,weight);
if (iZ == 0 && iA == 1)
{
if (residueDet) //iARes >= Ares)
{
keNeutron.Fill(product->getKE(),weight);
Nneutron += weight;
}
multTot++;
if (CN.isSymmetricFission())
{
if (product->origin == 0)
{
kePreSad.Fill(product->getKE(),weight);
NpreSad += weight;
}
if (product->origin == 1)
kePreSS.Fill(product->getKE(),weight);
if (product->origin <= 1)
{
NpreScis += weight;
kePreSc.Fill(product->getKE(),weight);
}
if (product->origin > 1)
{
Npost += weight;
kePost.Fill(product->getKE(),weight);
}
}
else keEvap.Fill(product->getKE(),weight);
}
else if (iZ == 1 && iA == 1 && residueDet) //iARes >= Ares)
{
keProton.Fill(product->getKE(),weight);
Nproton += weight;
}
else if (iZ == 2 && iA == 4)
{
if(residueDet) //iARes >=Ares )
{
/*
//rjc
if (product->getKE() < 15.)
{
cout << " i = " << i << endl;
cout << product->getParent()->iZ << " " <<
product->getParent()->iA << " " <<
product->getParent()->fEx << " " <<
product->getParent()->fJ << " " <<
product->getKE() << " " <<
product->getParent()->daughterHeavy->fJ << " " <<
product->getParent()->daughterHeavy->fEx << endl;
}
*/
//cout << "alpha " << product->getKE() << endl; //rjc
keAlpha.Fill(product->getKE(),weight);
Nalpha += weight;
}
}
else if (iZ == 3 && iA == 6)
{
if(residueDet) //iARes >=Ares )
{
keLi6.Fill(product->getKE(),weight);
NLi6 += weight;
}
}
else if (iZ == 3 && iA == 7)
{
if(residueDet) //iARes >=Ares )
{
keLi7.Fill(product->getKE(),weight);
NLi7 += weight;
}
}
else if (iZ == 4 && iA == 7)
{
if(residueDet) //iARes >=Ares )
{
keBe7.Fill(product->getKE(),weight);
NBe7 += weight;
}
}
if (iZ > 1 && iZ < 5)
{
angle.Fill(product->getThetaDegrees(),weight);
}
if (iZ > 5 && CN.isSymmetricFission())
{
keFF.Fill(product->getKE(),weight);
velFF.Fill(product->getVelocity(),weight);
Mfis += (float)product->iA;
M2fis += pow((float)product->iA,2);
M0fis += 1.;
histAFis.Fill(product->iA,weight);
}
product=CN.getProducts();
}
if (CN.isSymmetricFission())
{
if ((float)iAmax > 0.77*(float)CN.iA)
{
NfissLost += weight;
LfissLost += weight*CN.fJ;
}
float A2 = emax/(emax+enext)*(float)CN.iA;
float A1 = (float)CN.iA - A2;
histAFisPrimary.Fill(A1,weight);
histAFisPrimary.Fill(A2,weight);
A2 = vmax/(vmax+vnext)*(float)CN.iA;
A1 = (float)CN.iA - A2;
histAFisPrimaryVel.Fill(A1,weight);
histAFisPrimaryVel.Fill(A2,weight);
//cout << iAmax << " " << iAnext << " " << A2 << " " << A1 << endl;
histAA.Fill((float)iAnext,A2,weight);
histAA.Fill((float)iAmax,A1,weight);
}
float Amax = (float)iAmax/(float)(iAmax+iAnext)*162.;
float Anext = (float)iAnext/(float)(iAmax+iAnext)*162.;
int iasy = (int)(Amax/10);
asy[iasy] += weight;
asyMultPre[iasy] += weight*(float)CN.getMultPre();
asyMultPost[iasy] += weight*(float)CN.getMultPost();
asyMultTot[iasy] += weight*(float)multTot;
iasy = (int)(Anext/10);
asy[iasy] += weight;
asyMultPre[iasy] += weight*(float)CN.getMultPre();
asyMultPost[iasy] += weight*(float)CN.getMultPost();
asyMultTot[iasy] += weight*(float)multTot;
CN.reset();
}
}
title = title0+"M.dat";
ofstream ofFile(title.c_str());
for (int i=0;i<20;i++)
{
if (asy[i] == 0) continue;
ofFile << i*10 + 5 << " " << asyMultPre[i]/asy[i] << " " <<
asyMultPost[i]/asy[i] << " " << asyMultTot[i]/asy[i] << endl;
}
histA.Scale(plb/(float)numTot*sum);
histZ.Scale(plb/(float)numTot*sum);
histZ_fis.Scale(plb/(float)numTot*sum);
histZ_nofis.Scale(plb/(float)numTot*sum);
histN.Scale(plb/(float)numTot*sum);
histAFis.Scale(plb/(float)numTot*sum);
histAFisPrimary.Scale(plb/(float)numTot*sum);
histAFisPrimaryVel.Scale(plb/(float)numTot*sum);
histZN.Scale(plb/(float)numTot*sum);
keAlpha.Scale(1./NresDet);
keProton.Scale(1./NresDet);
keNeutron.Scale(1./NresDet);
keLi6.Scale(1./NresDet);
keLi7.Scale(1./NresDet);
keBe7.Scale(1./NresDet);
f->Write();
cout << "NresDet= " << NresDet << " Nneut= " << Nneutron << " NProt= " <<
Nproton << " Nalpha= " << Nalpha << " NLi6= " << NLi6 << " NLi7= " << NLi7
<< " NBe7= " << NBe7 << endl;
cout << "Li6 mult = " << NLi6/NresDet << endl;
cout << "Li7 mult = " << NLi7/NresDet << endl;
cout << "Be7 mult = " << NBe7/NresDet << endl;
cout << "neutron mult= " << Nneutron/NresDet << endl;
cout << "proton mult= " << Nproton/NresDet << endl;
cout << "alpha mult= " << Nalpha/NresDet << endl;
cout << " mean ER A = " << sumAres/Nres << endl;
cout << " for det res = " << sumAresDet/NresDet << endl;
float xER = Nres/(float)numTot*sum*plb;
float xFiss2 = Nfiss/(float)numTot*sum*plb;
if (NfissLost > 0) LfissLost /= NfissLost;
float xFissLost = NfissLost/(float)numTot*sum*plb;
cout << "sigmaER = " << xER << " mb " << endl;
float xFus = 0.;
for (int l=0;l<200;l++)
{
float xx = (float)(2*l+1);
if (d0 > 0.) xx /=(1.+exp(((float)l-(l0_max+l0_min)/2.)/d0));
else if (l > (l0_min+l0_max)/2.) break;
xFus += xx;
}
xFus *= plb;
float xFis = xFus - xER;
cout << "fusion xsec= " << xFus << " mb" << endl;
cout << "fission xsec= " << xFis << " mb " << xFiss2 << " "
<< xFissLost << " " << LfissLost<< endl;
if (Nfiss > 0.)
{
cout << "preSaddle neut mult = " << NpreSad/Nfiss << endl;
cout << "preScis neut mult = " << NpreScis/Nfiss << endl;
cout << "post neut mult = " << Npost/Nfiss << endl;
float Mav = Mfis/M0fis;
cout << "mean fission mass = " << Mav << endl;
float sigma2 = M2fis/(M0fis-1) - M0fis/(M0fis-1)*pow(Mav,2);
//float sigma = sqrt(sigma2);
cout << "sigma2M= " << sigma2 << endl;
}
if (numberA > 0) cout << "average x for xn products is " << (float)iAcn-
averageA/numberA << endl;
}
<file_sep>#include "CScatter.h"
double const CScatter::e2=1.44;
double const CScatter::kconstant = .048192;
CScatter::CScatter()
{
RealpotPara = new CPotPara();
ImagVpotPara = new CPotPara(); //volume imag
ImagSpotPara = new CPotPara(); //surface imag
}
//**************************************************
CScatter::CScatter(double mu0, double V0, double VE0, double R0, double a0,
double zz0, double Rc0)
{
init(mu0,V0,VE0,R0,a0,zz0,Rc0);
VEE = 0.;
}
//**********************************************************
CScatter::~CScatter()
{
delete RealpotPara;
delete ImagVpotPara;
delete ImagSpotPara;
}
//****************************************************************************
void CScatter::init(double mu0, double V0, double VE0, double R0, double a0,
double zz0, double Rc0)
{
mu = mu0;
V = V0;
VE = VE0;
R = R0;
a = a0;
zz = zz0;
Rc = Rc0;
RealpotPara->init(1.,R,a);
muhbar = kconstant*mu;
ImagVpotPara->init(0.,R,a);
ImagSpotPara->init(1.,R,a);
VEE = 0.;
}
//*************************************************************************
void CScatter::init(double mu0, double V0, double VE0, double VEE0, double R0, double a0, double zz0, double Rc0,double Wsur0, double WsurE0, double RW0, double aW0 )
{
mu = mu0;
V = V0;
VE = VE0;
VEE = VEE0;
R = R0;
a = a0;
zz = zz0;
Rc = Rc0;
Wsur = Wsur0;
WsurE = WsurE0;
Wvol = 0.;
Rsur = RW0;
asur = aW0;
RealpotPara->init(1.,R,a);
muhbar = kconstant*mu;
ImagVpotPara->init(1.,R,a);
ImagSpotPara->init(1.,Rsur,asur);
}
//****************************************************************************
void CScatter::init(double mu0, double V0, double VE0, double VEE0, double R0,
double a0, double zz0, double Rc0)
{
init(mu0,V0,VE0,R0,a0,zz0,Rc0);
VEE = VEE0;
}
//*************************************
void CScatter::init(double mu0, double V0, double VE0, double R0, double a0,
double zz0, double Rc0,double Wvol0,double Wsur0,
double Ri0, double ai0)
{
mu = mu0;
V = V0;
VE = VE0;
R = R0;
a = a0;
zz = zz0;
Rc = Rc0;
RealpotPara->init(1.,R,a);
muhbar = kconstant*mu;
Wsur = Wsur0;
Wvol = Wvol0;
Ri = Ri0;
ai = ai0;
ImagVpotPara->init(1.,Ri,ai);
ImagSpotPara->init(1.,Ri,ai);
}
//*************************************************************
double CScatter::getCoulPotential(double r)
{
if (r > Rc) return e2*zz/r;
else return e2*zz/2./Rc*(3.-pow(r/Rc,2));
}
//*************************************************************
double CScatter::getRealPotential(double r, double E)
{
double pot = getCoulPotential(r) + (V-VE*E-VEE*pow(E,2))*RealpotPara->woodSaxon(r);
if (l > 0) pot += (double)(l*(l+1))/pow(r,2)/muhbar;
return pot;
}
//*************************************************************
double CScatter::getImagPotential(double r, double E)
{
double pot = Wvol*ImagVpotPara->woodSaxon(r)
+ (Wsur-WsurE*E)*ImagSpotPara->derWoodSaxon(r);
return pot;
}
//***********************************************************
/**
* returns the Coulomb + centrifical barrier for the specified
* orbital angular momentum
\param l is the orbital angular momentum quantum number
*/
double CScatter::getBarrier(int l0)
{
l = l0;
double E = 0.;
double Uold;
double r;
for (int i=0;i<2;i++)
{
r = R + 8.;
Uold = 0.;
double U;
for (;;)
{
U = getRealPotential(r,E);
if (U <= Uold) break;
Uold = U;
r -= 0.1;
if (r <=0.) return -1.;
}
E = Uold;
if (VE == 0.) break;
}
rBarrier = r+.1;
r = rBarrier - 0.5;
double Ubelow = getRealPotential(r,E);
r = rBarrier + 0.5;
double Uabove = getRealPotential(r,E);
omega = sqrt((Uabove+Ubelow - 2.*Uold)/.25/mu)*6.466;
return Uold;
}
//************************************************************
/**
* returns the locations of the boundary continion - ie. the location
* of the minimum in the potential, if -1 returned then there is no
*minimum
\param l0 is the orbital angular momentum quantum number
*/
double CScatter::getBoundary(int l0)
{
l = l0;
double r;
double U;
double E = 0.;
//find boundary condition
if (zz == 0. && l0 == 0)
{
r = 5.;
U = getRealPotential(r,E);
}
else
{
r = R + 8.;
bool bar = 0;
double Uold = 0.;
for (;;)
{
U = getRealPotential(r,E);
if (U < Uold && bar == 0) //found barrier
{
bar = 1;
barrier = Uold;
rBarrier = r + .1;
}
else if (U > Uold && bar == 1) break; //found boundary
Uold = U;
r -= .1;
if (r <= 0.) return -1.;
}
}
Rboundary = r + .1;
return Rboundary;
}
//************************************************************
double CScatter::getWaveFunction(double energyCM, int l0)
{
scale = 0.; // set imaginary potential to zero
Ecm = energyCM;
l = l0;
Kwave2 = kconstant*mu*energyCM;
Kwave = sqrt(fabs(Kwave2));
plb = 656.80/mu/Ecm; // pi-lambda-bar squared in mb
//Sommerfield parameter
gamma = zz*e2*Kwave/energyCM/2.;
double Uboundary = getRealPotential(Rboundary,energyCM);
Rmatch = R + 5.;
// find initial and matching wave functions
//initialise wave function
double rhoStop = Rmatch*Kwave;
int lMax = max(5,l);
CWaves outWave(rhoStop,gamma,lMax);
//for (int i=0;i<lMax;i++) sigma[i] = outWave.sigma[i];
// initialize the coupled differential equation solver
initMerson(.001,.00001,.1,0);
valarray<double> WaveFunct(4);
WaveFunct[0] = 1.;
WaveFunct[1] = 0.;
if (energyCM > Uboundary)
{
WaveFunct[2] = 0.;
WaveFunct[3] = -sqrt((energyCM-Uboundary)*kconstant*mu);
}
else
{
WaveFunct[2] = sqrt((Uboundary-energyCM)*kconstant*mu);
WaveFunct[3] = 0.;
}
solveMerson(&WaveFunct,Rboundary,Rmatch);
//outWave gives derivates with respect to rho = Kwave*r
//but at this point WaveFunctOut have derivative with respect to r
// so make them with respect to rho=kwave*r
WaveFunct[1] /= Kwave;
WaveFunct[3] /= Kwave;
//cout << WaveFunct[0] << " " << WaveFunct[1] << endl;
// match wave functions
//real WaveFunct = AA*F + BB*G
double BB = outWave.dF[l]*WaveFunct[0]
- outWave.F[l]*WaveFunct[1];
double AA = -outWave.dG[l]*WaveFunct[0]
+ outWave.G[l]*WaveFunct[1];
// imaginary part => Wavefunct = CC*F + DD*G
double DD = outWave.dF[l]*WaveFunct[2]
- outWave.F[l]*WaveFunct[3];
double CC = -outWave.dG[l]*WaveFunct[2]
+ outWave.G[l]*WaveFunct[3];
double denominator = pow(AA+DD,2) + pow(CC-BB,2);
double etaReal = (pow(AA,2)-pow(DD,2) + pow(CC,2)
- pow(BB,2))/denominator;
double etaImag = 2.*(AA*BB+CC*DD)/denominator;
return 1.-pow(etaReal,2)-pow(etaImag,2);
//return 1. -(pow(BB+CC,2)+pow(AA-DD,2))/(pow(BB-CC,2)+pow(AA+DD,2));
}
//************************************************************
double CScatter::getTl_OM(double energyCM, int l0)
{
scale = 1.; // turn on imaginary potential
double rStart = .05;
Ecm = energyCM;
l = l0;
Kwave2 = kconstant*mu*energyCM;
Kwave = sqrt(fabs(Kwave2));
plb = 656.80/mu/Ecm; // pi-lambda-bar squared in mb
//Sommerfield parameter
gamma = zz*e2*Kwave/energyCM/2.;
Rmatch = R + 5.;
// find initial and matching wave functions
//initialise wave function
double rhoStop = Rmatch*Kwave;
int lMax = max(5,l);
CWaves outWave(rhoStop,gamma,lMax);
//for (int i=0;i<lMax;i++) sigma[i] = outWave.sigma[i];
// initialize the coupled differential equation solver
initMerson(.001,.00001,.1,0);
// potential at start
double Vstart = getRealPotential(rStart,Ecm);
double Wstart = getImagPotential(rStart,Ecm);
//derivative of potential at start
double dVstart = (getRealPotential(rStart+.01,Ecm) - Vstart)/0.01;
double dWstart = (getImagPotential(rStart+.01,Ecm) - Wstart)/0.01;
valarray<double> WaveFunct(4);
// initialize wavefunctions
double fact = pow(rStart,l+3)/2./(double)(2*l+3);
WaveFunct[0] = pow(rStart,l+1)
- muhbar*(energyCM-Vstart)*fact; // real part
WaveFunct[2] = Wstart*muhbar*fact; //imaginary part
// derivative of wavefunction
fact = (double)(l+3)*pow(rStart,l+2)/2./double(2*l+3);
WaveFunct[1] = (double)(l+1)*pow(rStart,l)
- muhbar*(energyCM-Vstart)*fact; // real
WaveFunct[3] = muhbar*Wstart*fact; // imaginary
fact = muhbar*pow(rStart,l+3)/2./(double)(2*l+3);
WaveFunct[1] += dVstart*fact;
WaveFunct[3] += dWstart*fact;
solveMerson(&WaveFunct,rStart,Rmatch);
//outWave gives derivates with respect to rho = Kwave*r
//but at this point WaveFunctOut have derivative with respect to r
// so make them with respect to rho=kwave*r
WaveFunct[1] /= Kwave;
WaveFunct[3] /= Kwave;
//cout << WaveFunct[0] << " " << WaveFunct[1] << endl;
// match wave functions
//real WaveFunct = AA*F + BB*G
double BB = outWave.dF[l]*WaveFunct[0]
- outWave.F[l]*WaveFunct[1];
double AA = -outWave.dG[l]*WaveFunct[0]
+ outWave.G[l]*WaveFunct[1];
// imaginary part => Wavefunct = CC*F + DD*G
double DD = outWave.dF[l]*WaveFunct[2]
- outWave.F[l]*WaveFunct[3];
double CC = -outWave.dG[l]*WaveFunct[2]
+ outWave.G[l]*WaveFunct[3];
double denominator = pow(AA+DD,2) + pow(CC-BB,2);
double etaReal = (pow(AA,2)-pow(DD,2) + pow(CC,2)
- pow(BB,2))/denominator;
double etaImag = 2.*(AA*BB+CC*DD)/denominator;
return 1.-pow(etaReal,2)-pow(etaImag,2);
//return 1. -(pow(BB+CC,2)+pow(AA-DD,2))/(pow(BB-CC,2)+pow(AA+DD,2));
}
//**************************************************************************
valarray<double> CScatter::diff(double r , valarray<double> w)
{
// REAL (kind=8) :: pot_real,pot_imag
// this subroutine is used by the mersion subroutine
// w[0] = REAL(u(r)) real part of radial wave function
//w[1] = REAL(du/dr) derrivative of real part of radial wave function
//w[2] = IMAG(u(r)) Imaginary part of radial wave function
//w[3] = IMAG(du/dr) derrivative of imaginary part
//F(1:4) are the derivaties of w(1:4)
int n = w.size();
valarray<double> f(n);
f[0] = w[1]; //these are equal by definition
double potReal = getRealPotential(r,Ecm)*muhbar;
//if ( l > 0) potReal += (double)(l*(l+1))/pow(r,2);
f[1] = -(Kwave2 - potReal)*w[0];
if (n == 4)
{
f[2] = w[3]; // equal by definition
double potImag = getImagPotential(r,Ecm)*muhbar*scale;
f[1] -= potImag*w[2];
f[3] = -(Kwave2 - potReal)*w[2] + potImag*w[0];
}
return f;
}
<file_sep>#ifndef chistory_h
#define chistory_h
#include "CNucleus.h"
#include <map>
#include <limits>
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
/**
*!\brief figures out the history of a fragment
*
* Figures out the de-excitation history of a fragment, and condenses this
* information as either a string of characters or a string of digits (i.e. an
* integer). Each character/digit represents one or more steps in the
* de-excitation process. Some of the possible processes may never be realised
* by a particular de-excitation model, but the encoding is meant to be allow
* comparisons among different de-excitation models. GEMINI++, for instance,
* will never produce fragments through process 3 ('m'), i.e.
* multifragmentation.
*
* The currently defined possible character values and their meanings are the
* following:
*
* digit char meaning
* 1 e evaporation product
* 2 E evaporation residue
* 3 m multifragmentation
* 4 a light partner in asymmetric fission or IMF emission
* 5 A heavy partner in asymmetric fission or IMF emission
* 6 f light partner in fission
* 7 F heavy partner in fission
* 8 s saddle-to-scission emission
* 9 n non-statistical emission (decay)
*
* Consecutive de-excitation steps are sometimes encoded as a single step, to
* save some space in the string. The rules are the following:
* 1. if last step == 'E' and new step == 'e', condense the two as 'e';
* 2. if last step == 'E' and new step == 'E', condense the two as 'E';
* 3. if last step == 's' and new step == 's', condense the two as 's'.
*
* Usage:
*
* CNucleus *CN = new CNucleus(iZ, iA, fEx, fJ);
* CN->decay();
* CHistory theHistoryClass(CN);
* int n = CN->GetNumberOfProducts();
* for(int i=0; i<n; ++i) {
* CNucleus *product = CN->getProducts(i);
* std::string historyString = theHistoryClass.getHistoryAsString(product);
* // or
* int32_t historyInt = theHistoryClass.getHistory(product);
* }
*/
class CHistory {
typedef std::map<CNucleus *, std::string> HistoryMap;
public:
/**
* destructor
*/
~CHistory() {};
/**
* returns the history of a fragment as an integer (a sequence of digits)
* \param p is a pointer to the fragment
*/
int32_t getHistory(CNucleus *p) {
std::string hist = getHistoryAsString(p).substr(0, maxInt32Len);
std::transform(hist.begin(),
hist.end(),
hist.begin(),
theTranslator
);
std::stringstream ss;
ss << hist;
int32_t iHist;
ss >> iHist;
return iHist;
}
/**
* returns the history of a fragment as a string (a sequence of chars)
* \param p is a pointer to the fragment
*/
std::string getHistoryAsString(CNucleus *p) {
HistoryMap::const_iterator iter = theMap.find(p);
if(iter != theMap.end())
return iter->second;
else {
std::cerr << "Unknown CNucleus pointer in HistoryMap" << std::endl;
return 0;
}
}
/**
* constructor
\param np pointer to compound nucleus
*/
CHistory(CNucleus *np) {
evap = CEvap::instance();
maxEvapZ = evap->maxZ;
theMap[np]="";
tagDaughters(np, "");
}
static const char Evaporation;
static const char EvaporationResidue;
static const char Multifragmentation;
static const char AsymmetricFissionLight;
static const char AsymmetricFissionHeavy;
static const char SymmetricFissionLight;
static const char SymmetricFissionHeavy;
static const char SaddleToScission;
static const char NonStatistical;
private:
void tagDaughters(CNucleus *n, std::string const &parentHistory);
std::string addToHistory(char steptype, std::string const &prevhist);
static class HistoryStringToDigitsTranslator {
typedef std::map<char, char> StepMap;
public:
HistoryStringToDigitsTranslator() {
theStepMap[Evaporation] = '1';
theStepMap[EvaporationResidue] = '2';
theStepMap[Multifragmentation] = '3';
theStepMap[AsymmetricFissionLight] = '4';
theStepMap[AsymmetricFissionHeavy] = '5';
theStepMap[SymmetricFissionLight] = '6';
theStepMap[SymmetricFissionHeavy] = '7';
theStepMap[SaddleToScission] = '8';
theStepMap[NonStatistical] = '9';
}
char operator()(char const c);
private:
StepMap theStepMap;
} theTranslator;
static const int maxInt32Len;
HistoryMap theMap;
int maxEvapZ; //!< maximum Z for evaporation
static CEvap *evap;
};
#endif // chistory_h
<file_sep>## Build & Install Gemini++ shared library & header files
This is a modified version of the Gemini++ source code taken from <NAME>'s
[[website|https://wustl.app.box.com/s/ehsih9oc1j41loxgl4ox/folder/6560861989]] (see `upstream` branch for version details).
The modifications concern only the way the library is built and installed:
* the original `Makefile` made a static library, but did not install it or the header files required for development;
* we build a shared library, `libGemini.so` and install it and all required files in a standard architecture:
- [path to installation]/lib/libGemini.so
- [path to installation]/include/gemini/ *all header files*
- [path to installation]/share/gemini/ *tbl/ and tl/ directories*
To build and install:
* clone this repository:
- git clone https://github.com/jdfrankland/gemini.git
* in the source directory, run `cmake` (version 2.8 or greater) giving the required installation directory:
- cmake . -DCMAKE_INSTALL_PREFIX=[path to installation]
* to build and install, do
- make [-j x] install
where `x` is the optional number of CPUs to use for a parallel build, if desired.
* in order to use the library, define/modify the two following environment variables:
- `LD_LIBRARY_PATH`: add [path to installation]/lib
- `GINPUT`: set to [path to installation]/share/gemini/
### Gemini++ References
<NAME>, "Systematic description of evaporation spectra for light and heavy compound nuclei", [[Physical Review C82, 014610 (2010)|https://doi.org/10.1103/PhysRevC.82.014610]]
<NAME>, <NAME> & <NAME>, "Unified description of fission in fusion and spallation reactions", [[Physical Review C82, 044610 (2010)|https://doi.org/10.1103/PhysRevC.82.044610]]
<file_sep>#include "CNuclide.h"
// mod-TU CMass CNuclide::mass;
const char* CNuclide::name[111]={"n","H","He","Li","Be","B",
"C","N","O","F","Ne",
"Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca",
"Sc","Ti","V","Cr","Mn","Fe","Co","Ni","Cu","Zn",
"Ga","Ge","As","Se","Br","Kr","Rb","Sr","Y","Zr",
"Nb","Mo","Tc","Ru","Rh","Pd","Ag","Cd","In",
"Sn","Sb","Te","I","Xe","Cs","Ba","La","Ce","Pr",
"Nd","Pm","Sm","Eu","Gd","Tb","Dy","Ho","Er",
"Tm","Yb","Lu","Hf","Ta","W","Re","Os","Ir",
"Pt","Au","Hg","Tl","Pb","Bi","Po","At","Rn",
"Fr","Ra","Ac","Th","Pa","U","Np","Pu","Am",
"Cm","Bk","Cf","Es","Fm","Md","No","Lr",
"Rf","Db","Sg","Bh","Hs","Mt","Ds"};
//*******************************************
/**
* Constructor specifies the isotope
\param iZ0 is the proton number
\param iA0 is the mass number
*/
CNuclide::CNuclide(int iZ0, int iA0)
{
//constructor
mass = CMass::instance(); // mod-TU
ran = CRandom::instance();
init(iZ0,iA0);
}
CNuclide::CNuclide() // mod-TU
{
mass = CMass::instance(); // mod-TU
ran = CRandom::instance();
}
//*******************************************************
/**
* Initializes the isotope
*
* Can be used to change the isotope
\param iZ0 is the proton number
\param iA0 is the mass number
*/
void CNuclide::init(int iZ0, int iA0)
{
//initialized the charge and mass
iZ = iZ0;
iA = iA0;
iN = iA - iZ;
fExpMass = mass->getExpMass(iZ,iA); // mod-TU mass now pointer
if (iZ == 0 && iA == 1) strChemName = "n";
else if (iZ ==1 && iA == 1) strChemName = "p";
else if (iZ == 1 && iA == 2) strChemName = "d";
else if (iZ == 1 && iA == 3) strChemName = "t";
else if (iZ>110) {
ostringstream outstring;
outstring << iA << "X-" << iZ;
strChemName = outstring.str();
}
else
{
ostringstream outstring;
outstring << iA;
strChemName = outstring.str()+ string(name[iZ]);
}
}
//**********************************************************
/**
* Returns the excess mass of the nuclide
*/
float CNuclide::getExcessMass()
{
return fExpMass;
}
//**********************************************************
/**
* alternative constructor
*/
CNuclide::CNuclide(int iZ0, int iA0, string strName0)
{
mass = CMass::instance(); // mod-TU
ran = CRandom::instance();
strName = strName0;
init(iZ0,iA0);
cout << iZ0 << " " << iA0 << " " << fExpMass << " " << strChemName << endl;
}
//**********************************************************
/**
* Returns the chemical name of the isotope as a character string
*/
const char * CNuclide::getSymbol()
{
return strChemName.c_str();
}
//********************************************
/**
* Returns the chemical name of the isotope as a string
*/
string CNuclide::getName()
{
return strChemName;
}
<file_sep>#include "CMerson.h"
#include "CPotPara.h"
#include "CWaves.h"
class CScatter : public CMerson
{
protected:
double scale;
double mu;
double V;
double VE;
double VEE;
double Wvol;
double Wsur;
double WsurE;
double Rsur;
double asur;
double a;
double zz;
double Rc;
double Ri;
double ai;
CPotPara *RealpotPara;
CPotPara *ImagVpotPara; // volume imag
CPotPara *ImagSpotPara; // surface imag
static double const e2;
static double const kconstant;
double Rmatch;
double gamma;
valarray<double> diff(double, valarray<double>);
double Kwave2;
double Kwave;
double muhbar;
int l;
public:
double plb; //!< pi-lambda-bar squared in mb
double R;
double Rboundary;
double rBarrier;
double barrier;
double omega;
double Ecm;
CScatter();
CScatter(double mu0, double V0, double VE0, double R0, double a0,double zz0, double Rc0);
virtual ~CScatter();
void init(double mu0, double V0, double VE0, double R0, double a0,double zz0, double Rc0);
void init(double mu0, double V0, double VE0, double VEE0, double R0, double a0,double zz0, double Rc0);
void init(double mu0, double V0, double VE0, double VEE0, double R0, double a0,double zz0, double Rc0, double Wsur, double WsurE, double RW, double aW);
void init(double mu0, double V0, double VE0, double R0, double a0,double zz0, double Rc0, double Wvol, double Wsur, double Ri, double ai);
double getBoundary(int l0);
double getBarrier(int l0);
double getRealPotential(double r, double E);
double getImagPotential(double r, double E);
double getCoulPotential(double r);
double getWaveFunction(double energyCM, int l0);
double getTl_OM(double energyCM, int l0);
};
<file_sep>#include "CRun.h"
/**
* this constructor is everything at the moment.
/param iZcn - CN proton number
/param iAcn is the mass number
/param fEx is the excitation energy in MeV
/param l0 is the critical spin , specifying the max spin in fusion (unit hbar)
/param d0 is the diffuseness of the spin distribution (units hbar)
/param lmax is the maximum spin value considered. (<l0 for just er info)
/param plb is pi-lambda-bar squared in mb
/param numTot is number of Monte Carlo simulations
/param title0 is name of output root file (without ".root" extension)
*/
CRun::CRun(int iZcn, int iAcn, float fEx, float l0, float d0, int lmax, float plb,
int numTot,string title0,float vcm/*=0.*/, float thetaDetMin/*=0.*/,
float thetaDetMax/*=360*/)
{
cout << title0 << endl;
string title = title0 + ".root";
bool residue;
bool residueDet;
// calculate the CN spin distribution
float prob[lmax+1];
float sum = 0.;
for (int l=0;l<=lmax;l++)
{
prob[l] = (float)(2*l+1);
//select either a fermi distribution of the erfc distribution
//if (d0 > 0.) prob[l] /= (1.+exp(((float)l-l0)/d0));
if (d0 > 0.) prob[l] *= erfc(((float)l-l0)/d0/4.*sqrt(3.14159))/2.;
else if ( l > l0) prob[l] = 0.;
sum += prob[l];
}
//normalise to unity
for (int l=0;l<=lmax;l++)
{
prob[l] /= sum;
if (l > 0) prob[l] += prob[l-1];
}
//root file for output
TFile *f = new TFile(title.c_str(),"RECREATE");
//crerate compound nucleus
CNucleus CN(iZcn,iAcn);
CNucleus.SetEvapMode(1); // turn on Hauser Feshbach
//CNucleus::setUserGDR();
//set GEMINI++ parameters
//CNucleus::setSolution(1);
//CNucleus::setFissionScaleFactor(7.38);
//CNucleus::setAddToFisBarrier(7.);
//CNucleus::setNoIMF();
//CNucleus::setAddToFisBarrier(4.);
//CNucleus::setLestone();
//CLevelDensity::setAfAn(1.036);
//CLevelDensity::setAimfAn(1.0);
//CNucleus::setTimeTransient(1.);
//CTlBarDist::setBarWidth(1.);
//CTlBarDist::setBarWidth(0.);
//CYrast::forceSierk();
CN.setVelocityCartesian((float)0.,(float)0.,(float)0.);
CAngle spin((float)0.,(float)0.);
CN.setSpinAxis(spin);
CN.printParameters();
float asy[20]={0.};
float asyMultPre[20] = {0.};
float asyMultPost[20] = {0.};
float asyMultTot[20] = {0.};
float Nres = 0.;
float NresDet = 0.;
float sumAres = 0.;
float sumAresDet = 0.;
float Nfiss = 0.;
float NpreSad = 0.;
float NpreScis = 0.;
float Npost = 0.;
float Nalpha = 0.;
float Nproton = 0.;
float Nneutron = 0.;
float NLi6 = 0.;
float NLi7 = 0.;
float NBe7 = 0.;
float Mfis = 0;
float M2fis = 0.;
float M0fis = 0.;
double numberA = 0.;
double averageA = 0.;
TH1F histEgammaTot("EgammaTot","",100,0,50);
histEgammaTot.GetXaxis()->SetTitle("E_{#gamma} [MeV]");
histEgammaTot.GetYaxis()->SetTitle("#sigma(E_{#gamma}) [mb/MeV]");
histEgammaTot.SetTitle("distribution of total gamma energy for all events");
TH1F histEgamma("Egamma","",100,0,50);
histEgamma.GetXaxis()->SetTitle("E_{#gamma} [MeV]");
histEgamma.GetYaxis()->SetTitle("#sigma(E_{#gamma}) [mb/MeV]");
histEgamma.SetTitle("distribution of gamma energies for all events");
TH1F histEgammaER("EgammaER","",100,0,50);
histEgammaER.GetXaxis()->SetTitle("E_{#gamma} [MeV] for residues");
histEgammaER.GetYaxis()->SetTitle("#sigma(E_{#gamma}) [mb/MeV]");
histEgammaER.SetTitle("distribution of gamma energies for evap. residues");
TH1F histER("histER","",91,-0.5,90.5);
histER.GetXaxis()->SetTitle("J_{CN} [hbar]");
histER.GetYaxis()->SetTitle("#sigma(J) [mb]");
histER.SetTitle("spin distribution of events that form residues");
TH1F histERxn("histERxn","",91,-0.5,90.5);
histERxn.GetXaxis()->SetTitle("J_{CN} [hbar]");
histERxn.GetYaxis()->SetTitle("#sigma(J) [mb]");
histERxn.SetTitle("spin distribution of residue that decay by neutrons only");
TH1F histFis("histFis","",91,-0.5,90.5);
histFis.GetXaxis()->SetTitle("J_{CN} [hbar]");
histFis.GetYaxis()->SetTitle("#sigma(J) [mb]");
histFis.SetTitle("spin distribution of events that fission");
TH1F histFus("histFus","",91,-0.5,90.5);
histFus.GetXaxis()->SetTitle("J [hbar]");
histFus.GetYaxis()->SetTitle("#sigma(J) [mb]");
histFus.SetTitle("spin distribution of all fusion events");
TH1F histA("histA","",231,-0.5,230.5);
histA.GetXaxis()->SetTitle("A");
histA.GetYaxis()->SetTitle("#sigma(A) [mb]");
histA.SetTitle(" inclusive mass distribution");
TH1F histZ("histZ","",93,-0.5,92.5);
histZ.GetXaxis()->SetTitle("Z");
histZ.GetYaxis()->SetTitle("#sigma(Z) [mb]");
histZ.SetTitle(" inclusive charge distribution");
TH1F histZ_fis("histZ_fis","",93,-0.5,92.5);
histZ_fis.GetXaxis()->SetTitle("Z");
histZ_fis.GetYaxis()->SetTitle("#sigma(Z) [mb]");
histZ_fis.SetTitle("charge distribution for fission events");
TH1F histZ_nofis("histZ_nofis","",93,-0.5,92.5);
histZ_nofis.GetXaxis()->SetTitle("Z");
histZ_nofis.GetYaxis()->SetTitle("#sigma(Z) [mb]");
histZ_nofis.SetTitle("charge distribution for non-fission events");
TH1F histN("histN","",153,-0.5,152.5);
histN.GetXaxis()->SetTitle("N");
histN.GetYaxis()->SetTitle("#sigma(N) [mb]");
histN.SetTitle(" inclusive neutron-number distribution");
//the following are differential multiplicity
TH1F keNeutron("keNeutron","",50,0,50);
keNeutron.GetXaxis()->SetTitle("E_{k} [MeV]");
keNeutron.GetYaxis()->SetTitle("dm/dE [MeV^{-1}]");
keNeutron.SetTitle("neutron energy spectra in coincidence with residues");
TH1F keAlpha("keAlpha","",50,0,50);
keAlpha.GetXaxis()->SetTitle("E_{k} [MeV]");
keAlpha.GetYaxis()->SetTitle("dm/dE [MeV^{-1}]");
keAlpha.SetTitle("#alpha particle energy spectra in coincidence with residues");
TH1F keProton("keProton","",50,0,50);
keProton.GetXaxis()->SetTitle("E_{k} [MeV]");
keProton.GetYaxis()->SetTitle("dm/dE [MeV^{-1}]");
keProton.SetTitle("proton energy spectra in coincidence with residues");
TH1F keLi6("keLi6","",60,0,60);
keLi6.GetXaxis()->SetTitle("E_{k} [MeV]");
keLi6.GetYaxis()->SetTitle("dm/dE [MeV^{_1}]");
keLi6.SetTitle("^{6}Li energy spectra in coincidence with residues");
TH1F keLi7("keLi7","",60,0,60);
keLi7.GetXaxis()->SetTitle("E_{k} [MeV]");
keLi7.GetYaxis()->SetTitle("dm/dE [MeV^{-1}]");
keLi7.SetTitle("^{7}Li energy spectra in coincidence with residues");
TH1F keBe7("keBe7","",60,0,60);
keBe7.GetXaxis()->SetTitle("E_{k} [MeV]");
keBe7.GetYaxis()->SetTitle("dm/dE [MeV^{-1}]");
keBe7.SetTitle("^{7}Be energy spectra in coincidence with residues");
//the following are differential cross sections
TH1F sigNeutron("sigNeutron","",50,0,50);
sigNeutron.GetXaxis()->SetTitle("E_{k} [MeV]");
sigNeutron.GetYaxis()->SetTitle("d#sigma/dE [mb/MeV]");
sigNeutron.SetTitle("inclusive neutron energy spectra");
TH1F sigAlpha("sigAlpha","",50,0,50);
sigAlpha.GetXaxis()->SetTitle("E_{k} [MeV]");
sigAlpha.GetYaxis()->SetTitle("d#sigma/dE [mb/MeV]");
sigAlpha.SetTitle("inclusive #alpha-particle energy spectra");
TH1F sigProton("sigProton","",50,0,50);
sigProton.GetXaxis()->SetTitle("E_{k} [MeV]");
sigProton.GetYaxis()->SetTitle("d#sigma/dE [mb/MeV]");
sigProton.SetTitle("inclusive proton energy spectra");
TH2F histAL("histAL","",251,-0.5,250.5,100,0,100);
histAL.GetXaxis()->SetTitle("A");
histAL.GetYaxis()->SetTitle("J_{CN} [hbar]");
histAL.SetTitle("inclusive mass and CN spin distribution");
TH2F histZN("histZN","",152,-0.5,151.5,152,-0.5,151.5);
histZN.GetXaxis()->SetTitle("N");
histZN.GetYaxis()->SetTitle("Z");
histZN.SetTitle("inclusive joint N_Z distributions of all fragments");
TH1F keFF("keFF","",150,0,150);
keFF.GetXaxis()->SetTitle("E_{k} [MeV]");
keFF.GetYaxis()->SetTitle("d#sigma/dE [mb/MeV]");
keFF.SetTitle("Fission Fragment kinetic-energy spectrum");
TH1F velFF("velFF","",100,0,4.);
velFF.GetXaxis()->SetTitle("v [cm/ns]");
velFF.GetYaxis()->SetTitle("d#sigma/dv [mb/cm/ns]");
velFF.SetTitle("Fission Fragment velocity spectrum");
TH1F kePreSad("kePreSad","",100,0,30);
kePreSad.GetXaxis()->SetTitle("E_{k} [MeV]");
kePreSad.GetYaxis()->SetTitle("dm/dE [MeV^{-1}]");
kePreSad.SetTitle("pre-saddle neutron multiplicity spectrum");
TH1F kePreSS("keSS","",100,0,30);
kePreSS.GetXaxis()->SetTitle("E_{k} [MeV]");
kePreSS.GetYaxis()->SetTitle("dm/dE [MeV^{-1}]");
kePreSS.SetTitle("saddle-to-scission neutron multiplicity spectrum");
TH1F kePreSc("kePreSc","",100,0,30);
kePreSc.GetXaxis()->SetTitle("E_{k} [MeV]");
kePreSc.GetYaxis()->SetTitle("dm/dE [MeV^{-1}]");
kePreSc.SetTitle("pre-scission neutron multiplicity spectrum");
TH1F kePost("kePost","",100,0,30);
kePost.GetXaxis()->SetTitle("E_{k} [MeV]");
kePost.GetYaxis()->SetTitle("dm/dE [MeV^{-1}]");
kePost.SetTitle("post scission neutron spectrum");
bool f14=1;
bool f12=1;
bool f34=1;
for (int i=0;i<numTot;i++)
{
float weight = 1.;
//cout <<"event= " << i << endl;
if (i > numTot*.25 && f14)
{
cout << " 25%" << flush;
f14 = 0;
}
if (i > numTot*.5 && f12)
{
cout << '\xd' << " 50%" << flush;
f12 = 0;
}
if (i > numTot*.75 && f34)
{
cout << '\xd'<< " 75%" << endl;
f34 = 0;
}
float ran = CN.ran->Rndm();
int l = 0;
for (;;)
{
if (ran < prob[l]) break;
l++;
}
// l = 43; //rjc
//fEx = 77.83;
CN.setCompoundNucleus(fEx,(float)l);
{
//if (i%100==0)cout << "l= "<< l << " i= " << i << endl;
CN.setWeightIMF(); //turn on enhanced IMF emission
CN.decay();
if (CN.abortEvent)
{
CN.reset();
continue;
}
histEgammaTot.Fill(CN.getSumGammaEnergy());
for(int i =0; i<CN.getnGammaRays(); i++)
{
histEgamma.Fill(CN.getGammaRayEnergy(i));
if (CN.isResidue())histEgammaER.Fill(CN.getGammaRayEnergy(i));
}
int iStable = CN.getNumberOfProducts();
CNucleus *productER = CN.getProducts(iStable-1);
weight *= productER->getWeightFactor();
if(productER->iZ == iZcn)
{
averageA += (double)productER->iA*(double)weight;
numberA += (double)weight;
}
int iZres = productER->iZ;
//int iAres = productER->iA;
int multTot = 0;
int iZ, iA;
CNucleus * product = CN.getProducts(0);
histFus.Fill(l,weight);
if (CN.isResidue())
{
float * vv;
vv = productER->getVelocityVector();
vv[2] += vcm;
float vvv = sqrt(pow(vv[0],2)+pow(vv[1],2)+pow(vv[2],2));
float AngleDeg = acos(vv[2]/vvv)*180./3.14159;
if (AngleDeg > thetaDetMin && AngleDeg < thetaDetMax)
residueDet = 1;
else residueDet = 0;
residue = 1;
histER.Fill(l,weight);
if (iZres == iZcn)
{
histERxn.Fill(l,weight);
}
Nres += weight;
sumAres += weight*(float)productER->iA;
if (residueDet)
{
NresDet += weight;
sumAresDet += weight*(float)productER->iA;
}
}
else
{
residue = 0;
residueDet = 0;
}
if (CN.isSymmetricFission())
{
Nfiss += weight;
histFis.Fill(l,weight);
}
int iAmax = 0;
int iAnext = 0;
float vmax = 0.;
float vnext = 0.;
float emax = 0.;
float enext = 0.;
for (int j=0;j<iStable;j++)
{
iZ = product->iZ;
iA = product->iA;
if (iA > iAmax)
{
iAnext = iAmax;
vnext = vmax;
enext = emax;
iAmax = iA;
emax = product->getKE();
vmax = product->getVelocity();
}
else if (iA > iAnext)
{
iAnext = iA;
enext = product->getKE();
vnext = product->getVelocity();
}
//cout << iZ << " " << iA << endl;
if (product->getTime() < 0.)
{
cout << "negative time" << endl;
cout << iZ << " " << iA << " " <<
product->getParent()->iZ << " " <<
product->getParent()->iA << " "
<< product->getParent()->fEx << " "
<< product->getParent()->fJ << endl;
}
histZ.Fill(iZ,weight);
if (CN.isSymmetricFission())histZ_fis.Fill(iZ,weight);
else histZ_nofis.Fill(iZ,weight);
histA.Fill(iA,weight);
histAL.Fill(iA,l,weight);
histN.Fill(iA-iZ,weight);
histZN.Fill(iA-iZ,iZ,weight);
if (iZ == 0 && iA == 1)
{
if (residueDet) //iARes >= Ares)
{
keNeutron.Fill(product->getKE(),weight);
Nneutron += weight;
}
sigNeutron.Fill(product->getKE(),weight);
multTot++;
if (CN.isSymmetricFission())
{
if (product->origin == 0)
{
kePreSad.Fill(product->getKE(),weight);
NpreSad += weight;
}
if (product->origin == 1)
kePreSS.Fill(product->getKE(),weight);
if (product->origin <= 1)
{
NpreScis += weight;
kePreSc.Fill(product->getKE(),weight);
}
if (product->origin > 1)
{
Npost += weight;
kePost.Fill(product->getKE(),weight);
}
}
}
else if (iZ == 1 && iA == 1)
{
if(residueDet)
{
keProton.Fill(product->getKE(),weight);
Nproton += weight;
}
sigProton.Fill(product->getKE(),weight);
}
else if (iZ == 2 && iA == 4)
{
if(residueDet)
{
keAlpha.Fill(product->getKE(),weight);
Nalpha += weight;
}
sigAlpha.Fill(product->getKE(),weight);
}
else if (iZ == 3 && iA == 6)
{
if(residueDet)
{
keLi6.Fill(product->getKE(),weight);
NLi6 += weight;
}
}
else if (iZ == 3 && iA == 7)
{
if(residueDet)
{
keLi7.Fill(product->getKE(),weight);
NLi7 += weight;
}
}
else if (iZ == 4 && iA == 7)
{
if(residueDet)
{
keBe7.Fill(product->getKE(),weight);
NBe7 += weight;
}
}
if (iZ > 5 && CN.isSymmetricFission())
{
keFF.Fill(product->getKE(),weight);
velFF.Fill(product->getVelocity(),weight);
Mfis += (float)product->iA;
M2fis += pow((float)product->iA,2);
M0fis += 1.;
}
product=CN.getProducts();
}
float Amax = (float)iAmax/(float)(iAmax+iAnext)*162.;
float Anext = (float)iAnext/(float)(iAmax+iAnext)*162.;
int iasy = (int)(Amax/10);
asy[iasy] += weight;
asyMultPre[iasy] += weight*(float)CN.getMultPre();
asyMultPost[iasy] += weight*(float)CN.getMultPost();
asyMultTot[iasy] += weight*(float)multTot;
iasy = (int)(Anext/10);
asy[iasy] += weight;
asyMultPre[iasy] += weight*(float)CN.getMultPre();
asyMultPost[iasy] += weight*(float)CN.getMultPost();
asyMultTot[iasy] += weight*(float)multTot;
CN.reset();
}
}
title = title0+"M.dat";
ofstream ofFile(title.c_str());
for (int i=0;i<20;i++)
{
if (asy[i] == 0) continue;
ofFile << i*10 + 5 << " " << asyMultPre[i]/asy[i] << " " <<
asyMultPost[i]/asy[i] << " " << asyMultTot[i]/asy[i] << endl;
}
histA.Scale(plb/(float)numTot*sum);
histZ.Scale(plb/(float)numTot*sum);
histZ_fis.Scale(plb/(float)numTot*sum);
histZ_nofis.Scale(plb/(float)numTot*sum);
histN.Scale(plb/(float)numTot*sum);
histZN.Scale(plb/(float)numTot*sum);
velFF.Scale(plb/(float)numTot*sum/velFF.GetBinWidth(1));
keFF.Scale(plb/(float)numTot*sum/keFF.GetBinWidth(1));
//for multiplicity spectrra in coincidence with fission
kePreSad.Scale(1./Nfiss/kePreSad.GetBinWidth(1));
kePreSS.Scale(1./Nfiss/kePreSS.GetBinWidth(1));
kePreSc.Scale(1./Nfiss/kePreSc.GetBinWidth(1));
kePost.Scale(1./Nfiss/kePost.GetBinWidth(1));
//for multiplicity spectra in coincidence with residues
keAlpha.Scale(1./NresDet/keAlpha.GetBinWidth(1));
keProton.Scale(1./NresDet/keProton.GetBinWidth(1));
keNeutron.Scale(1./NresDet/keNeutron.GetBinWidth(1));
keLi6.Scale(1./NresDet/keLi6.GetBinWidth(1));
keLi7.Scale(1./NresDet/keLi7.GetBinWidth(1));
keBe7.Scale(1./NresDet/keBe7.GetBinWidth(1));
sigNeutron.Scale(plb/(float)numTot*sum/sigNeutron.GetBinWidth(1));
sigProton.Scale(plb/(float)numTot*sum/sigProton.GetBinWidth(1));
sigAlpha.Scale(plb/(float)numTot*sum/sigAlpha.GetBinWidth(1));
histEgamma.Scale(plb/(float)numTot*sum/histEgamma.GetBinWidth(1));
histEgammaER.Scale(plb/(float)numTot*sum/histEgammaER.GetBinWidth(1));
histEgammaTot.Scale(plb/(float)numTot*sum/histEgammaTot.GetBinWidth(1));
f->Write();
cout << "NresDet= " << NresDet << " Nneut= " << Nneutron << " NProt= " <<
Nproton << " Nalpha= " << Nalpha << " NLi6= " << NLi6 << " NLi7= " << NLi7
<< " NBe7= " << NBe7 << endl;
cout << "Li6 mult = " << NLi6/NresDet << endl;
cout << "Li7 mult = " << NLi7/NresDet << endl;
cout << "Be7 mult = " << NBe7/NresDet << endl;
cout << "neutron mult= " << Nneutron/NresDet << endl;
cout << "proton mult= " << Nproton/NresDet << endl;
cout << "alpha mult= " << Nalpha/NresDet << endl;
cout << " mean ER A = " << sumAres/Nres << endl;
cout << " for det res = " << sumAresDet/NresDet << endl;
float xER = Nres/(float)numTot*sum*plb;
float xFiss2 = Nfiss/(float)numTot*sum*plb;
cout << "sigmaER = " << xER << " mb " << endl;
float xFus = 0.;
for (int l=0;l<200;l++)
{
float xx = (float)(2*l+1);
if (d0 > 0.) xx /=(1.+exp(((float)l-l0)/d0));
else if (l > l0) break;
xFus += xx;
}
xFus *= plb;
float xFis = xFus - xER;
cout << "fusion xsec= " << xFus << " mb" << endl;
cout << "fission xsec= " << xFis << " mb " << xFiss2 << " mb " << endl;
if (Nfiss > 0.)
{
cout << "preSaddle neut mult = " << NpreSad/Nfiss << endl;
cout << "preScis neut mult = " << NpreScis/Nfiss << endl;
cout << "post neut mult = " << Npost/Nfiss << endl;
float Mav = Mfis/M0fis;
cout << "mean fission mass = " << Mav << endl;
float sigma2 = M2fis/(M0fis-1) - M0fis/(M0fis-1)*pow(Mav,2);
//float sigma = sqrt(sigma2);
cout << "sigma2M= " << sigma2 << endl;
}
if (numberA > 0) cout << "average x for xn products is " << (float)iAcn-
averageA/numberA << endl;
}
<file_sep>#include "CEvap.h"
CEvap* CEvap::fInstance = 0;
float const r0 = 1.16;
/**
* Constructor
*/
CEvap::CEvap()
{
string fileName("tbl/evap.inp");
string fullName;
if (getenv("GINPUT") == NULL) fullName = fileName;
else
{
string dir(getenv("GINPUT"));
fullName = dir+fileName;
}
ifstream ifFile (fullName.c_str());
if (ifFile.fail())
{
cout << " file " << fullName << " not found" << endl;
abort();
}
// read in number of evaporation channels
ifFile >> nLight;
prob = new float [nLight];
// create array of CLightP pointers
lightP = new CLightP * [nLight];
tlArray = new CTlBarDist * [nLight];
sigBarDist = new CSigBarDist * [nLight];
// read in channel information and initialize pointers
decay = new SDecay [nLight];
// skip line
string line;
getline(ifFile,line);
getline(ifFile,line);
float fJ, fEx, Ek, suppress;
int iZ, iA;
string nameOld("");
string name("");
bool newTl;
nTl = 0;
for (int i=0;i<nLight;i++)
{
nameOld = name;
ifFile >> iZ >> iA >> fJ >> fEx >> name >> suppress >> Ek;
// determine if we need to create new transmission coeff
newTl = 1;
if (i > 0)
{
if (name == nameOld) newTl = 0;
}
if (newTl)
{
tlArray[nTl] = new CTlBarDist(name);
sigBarDist[nTl] = new CSigBarDist(name,(float)iZ,(float)iA);
nTl++;
}
lightP[i] = new CLightP(iZ,iA,fJ,tlArray[nTl-1],sigBarDist[nTl-1]);
lightP[i]->rLight = pow((float)iA,(float)(1./3.))*r0;
lightP[i]->fEx = fEx;
lightP[i]->suppress = suppress;
// if an excited state add excitation energy to mass excess
if (fEx > 0.0) lightP[i]->fExpMass += fEx;
maxZ = iZ;
decay[i].Ek = Ek;
if (Ek == 0.) continue;
// read in decay information
ifFile >> decay[i].Z1 >> decay[i].A1 >> decay[i].S1 >>
decay[i].S2 >> decay[i].L >> decay[i].lPlusS1 >> decay[i].gamma;
// here are sum checks to make sure decay information is possible
if (decay[i].lPlusS1 > decay[i].S1 + (float)decay[i].L)
{
cout << "bad LPlusS1 in evap.cpp for mode " << i << endl;
abort();
}
if (decay[i].lPlusS1 < fabs(decay[i].S1 - (float)decay[i].L))
{
cout << "bad LPlusS1 in evap.cpp for mode " << i << endl;
abort();
}
if (fJ > decay[i].lPlusS1+decay[i].S2)
{
cout << "bad fJ in evap.cpp for mode " << i << endl;
abort();
}
if (fJ < fabs(decay[i].lPlusS1-decay[i].S2))
{
cout << "bad fJ in evap.cpp for mode " << i << endl;
abort();
}
}
ifFile.clear();
ifFile.close();
}
CEvap* CEvap::instance()
{
if (fInstance == 0) {
fInstance = new CEvap;
}
return fInstance;
}
//**************************************************
/**
* Destructor
*/
CEvap::~CEvap()
{
for (int i=0;i<nLight;i++) delete lightP[i];
for (int i=0;i<nTl;i++)
{
delete tlArray[i];
delete sigBarDist[i];
}
delete [] prob;
delete [] lightP;
delete [] tlArray;
delete [] sigBarDist;
delete [] decay;
}
<file_sep>/**
*!\brief weighted Monte Carlo
*
* Class CWeight is a base class that deals with a weighted
* Monte Carlo scheme. It is used to enhance the probabilty of IMF emission.
* To compensate for this, each event is given a weight.
* This weight should be used when histogramming events.
*
*/
class CWeight
{
protected:
float fact; //!< weighting factor
int iWeight; //!< ==0, no weighting
float runningWeight; //!< running weight of event
void findFactor(float Glight, float Gimf, float Gfission, float Ggamma);
public:
int chooseChannel(float Glight, float Gimf, float Gfission, float Ggamma,
float xran);
void setWeightIMF();
float getWeightFactor();
};
<file_sep>#ifndef coul_
#define coul_
#include <iostream>
#include <cmath>
#include <complex>
using namespace std;
class CCoul
{
public:
double logDerF(int ,double, double );
complex<double> logDerH(int, double, double);
double abSum (complex<double>);
int init(int, double, double);
double F;
double dF;
double G;
double dG;
};
#endif
<file_sep>#ifndef evap_
#define evap_
#include "CLightP.h"
#include <fstream>
#include <iostream>
using namespace std;
/**
*!\brief storage of light particle properties
*
* the Structure stores the information on the secondary decay of
* particle-unstable evaporation fragments. (used in CEvap)
*/
struct SDecay
{
float Ek; //!< kinetic energy released in secoardy decay (MeV)
float S1; //!< spin of one of the secondary particles
float S2; //!< spin of the other secondary particle
float lPlusS1; //!< spin + orbital AM of the first secondary particle
short unsigned Z1; //!<proton number of the first secondary particle
short unsigned A1; //!< mass number of the first secondary particle
short unsigned L; //!< orbital angular momentum of the decay
float gamma; //!< width of the state im MeV
};
/**
*!\brief stores info for light particle evaporation
*
* class to store indormation on all the light particle evaporation channels
*/
class CEvap
{
protected:
CEvap();
static CEvap *fInstance; //!< instance member to make this class a singleton
CTlBarDist ** tlArray; //!< arrays of objects generating transmission coef.
CSigBarDist ** sigBarDist; //!< arrays of objects generating inverse cross section
int nTl; //!< number of transmission coef generating objects
public:
static CEvap *instance();
int nLight; //!< number of light-particle evaporation channels
CLightP ** lightP; //!< array of evaporated particles
int maxZ; //!< max Z of all fragments evaporated, IMF emission for larger Z's
SDecay * decay; //!<information on secondary decay of evaporated particles
~CEvap();
float * prob; //!< probability for decay
};
#endif
<file_sep>#include "CRandom.h"
CRandom* CRandom::fInstance = 0;
/**
* Makes an instance of CRandom
*/
CRandom* CRandom::instance()
{
if (fInstance == 0) {
fInstance = new CRandom;
}
return fInstance;
}
/**
* COnstructor for CRandom
*/
CRandom::CRandom()
{
pi = acos(-1.);
one = true;
angle = 0.;
x = 0.;
}
CRandom::~CRandom()
{
}
/**
* Returns a random number with uniform distribution between 0 and 1
*/
double CRandom::Rndm()
{
return (float)rand()/(float)RAND_MAX;
}
//***********************
/**
* Returns random number with Gaussian distribution
\param mean is the mean value of the Gaussian distribution
\param sigma is the standard deviation of the distribution
*/
float CRandom::Gaus(float mean, float sigma)
{
float r;
if (one)
{
x = sqrt(-2.*log(Rndm()+1.e-37));
angle = 2.*pi*Rndm();
one = 0;
r = x*cos(angle);
}
else
{
r = x*sin(angle);
one = 1;
}
return sigma*r + mean;
}
//*************************
/**
* returns a decay time in zs sampled from a exponential distribution
\param width is the total decay width in MeV
*/
float CRandom::expDecayTime(float width)
{
// returns a time from an exponential decay distribution
//consistent with the total decay width
if(width>0.)
return - 0.65824*log(Rndm()+1.0e-37)/width;
else
return 1.E30;
}
//****************************************
/**
* Returns a random number with a BreitWigner distribution
\param mean is the mean value of the distribution
\param width is the Full Width Half max of the distribution
*/
float CRandom::BreitWigner(float mean, float width)
{
float xx = (1.-2.*Rndm())*pi/2.;
float yy = tan(xx)/2.;
return yy*width + mean;
}
<file_sep>//sample program to use GEMINI++
// in alpha induced reactions.
// The reaction cross section predicted by the
// optical model with Avrigeanu's global parmeters
// is assumed to go completely into fusion with the spin distribution
// predicted by the optical model.
// The compound nuclei are then decayed with gemini++
// The xn cross sections are printed out.
#include "CRunAlpha.h"
#include "CNucleus.h"
#include "CAlphaOM.h"
#include "CMass.h"
CRunAlpha::CRunAlpha(int iZ, int iA, double Elab, int Nevents)
{
CAlphaOM om((double)iZ,(double)iA,Elab);
int iZCN = iZ + 2;
int iACN = iA + 4;
CNucleus CN(iZCN,iACN);
CLevelDensity::setLittleA(12.);
CN.setEvapMode(1);
CN.printParameters();
CMass * mass = CMass::instance();
float Ecm = Elab*(float)iA/(float)(iACN);
float Q = mass->getExpMass(iZ,iA) + 2.242 - mass->getExpMass(iZCN,iACN);
cout << "Q = " << Q << " MeV" << endl;
float Ex = Ecm + Q;
cout << "Ex = " << Ex << " MeV" << endl;
int xn[20]={0};
int Nfission = 0;
for (int i=0;i<Nevents;i++)
{
float fL = (float)om.getL(CN.ran->Rndm());
CN.setCompoundNucleus(Ex,fL);
CN.decay();
if (CN.abortEvent)
{
CN.reset();
continue;
}
if (CN.isSymmetricFission()) Nfission++;
else
{
int iStable = CN.getNumberOfProducts();
CNucleus *productER = CN.getProducts(iStable-1);
if (productER->iZ == iZCN)
{
int x = iACN - productER->iA;
if (x < 20) xn[x]++;
}
}
CN.reset();
}
cout << "tot x sec = " << om.getXsec() << " mb" << endl;
float konst = om.getXsec()/(float)Nevents;
cout << "sigFission = " << (float)Nfission*konst << " mb " <<
sqrt((float)Nfission)*konst << endl;
for (int i=0;i<10;i++)
{
cout << i << " " << (float)xn[i]*konst << " " <<
sqrt((float)xn[i])*konst << endl;
}
}
<file_sep>// -*- mode: c++ -*-
//
#ifndef nuclide_
#define nuclide_
#include <string>
#include "CMass.h"
#include "CRandom.h"
#include <sstream>
//*****ROOT**********
//#include "TObject.h"
/**
*!\brief info on each nucleus
*
* basic class CNuclide - stores the basic properties of the nucleus
*/
class CNuclide //: public TObject
{
protected:
string strChemName; //!< gives isotopes and chemical name, e.g. 208Pb
string strName; //!< identifation name
static const char * name[111]; //!< array containing name of all elements
public:
// mod-TU static CMass mass; //!< mass excess class
CMass *mass; //!< mass excess class
CRandom *ran; //!< random number generator class
int iZ; //!< proton number
int iN; //!< neutron number
int iA; //!< mass number
float fJ; //!< spin [hbar]
float fExpMass; //!< mass excess [MeV]
float fEx; //!< excitation energy [MeV]
CNuclide(int iZ ,int iA);
CNuclide(int,int,string);
void init(int,int);
// mod-TU CNuclide(){};
CNuclide(); // mod-TU
float getExcessMass();
const char* getSymbol();
string getName();
//*****ROOT*******
//ClassDef(CNuclide,1) //Gemini Nuclide
};
#endif
<file_sep>#include "CWaves.h"
#include "CCoul.h"
CWaves::CWaves(double rho0, double gamma0, int lMaximum0)
:rho(rho0),gamma(gamma0),lMaximum(lMaximum0)
{
F = new double [lMaximum+2];
dF = new double [lMaximum+2];
G = new double [lMaximum+2];
dG = new double [lMaximum+2];
sigma = new double [lMaximum+2];
if (gamma == 0.) sphericalBessel();
else coulombWave();
}
//******************************************************
// destructor
CWaves::~CWaves()
{
delete [] F;
delete [] dF;
delete [] G;
delete [] dG;
delete [] sigma;
}
//**************************************************************
// prepares Coulomb wave functions and the phase shift
// follows B. Buck paper
void CWaves::coulombWave()
{
// first calculate sigma - Coulomb phase shift
// to do this, start with a calculation of the
// phaseshift for l=50 from asymptotic series expansion
int const lBegin = 50;
double lbegin1 = (double)(lBegin+1);
double alpha = atan(gamma/lbegin1);
double beta = sqrt(pow(gamma,2)+ pow(lbegin1,2));
double sigma0 = alpha*((double)lBegin+1./2.) + gamma*(log(beta)-1.)
+ (-sin(alpha)/12. + sin(3.*alpha)/360./pow(beta,2)
- sin(5.*alpha)/1260./pow(beta,4) + sin(7.*alpha)/1680./pow(beta,6)
- sin(9.*alpha)/1188./pow(beta,8))/beta;
// now use recurrence relationship to get sigma for all lower l-waves
for (int l=lBegin-1;l>=0;l--)
{
sigma0 -= atan(gamma/(double)(l+1));
if (l <= lMaximum) sigma[l] = sigma0;
}
//***********************************************
// now calculate G0
double s = 1.;
double t = 0.;
double S = 0.;
double T = 1.- gamma/rho;
double sums = s;
double sumS = S;
double sumt = t;
double sumT = T;
for (int i=0;i<26;i++)
{
double denominator = 2.*rho*(double)(i+1);
double fact1 = (double)(2*i+1)*gamma/denominator;
double fact2 = (pow(gamma,2) - (double)(i*(i+1)))/denominator;
double snew = fact1*s - fact2*t;
double tnew = fact1*t + fact2*s;
double Snew = fact1*S - fact2*T - snew/rho;
double Tnew = fact1*T + fact2*S - tnew/rho;
s = snew; t = tnew; S = Snew; T = Tnew;
sums += s;
sumt += t;
sumS += S;
sumT += T;
}
if (abs(sums*sumT - sumS*sumt - 1.) > 1e-4)
{
// cout << " Problem generating G0" << endl;
//cout << "s*T - S*t = " << sums*sumT - sumS*sumt << endl;
CCoul coul;
coul.init(0,gamma,rho);
G[0] = coul.G;
dG[0] = coul.dG;
}
else
{
double fact = -gamma*log(2.*rho) + rho + sigma[0];
G[0] = sums*cos(fact) - sumt*sin(fact);
dG[0] = sumS*cos(fact) - sumT*sin(fact);
}
//****************************************************
// now get G1 from Eq 17 B. Buck
G[1] = ((gamma + 1./rho)*G[0] - dG[0])/sqrt(pow(gamma,2)+1.);
//*****************************************************
//now use recursion relationship Eq 15 of B. Buck to get all G's
// also Eq 17 will give us the derivatives.
for (int l=1;l<=lMaximum;l++)
{
double ll = (double)l;
double fact1 = (2.*ll+1.)*(gamma/(ll*(ll+1.)) + 1./rho);
double fact2 = sqrt(pow(gamma,2)+pow(ll,2))/ll;
double fact3 = sqrt(pow(gamma,2)+pow(ll+1.,2))/(ll+1.);
double fact4 = gamma/(ll+1) + (ll+1)/rho;
G[l+1] = (fact1*G[l] - fact2*G[l-1])/fact3;
dG[l] = (fact4*G[l] - fact3*G[l+1]);
}
//*****************************************************
// now for the F's using recursion relationship Eq 15 of <NAME>
// also derivative from Eq 17
int const lstart = 60;
double const epsilon = 1.e-60;
double fp = 0.; // value of F/scale at l+1
double f = epsilon; // value of F/scale at l
double fm; // value of f at l-1
for (int l=lstart;l>=1;l--)
{
double ll = (double)l;
double fact1 = (2.*ll+1.)*(gamma/(ll*(ll+1.)) + 1./rho);
double fact2 = sqrt(pow(gamma,2)+pow(ll,2))/ll;
double fact3 = sqrt(pow(gamma,2)+pow(ll+1.,2))/(ll+1.);
double fact4 = gamma/(ll+1) + (ll+1)/rho;
fm = ( fact1*f - fact3*fp )/fact2;
if (l-1 <= lMaximum) F[l-1] = fm;
if (l <= lMaximum) dF[l] = fact4*f - fact3*fp;
fp = f; f = fm;
}
dF[0] = (gamma + 1./rho)*F[0] - sqrt(pow(gamma,2)+1.)*F[1];
//***********************************************
// finding scaling parameter for F and dF,
// the Wronskian (Eq 16) should be unity
double scale = dF[0]*G[0] - F[0]*dG[0];
for (int l=0;l<=lMaximum;l++)
{
dF[l] /= scale;
F[l] /= scale;
}
}
//****************************************************
void CWaves::sphericalBessel()
{
// start with the regular soultion
F[0]=sin(rho)/rho;
F[1]=(F[0]-cos(rho))/rho;
if (lMaximum >= 2)
{
double sa = F[0];
double sb = F[1];
double f0 = 0.0;
double f1 = 1.0E0-100;
double f;
int const lStart = 60;
for (int k=lStart;k>=0;k--)
{
f = (2.0*(double)k+3.0)*f1/rho-f0;
if (k <= lMaximum) F[k]=f;
f0 = f1;
f1 = f;
}
double cs=1.;
if (abs(sa) > abs(sb)) cs=sa/f;
else cs=sb/f0;
for (int k=0;k<=lMaximum;k++)F[k]*=cs;
}
dF[0]=(cos(rho)-sin(rho)/rho)/rho;
for (int k=1;k<=lMaximum;k++)dF[k]=F[k-1]-(k+1.0)*F[k]/rho;
//************ now for the irregular
G[0]=-cos(rho)/rho;
G[1]=(G[0]-sin(rho))/rho;
double f0 = G[0];
double f1 = G[1];
int k = 2;
double f;
for (;;)
{
f=(2.0*(double)k-1.0)*f1/rho-f0;
G[k]=f;
if (abs(f) >= 1.0E+300) break;
f0 = f1;
f1 = f;
k++;
if (k > lMaximum) break;
}
dG[0]=(sin(rho)+cos(rho)/rho)/rho;
for (int i=1;i<=lMaximum;i++)
dG[i]=G[i-1]-((double)i+1.0)*G[i]/rho;
// up until this point F,G and dF,dF are the regular and irregular
// spherical bessel functions and their derivative
// we now need to go the equivalent form of the
// the regular wavefunction F and the irregular G.
for (int k=0;k<=lMaximum;k++)
{
dF[k] = dF[k]*rho + F[k];
dG[k] = -dG[k]*rho - G[k];
F[k] *= rho;
G[k] *= -rho;
sigma[k] = 0.;
if (abs(dF[k]*G[k] - F[k]*dG[k] - 1.) > .001)
{
if (k == 1)
{
cout << "Wronskina error" << endl;
cout << "l= " << k << " rho= " << rho << endl;
cout << F[k] << " " << dF[k] << " " << G[k] << " " << dG[k] << endl;
cout << dF[k]*G[k] - F[k]*dG[k] << endl;
}
}
}
}
<file_sep>#include "CAlphaOM.h"
using namespace std;
CAlphaOM::CAlphaOM(double Z, double A, double Elab)
{
double Ecm = Elab*A/(A+4.);
alpha.findPara(Z,A,Elab);
scatter.init(alpha.mu,alpha.V,0.,alpha.R,alpha.a,alpha.zz,
alpha.Rc,alpha.Wvol,alpha.Wsur,alpha.Ri,alpha.ai);
int l= 0;
xsec = 0.;
for (;;)
{
double tl = scatter.getTl_OM(Ecm,l);
sl[l] = (double)(2*l+1)*tl*scatter.plb;
xsec += sl[l];
if (tl < .001) break;
l++;
}
lmax = l;
for (int l=0;l<=lmax;l++)
{
prob[l] = sl[l]/xsec;
if (l > 0) prob[l] += prob[l-1];
}
}
//****************************************************************
/**
* returns the reaction cross section in mb for a given ell wave
\param l ell wave number
*/
double CAlphaOM::getSigL(int l)
{
if (l > lmax) return 0.;
return sl[l];
}
//*******************************************************************
double CAlphaOM::getXsec()
{
return xsec;
}
//***************************************************************
int CAlphaOM::getLmax()
{
return lmax;
}
//************************************************************
int CAlphaOM::getL(double random)
{
int l= 0;
for (;;)
{
if (random < prob[l]) break;
if (l == lmax ) break;
l++;
}
return l;
}
<file_sep>#include "CAvrigeanu.h"
#include <cmath>
//**************************************************
/**
* gives the global optical model potential for
* alpha particle scattering described by Avrigneau
* PRC 49 (1994) 2136
\param Z target Z
\param A target A
\param E lab energy of alpha particle
*/
void CAvrigeanu::findPara(double Z, double A, double E)
{
double A3 = pow(A,1./3.);
R = 1.245*A3;
a = 0.817 - 0.0085*A3;
V = 101.1 + 6.051*Z/A3 - 0.248*E;
Ri = 1.57*A3;
ai = 0.692-0.02*A3;
if (E < 73.) Wvol = 12.64 - 1.706*A3 + 0.2*E;
else Wvol = 26.82 - 1.706*A3 + .006*E;
Rc = 1.17*A3;
mu = A*4./(A+4.);
zz = 2.*Z;
}
<file_sep>#include "CCoul.h"
using namespace std;
//Coulomb wave functions using continued-fraction evalution of Coulomb
//Functions and their derivatives
//Journal of computational Physics 46 (1982) 171
//The values of F, G and derivative dF, and dG are correct except
//their sign may be wrong. Either all right or all the wrong sign
complex<double> CCoul::logDerH(int l, double eta, double x)
{
double const accur = 1e-33;
int const MaxIterations=2000;
double const accuh = sqrt(accur);
complex<double> one(1.,0.);
complex<double> two(2.,0.);
complex<double> out(0.,1. - eta/x);
complex<double> bb(2.*(x-eta),2.);
complex<double> aa(-pow(eta,2)- pow((double)l,2) - (double)l,eta);
complex<double> rk(0.,0.);
complex<double> wi(0.,2.*eta);
complex<double> rl(0.,1/x);
if (abSum(bb) < accuh)
{
rl *= aa/(aa + rk + wi);
out += rl*(bb+complex<double>(0.,2.));
aa += 2.*(rk + wi + one);
bb += complex<double>(0.,4.);
rk+= complex<double>(4.,0.);
}
complex<double> dd = one/bb;
complex<double> dl = aa*dd*rl;
for (;;)
{
complex<double>outOld = out;
out += dl;
rk+= two;
aa+= rk+wi;
bb+=complex<double>(0.,2.);
dd = one/(aa*dd+bb);
dl*=bb*dd-one;
//double error = abSum(dl)/abSum(out);
//cout << out << endl;
if (rk.real() > 2*MaxIterations) break;
if (abs(out-outOld) < accur) break;
}
out += dl;
return out;
}
//***********************************************
double CCoul::abSum(complex<double> x)
{
return abs(x.real()) + abs(x.imag());
}
//***********************************************
double CCoul::logDerF(int l, double eta, double x)
{
double const tiny = 1.e-30;
double const eps = 1.e-30;
double l1 = (double)l;
double l2 = l1+1.;
double S1 = l1/x + eta/l1;
double S2 = l2/x + eta/l2;
double out2 = S2;
if (out2 == 0.)out2 = tiny;
double C = out2;
double D = 0.;
for (;;)
{
double out1 = out2;
l++;
l1 = (double)l;
l2 = l1+1.;
S1 = S2;
S2 = l2/x + eta/l2;
double B = S1 + S2;
double A = -(1.+pow(eta/l1,2));
D = B + A*D;
if (D == 0.) D = tiny;
C = B + A/C;
if (C == 0.) C = tiny;
D = 1./D;
double delta = C*D;
out2 = out1*delta;
//cout << out2 << endl;
if (abs(delta-1.) < eps)break;
}
return out2;
}
//******************************************
int CCoul::init(int l, double eta, double x)
{
//double xx = eta + sqrt(pow(eta,2)+ (double)(l*(l+1)));
//if ( x < xx) cout << " x << xx= " << xx << endl;
double f = logDerF(l,eta,x);
complex<double> h = logDerH(l,eta,x);
double p = h.real();
double q = h.imag();
F = 1./sqrt(pow(f-p,2)/q + q);
dF = f*F;
G = (f-p)*F/q;
dG = p*G - q*F;
return 1;
}
<file_sep>#include "CLevelDensity.h"
CLevelDensity* CLevelDensity::fInstance = 0;
bool CLevelDensity::normal = true;
float const CLevelDensity::pi=acos(-1.);
float CLevelDensity::k0=7.3;
float CLevelDensity::kInfinity=12.;
float CLevelDensity::aKappa = 0.00517;
float CLevelDensity::cKappa = .0345;
float CLevelDensity::af_an = 1.036;
float CLevelDensity::aimf_an = 1.02;
float CLevelDensity::eFade = 18.52;
float CLevelDensity::jFade = 50.;
float CLevelDensity::Ucrit0 = 9.;
float CLevelDensity::Jcrit = 14;
//float CLevelDensity::Ucrit0 = 0.;
//float CLevelDensity::Jcrit = -1.;
/**
* Constructor
*/
CLevelDensity::CLevelDensity()
{
//constructor read in in level density parameter
string fileName("tbl/gemini.inp");
string fullName;
if (getenv("GINPUT") == NULL) fullName = fileName;
else
{
string dir(getenv("GINPUT"));
fullName = dir+fileName;
}
ifstream ifFile (fullName.c_str());
if (ifFile.fail())
{
cout << "Gemini++: unable to open gemini.inp" << endl;
return;
}
string line;
string text1;
string text2;
string text3;
string text4;
getline(ifFile,line);
ifFile >> text1 >> k0 >> text2 >> aKappa >> text3 >> cKappa >> text4
>> kInfinity;
ifFile >> text1 >> eFade >> text2 >> jFade >> text3;
ifFile >> text1 >> Ucrit0 >> text2 >> Jcrit >> text3;
ifFile.close();
ifFile.clear();
}
CLevelDensity* CLevelDensity::instance() // mod-TU
{
if (fInstance == 0) {
fInstance = new CLevelDensity;
}
return fInstance;
}
//*********************************************************************
/**
* Returns the backshifted excitation energy energy to be used in the
* Fermi gas formula for the level Density
\param fU0 is the thermal excitation energy in MeV
\param fPairing is the pairing correction in MeV
\param fShell is the shell correction in MeV
\param fJ is the angular momentum in units of hbar
*/
float CLevelDensity::getU(float fU0, float fPairing, float fShell, float fJ)
{
fU = fU0;
if (fU <= 0.)
{
fU = 0.;
return fU;
}
//simple fade out of pairing
float shiftP;
float Ucrit = 0.;
if (fJ < Jcrit) Ucrit = Ucrit0*pow(1.-fJ/Jcrit,2);
if (fU > Ucrit) shiftP = fPairing;
else shiftP = fPairing*(1.-pow(1.-fU/Ucrit,2));
fU += shiftP;
if (fU <= 0.)
{
fU = 0.;
return fU;
}
//fU += fShell*(1.0-exp(-fU/eFade-fJ/jFade));
float shiftS = fShell*tanh(fU/eFade+fJ/jFade);
fU += shiftS;
if (fU < 0.) fU = 0.;
J = fJ;
return fU;
}
//*********************************************
/**
* Returns the level-density parameter in units of MeV-1, the getU function
* must already have been called to use this version
\param iA is the mass number
\param fJ is the angular momentum in units of hbar
\param iFission is a short indicating we are detail with a saddle-point shape
*/
float CLevelDensity::getLittleA(int iA, short iFission/*=0*/)
{
//calculates the level density parameter
//iA is nucleus mass number
//fU is thermal excitation energy
//fPairing is the pairing energy
//fShell is the shell correction to the mass
float fA = (float)iA;
float kappa = 0.;
float daden_dU;
if ((normal && fU/fA < 3.) || aKappa == 0.)
{
if (k0 == kInfinity)
{
aden = fA/k0;
daden_dU = 0.;
}
else
{
if (aKappa > 0.) kappa = aKappa*exp(cKappa*fA);
//kappa = 1.5+.1143*J;
float expTerm = exp(-kappa*fU/fA/(kInfinity-k0));
aden = fA/(kInfinity - (kInfinity-k0)*expTerm);
daden_dU = -pow(aden/fA,2)*kappa*expTerm;
}
switch(iFission)
{
case 1:
aden *= af_an;
daden_dU *= af_an;
break;
case 2:
aden *= aimf_an;
daden_dU *= aimf_an;
break;
}
}
else
{
float r;
if (iFission == 1)r = 1.0696;
if (iFission == 2)r = 1.05;
else r = 1.0;
if (aKappa > 0.) kappa = aKappa*exp(cKappa*fA);
float fofr = ( kInfinity - ( kInfinity - k0 ) * r ) / (k0*r);
float expTerm = exp(-fofr*kappa*fU/fA/(kInfinity-k0));
aden = fA/(kInfinity - (kInfinity-k0)*r*expTerm);
daden_dU = -pow(aden/fA,2)*kappa*expTerm*fofr;
}
entropy = 2.*sqrt(aden*fU);
temp = sqrt(fU/aden)/(1.+fU/aden*daden_dU);
return aden;
}
//*********************************************
/**
* Returns the level-density parameter in units of MeV-1
\param iA is the mass number
\param fU0 is the thermal excitation energy in MeV
\param fPairing is the pairing correction in MeV
\param fShell is the shell correction in MeV
\param fJ is the angular momentum in units of hbar
\param iFission is a short indicating we are detail with a saddle-point shape
*/
float CLevelDensity::getLittleA(int iA, float fU0, float fPairing/*=0.*/,
float fShell/*=0.*/, float fJ/*=0.*/, short iFission/*=0*/)
{
//calculates the level density parameter
//iA is nucleus mass number
//fU is thermal excitation energy
//fPairing is the pairing energy
//fShell is the shell correction to the mass
//if (getU(fU0, fPairing,fShell,fJ) <= 0.) return 0.;
getU(fU0, fPairing,fShell,fJ);
return getLittleA(iA,iFission);
}
//************************************************
/**
* Returns the natural logrithm of the spin dependent level density in MeV-1
* if fJ < 0, then littleA is calculated taking into account the spin reduction
* of paring, but subsequentally the level density is calculated for
* zero spin. This is done when using Weisskopf formalism for evaporation.
\param iA is the mass number
\param fU0 is the thermal excitation energy in MeV
\param fPairing is the pairing energy in MeV
\param fShell is the shell correction in MeV
\param fJ is the spin in hbar
\param fMinertia is the moment of inertia in nucleon mass* fm^2
\param iFission indicates its for the saddle-point configuration
*/
//spin dependent Fermi_gas level density
float CLevelDensity::getLogLevelDensitySpherical
(int iA, float fU0, float fPairing,
float fShell, float fJ, float fMinertia, short iFission/*=0*/)
{
//calculates the level density
//iA is nucleus mass number
//fU is thermal excitation energy
//fPairing is the pairing energy
//fShell is the shell correction to the mass
if (getLittleA(iA,fU0,fPairing,fShell,fabs(fJ),iFission) == 0.) return 0.;
if (fU <=0.) return 0.;
if (fJ < 0.) fJ = 0.;
float sigma = fMinertia*temp/40.848;
float preExp = (2.*fJ+1.)/(1.+pow(fU,(float)(1.25))*pow(sigma,(float)1.5))
/pow(aden,(float)0.25)/24./sqrt(2.);
return entropy + log(preExp);
}
//******************************************
/**
* Returns the temperature in MeV
* getLittleA must be called first
*/
float CLevelDensity::getTemp()
{
return temp;
}
//*************************************
/**
* Returns the entropy.
* getLittleA must be called first
*/
float CLevelDensity::getEntropy()
{
return entropy;
}
//*************************************
/**
* Returns the level-density parameter in MeV-1
*/
float CLevelDensity::getAden()
{
return aden;
}
//************************************************
/**
* Returns the spin independent Fermi-gas level density
\param iA is the mass number
\param fU0 is the thermal excitation energy in MeV
\param fPairing is the pairing correction in MeV
\param fShell is the shell correction in MeV
*/
float CLevelDensity::getLogLevelDensitySpherical
(int iA, float fU0, float fPairing, float fShell)
{
//calculates the level density
//iA is nucleus mass number
//fU is thermal excitation energy
//fPairing is the pairing energy
//fShell is the shell correction to the mass
if (getLittleA(iA,fU0,fPairing,fShell)== 0.) return 0.;
if (fU <=0.) return 0.;
float preExp = sqrt(pi)/12./pow(aden,(float)0.25)/
(1.+pow(fU+temp,(float)1.25));
return entropy + log(preExp);
}
//***************************************************
/**
* Sets the constants for level-density parameter
* where \f$a=\frac{A}{k_{\infty} - \left(k_{\infty} -k_{0} \right) \exp\left( \frac{\kappa}{k_{\infty}-k_{0}}\frac{U}{A}\right)}\f$
* where \f$ \kappa = a_{\kappa} \exp\left(c_{\kappa} A\right) \f$.
* Note setLittleA(8.) is equivalent to \f$a=A/8\f$
\param k00 is \f$k_{0}\f$
\param aKappa0 is \f$a_{\kappa}\f$
\param cKappa0 is \f$c_{kappa}\f$
\param kInfinity0 is \f$k_{\infty}\f$
*/
void CLevelDensity::setLittleA(float k00, float aKappa0/*=0.*/,
float cKappa0 /*=0.*/, float kInfinity0 /*=12.*/)
{
k0 = k00;
aKappa = aKappa0;
cKappa = cKappa0;
kInfinity = kInfinity0;
if (aKappa == 0.) kInfinity = k0;
}
//****************************************************
/**
* returns the inverse level-density parameter at zero excitation energy
*/
float CLevelDensity::getK0()
{
return k0;
}
//************************************************************
/**
* returns the inverse level-density parameter at infinite excitation
* energy
*/
float CLevelDensity::getKInfinity()
{
return kInfinity;
}
//****************************************************
/**
* returns one of the coefficients used to calculate kappa
* \f$ \kappa = a_{\kappa} \exp\left(c_{\kappa} A\right) \f$
*/
float CLevelDensity::getAKappa()
{
return aKappa;
}
//****************************************************
/**
* returns the other coefficients used to calculate kappa
* \f$ \kappa = a_{\kappa} \exp\left(c_{\kappa} A\right) \f$
*/
float CLevelDensity::getCKappa()
{
return cKappa;
}
//*****************************************************
/**
* returns the ration of saddle-point to equilibrium level-density parameter
* for symmetyric fission
*/
float CLevelDensity::getAfAn()
{
return af_an;
}
//*****************************************************
/**
* returns the ration of saddle-point to equilibrium level-density parameter
* for asymmetric fission
*/
float CLevelDensity::getAimfAn()
{
return aimf_an;
}
//*****************************************************
/**
* set the ration of level-density paramters at the saddle-point to
* equilibrium shape for symmetric fission
\param af_an0 is the level-density parameter ratio for saddle-point to equilibirum deformation
*/
void CLevelDensity::setAfAn(float af_an0)
{
af_an = af_an0;
}
//*****************************************************
/**
* set the ration of level-density paramters at the saddle-point to
* equilibrium shape for asymmetric fisison , ie. imf emission
\param aimf_an0 is the level-density parameter ratio for saddle-point to equilibirum deformation
*/
void CLevelDensity::setAimfAn(float aimf_an0)
{
aimf_an = aimf_an0;
}
//***************************************************
/**
* writes out the values of the parameters
*/
void CLevelDensity::printParameters()
{
cout << "k0 = " << k0 << " kInfinity= " << kInfinity << endl;
cout << "aKappa= " << aKappa << " cKappa= " << cKappa << endl;
cout << "af/an= " << af_an << " for symmetric fission" <<endl;
cout << "aimf/an= " << aimf_an << " for asymmetric fission" <<endl;
cout << "eFade= " << eFade << " jFade= " << jFade << endl;
cout << "Ucrit0= " << Ucrit0 << " Jcrit= " << Jcrit << endl;
}
//***************************************************
/**
* returns the level density for a scission configuration.
* This is used for evaporation from saddle to scission and
* for determining the fission mass asymmetry
\param iA is mass number of fissioning system
\param fU is thermal excitation of fission system
\param adenInv in the inverse level-density paramter in MeV, is \f$a=A/adenInv\f$
*/
float CLevelDensity::getLogLevelDensityScission(int iA, float fU,
float adenInv/*=8.*/ )
{
aden = (float)iA/adenInv;
temp = sqrt(fU/aden);
entropy = 2.*sqrt(aden*fU);
float preExp = sqrt(pi)/12./pow(aden,(float)0.25)/
(1.+pow(fU+temp,(float)1.25));
return entropy + log(preExp);
}
//*****************************************************
/**
* set the critical thermal excitation where pairing vanishes
\param Ucrit0 is critical thermal excitaion energy in MeV
\param Jcrit is critical angular momentum where pairing vanishes
*/
void CLevelDensity::setUcrit(float Ucrit00, float Jcrit0)
{
Ucrit0 = Ucrit00;
Jcrit = Jcrit0;
}
<file_sep>#include "CLightP.h"
//! constructor which creates a CTlBarDist object
/**
\param iZ0 proton number of particle
\param iA0 mass number of particle
\param fJ0 spin of particle
\param name0 name of *.tl file containing transmission coefs.
*/
CLightP::CLightP(int iZ0, int iA0, float fJ0, string name0)
: CNuclide(iZ0,iA0,name0)
{
fJ = fJ0;
tlArray = new CTlBarDist(name0);
sigBarDist = new CSigBarDist(name0,(float)iZ0,(float)iA0);
}
//******************************************************
//! constructor which uses an existing CTlBarDist object
/**
* Alternative constructor which uses a previously defined
* transmission coeff object CTlArray
\param iZ0 proton number of particle
\param iA0 mass number of particle
\param fJ0 spin of particle
\param tlArray0 is the pointer to the object for transmission coefficients
\param sigBarDist0 is the pointer to the object for inverse xsections
*/
CLightP::CLightP(int iZ0, int iA0, float fJ0, CTlBarDist* tlArray0,
CSigBarDist * sigBarDist0)
: CNuclide(iZ0,iA0)
{
fJ = fJ0;
tlArray = tlArray0;
sigBarDist = sigBarDist0;
mustDelete = 0;
}
//*****************************************************************
/**
* Destructor
*/
CLightP::~CLightP()
{
if (mustDelete)
{
delete tlArray;
delete sigBarDist;
}
}
<file_sep>#include "CNucleus.h"
#include "TFile.h"
#include "TH1F.h"
#include "TH2F.h"
/**
*!\brief example of fusion with root histograms
*
* class that I use to simulate statistical decay in fusion
* reaction. It produces a number of histograms, such a mass, charge
* and evaporation spectra - The output is stored in root file
*/
class CRun
{
public:
CRun(int iZ, int iA, float fEx, float l0, float d0, int lmax, float plb,
int numTot,string title0,float vcm=0.,float thetaDetMin=0.,
float thetaDetMax = 360.);
};
<file_sep>#include "CTlBarDist.h"
float CTlBarDist::width=1.;
float const CTlBarDist::width0=1.5;
//****************************************************************
/**
* constructor
/param sName0 is the name of the files containing fitted coeff.
*/
CTlBarDist::CTlBarDist(string sName0)
{
string sName = sName0;
tlArray[1] = new CTlArray(sName);
sName = sName0+"P";
//see if second file is there
string fullName;
if (getenv("GINPUT") == NULL) fullName = "tl/"+sName+".tl";
else
{
string dir(getenv("GINPUT"));
fullName = dir+"tl/"+sName+".tl";
}
ifstream ifFile(fullName.c_str());
//do not include fluctuations for protons and neutrons
//The IWBC barriers do not extrapolate very well for
// high spins when the barrier is increases and we often get
//some artifacts, so its best not to include these.
if (ifFile.fail() || sName0 == "neutron" || sName0 == "proton" )
{
one = 1;
return;
}
ifFile.close();
ifFile.clear();
one = 0;
tlArray[2] = new CTlArray(sName);
sName = sName0+"M";
tlArray[0] = new CTlArray(sName);
}
//****************************************************
/**
* destructor
*/
CTlBarDist::~CTlBarDist()
{
if (one) delete tlArray[1];
else for (int i=0;i<3;i++) delete tlArray[i];
}
//******************************************************
/**
* returns the transmission coeff, including barrier distibution
/param iL is orbital angular momentum of evaporated particle
/param fEk is the kinetic energy in MeV of the evaporated particle
/param temp is the temperature in MeV of daughter
*/
float CTlBarDist::getTl(int iL, float fEk, float temp)
{
if (one || temp <= 0. || width == 0.) return tlArray[1]->getTl(iL,fEk);
if (tlArray[0]->iZMin >= iZ) return tlArray[1]->getTl(iL,fEk);
if (tlArray[2]->iZMin >= iZ) return tlArray[1]->getTl(iL,fEk);
float deltaR = sqrt(temp)*width;
float ee[3];
for (int i=0;i<3;i++) ee[i] = tlArray[i]->getTermInExp(iL,fEk);
// for proton emission light nuclei at high angular momentum,
// the parameterized
// transmission coefficients are extrapolations. For tlArray[0]
// we sometime find this extrapolation is bad, the tl value is
// larger than for tlArray[1]. tlArray[2] extrapolates better
// which is good as it defined the subbarrier behavoir
// the following if block is desigend to correct for bad extrapolations
//of tlArray[0]
if (ee[0] < ee[1])
{
double fE = fEk-1.;
double tlNew;
double tlOld = ee[2];
for(;;)
{
if (fE <= 0.) break;
tlNew = tlArray[2]->getTermInExp(iL,fE);
if (tlNew >= ee[1])break;
fE--;
tlOld = tlNew;
}
if (fE <= 0.)
{
ee[0] = 1000.;
if (ee[1] > ee[0]) ee[0] = ee[1];
}
else
{
fE -= (ee[1]-tlOld)/(tlNew-tlOld) -1.;
ee[0] = tlArray[1]->getTermInExp(iL,fE);
}
}
float c1 = (ee[2]-ee[0])/2./width0;
float c2 = (ee[2]+ee[0]-2.*ee[1])/pow(width0,2)/2.;
float Tl = 1./(1.+exp(ee[1]));
//float eee = ee[1] + deltaR*(c1 + c2*deltaR);
float eee = ee[1] + deltaR*c1 + c2*pow(deltaR,2);
Tl += 1./(1.+exp(eee));
//eee = ee[1] - deltaR*(c1 - c2*deltaR);
eee = ee[1] - deltaR*c1 + c2*pow(deltaR,2);
Tl += 1./(1.+exp(eee));
Tl /=3.;
return Tl;
}
//******************************************************
/**
* The transmission coeff is determine from the average of three
* transmission coeff. This routine returns the one of these three
* transmission coeff. with the lowest barrier
/param iL is orbital angular momentum of evaporated particle
/param fEk is the kinetic energy in MeV of the evaporated particle
/param temp is the temperature in MeV of daughter
*/
float CTlBarDist::getTlLow(int iL, float fEk, float temp)
{
if (one || temp <= 0. || width == 0.) return tlArray[1]->getTl(iL,fEk);
if (tlArray[0]->iZMin >= iZ) return tlArray[1]->getTl(iL,fEk);
if (tlArray[2]->iZMin >= iZ) return tlArray[1]->getTl(iL,fEk);
float deltaR = sqrt(temp)*width;
float ee[3];
for (int i=0;i<3;i++) ee[i] = tlArray[i]->getTermInExp(iL,fEk);
// for proton emission light nuclei at high angular momentum,
// the parameterized
// transmission coefficients are extrapolations. For tlArray[0]
// we sometime find this extrapolation is bad, the tl value is
// larger than for tlArray[1]. tlArray[2] extrapolates better
// which is good as it defined the subbarrier behavoir
// the following if block is desigend to correct for bad extrapolations
//of tlArray[0]
if (ee[0] < ee[1])
{
double fE = fEk-1.;
double tlNew;
double tlOld = ee[2];
for(;;)
{
if (fE <= 0.) break;
tlNew = tlArray[2]->getTermInExp(iL,fE);
if (tlNew >= ee[1])break;
fE--;
tlOld = tlNew;
}
if (fE <= 0.)
{
ee[0] = 1000.;
if (ee[1] > ee[0]) ee[0] = ee[1];
}
else
{
fE -= (ee[1]-tlOld)/(tlNew-tlOld) -1.;
ee[0] = tlArray[1]->getTermInExp(iL,fE);
}
}
float c1 = (ee[2]-ee[0])/2./width0;
float c2 = (ee[2]+ee[0]-2.*ee[1])/pow(width0,2)/2.;
float eee = ee[1] + deltaR*c1 + c2*pow(deltaR,2);
float Tl = 1./(1.+exp(eee));
return Tl;
}
//******************************************************
/**
* The transmission coeff is determine from the average of three
* transmission coeff. This routine returns the one of these three
* transmission coeff. with the highest barrier
/param iL is orbital angular momentum of evaporated particle
/param fEk is the kinetic energy in MeV of the evaporated particle
/param temp is the temperature in MeV of daughter
*/
float CTlBarDist::getTlHigh(int iL, float fEk, float temp)
{
if (one || temp <= 0. || width == 0.) return tlArray[1]->getTl(iL,fEk);
if (tlArray[0]->iZMin >= iZ) return tlArray[1]->getTl(iL,fEk);
if (tlArray[2]->iZMin >= iZ) return tlArray[1]->getTl(iL,fEk);
float deltaR = sqrt(temp)*width;
float ee[3];
for (int i=0;i<3;i++) ee[i] = tlArray[i]->getTermInExp(iL,fEk);
// for proton emission light nuclei at high angular momentum,
// the parameterized
// transmission coefficients are extrapolations. For tlArray[0]
// we sometime find this extrapolation is bad, the tl value is
// larger than for tlArray[1]. tlArray[2] extrapolates better
// which is good as it defined the subbarrier behavoir
// the following if block is desigend to correct for bad extrapolations
//of tlArray[0]
if (ee[0] < ee[1])
{
double fE = fEk-1.;
double tlNew;
double tlOld = ee[2];
for(;;)
{
if (fE <= 0.) break;
tlNew = tlArray[2]->getTermInExp(iL,fE);
if (tlNew >= ee[1])break;
fE--;
tlOld = tlNew;
}
if (fE <= 0.)
{
ee[0] = 1000.;
if (ee[1] > ee[0]) ee[0] = ee[1];
}
else
{
fE -= (ee[1]-tlOld)/(tlNew-tlOld) -1.;
ee[0] = tlArray[1]->getTermInExp(iL,fE);
}
}
float c1 = (ee[2]-ee[0])/2./width0;
float c2 = (ee[2]+ee[0]-2.*ee[1])/pow(width0,2)/2.;
float eee = ee[1] - deltaR*c1 + c2*pow(deltaR,2);
float Tl = 1./(1.+exp(eee));
return Tl;
}
//*******************************************
/**
* returns the quantity
* \f$S=\sum_{\ell=0}^{\infty} (2\ell+1)T_{\ell}(\varepsilon)\f$
* which is related to the inverse cross section by
* \f$S=\frac{\sigma_{inv}}{\pi\lambda^{2}}\f$
\param fEk is the kinetic energy of the evaporated particle
\param temp is temperature of daughter in MeV
*/
float CTlBarDist::getInverseXsec(float fEk, float temp)
{
float tot = 0.;
float xmax = 0.;
int iL = 0;
for(;;)
{
float x = (float)(2*iL+1)*getTl(iL,fEk,temp);
xmax = max(x,xmax);
tot += x;
if (x < xmax*.01) break;
iL++;
if (iL > 20) break;
}
return tot;
}
//**************************************************
/**
* set the parameter controlling the width of the barrier distribution
\param width00 - radial shift is \f$ \Delta R= \sqrt T* width00 \f$
*/
void CTlBarDist::setBarWidth(float width00)
{
width = width00;
}
//***************************************************
/**
* returns the parameter controlling the width of the barrier dist
*/
float CTlBarDist::getBarWidth()
{
return width;
}
//**************************************************************************
/**
* prints out the width parameter
*/
void CTlBarDist::printParameters()
{
cout << "tl barrier width parameter = " << width << endl;
}
//**************************************************************************
/**
* prepares for a series of opertions for a given iZ
/param iZ0 is proton number of daughter
*/
void CTlBarDist::prepare(int iZ0)
{
iZ = iZ0;
tlArray[1]->prepare(iZ);
if (one) return;
tlArray[0]->prepare(iZ);
tlArray[2]->prepare(iZ);
}
<file_sep>cmake_minimum_required (VERSION 2.8)
project(Gemini)
set(SOURCES Angle.cpp Fus.cpp LightP.cpp Random.cpp TlArray.cpp
AngleDist.cpp Gdr.cpp Mass.cpp Scission.cpp TlBarDist.cpp
Chart.cpp History.cpp Nucleus.cpp SigBarDist.cpp Weight.cpp
Evap.cpp LevelDensity.cpp Nuclide.cpp SigCharged.cpp Yrast.cpp)
set(HEADERS CAngleDist.h CFus.h CLightP.h CRandom.h CSigBarDist.h CWeight.h
CAngle.h CGdr.h CMass.h CRun.h CSigCharged.h CYrast.h
CChart.h CHistory.h CNucleus.h CRunThick.h CTlArray.h SStoreEvap.h
CEvap.h CLevelDensity.h CNuclide.h CScission.h CTlBarDist.h)
add_library(Gemini SHARED ${SOURCES})
set(LIB_INSTALL ${CMAKE_INSTALL_PREFIX}/lib)
set(HEAD_INSTALL ${CMAKE_INSTALL_PREFIX}/include/gemini)
set(DATA_INSTALL ${CMAKE_INSTALL_PREFIX}/share/gemini)
install(TARGETS Gemini DESTINATION ${LIB_INSTALL})
install(FILES ${HEADERS} DESTINATION ${HEAD_INSTALL})
install(DIRECTORY tbl tl DESTINATION ${DATA_INSTALL})
<file_sep>#include "CFus.h"
#include <cmath>
//the following is needed in the ROOT version
//ClassImp(CFus)
float const CFus::E=3.3;
float const CFus::H=0.65;
float const CFus::D=.03;
float const CFus::G=0.0061;
/**
* Constructor
\param plb0 is pi-lambda-squared in mb
\param dif0 is the diffuseness in hbar
*/
CFus::CFus(float plb0, float dif0)
{
plb = plb0;
dif = dif0;
}
/**
* alternative constructor
\param iZprojectile is the projectile atomic number
\param iAprojectile is projectile mass number
\param iZtarget is the target atomic number
\param iAtarget is target mass number
\param Elab is lab. energy of projectile in MeV
\param dif0 is the diffuseness in hbar
*/
CFus::CFus(int iZprojectile, int iAprojectile,
int iZtarget, int iAtarget, float Elab, float dif0)
{
iZp = iZprojectile;
iAp = iAprojectile;
iZt = iZtarget;
iAt = iAtarget;
fElab = Elab;
// mod-TU CMass mass;
CMass *mass = CMass::instance(); // mod-TU
float massProjectile= mass->getExpMass(iZprojectile,iAprojectile); // mod-TU mass now pointer
float massTarget= mass->getExpMass(iZtarget,iAtarget); // mod-TU mass now pointer
iZcn = iZprojectile + iZtarget;
iAcn = iAprojectile + iAtarget;
float massCN = mass->getExpMass(iZcn,iAcn); // mod-TU mass now pointer
float Q=massProjectile + massTarget - massCN;
Ecm = (float)iAtarget/(float)(iAtarget+iAprojectile)*Elab;
vbeam = sqrt(2.*Elab/(float)iAprojectile)*.9784;
vcm = (float)iAprojectile*vbeam/(float)(iAtarget+iAprojectile);
Ex = Ecm + Q;
float Ared = (float)(iAtarget*iAprojectile)/(float)(iAtarget+iAprojectile);
plb = 656.80/Ared/Ecm;
dif = dif0;
}
//*********************************************
/**
* reinitialization
\param plb0 is pi-lambda-squared in mb
\param dif0 is the diffuseness in hbar
*/
void CFus::init(float plb0, float dif0)
{
plb = plb0;
dif = dif0;
}
//*******************************
/**
* returns the critical amgular momentum
\param xsection is the fusion cross section in mb
*/
float CFus:: getL0(float xsection)
{
//first get the value for dif=0
float l00 = sqrt(xsection/plb)-1;
float l0 = l00;
float dl0;
for(;;)
{
int il=0;
float xsec = 0.;
float dxsec = 0.;
float maxExtra = 0.;
for (;;)
{
float fl = (float)il;
float trans = 1./(1.+exp((fl-l0)/dif));
float DtransDl0 = pow(trans,2)*exp((fl-l0)/dif)/dif;
float extra = trans*(2.*fl+1.)*plb;
if (maxExtra < extra) maxExtra = extra;
xsec += extra;
dxsec += DtransDl0*(2.*fl+1.)*plb;
if (extra < maxExtra/1000.) break;
il++;
}
float difference = xsec - xsection;
if (fabs(difference) < .1 ) break;
dl0 = -difference/dxsec;
l0 += dl0;
}
return l0;
}
//**************************************************************
/**
*returns the Bass-model potential in MeV
\param R radius in fm
\param AL is orbital angular momentum
*/
float CFus::F(float R,float AL)
{
float S= R - R12;
return A/R+B*AL*(AL+1.)/pow(R,2)-C/(D*exp(S/E)+G*exp(S/H));
}
//*************************************************
/**
*returns the derivative Bass-model potential in MeV withrespect to R
\param R radius in fm
\param AL is orbital angular momentum
*/
float CFus::FF(float R,float AL)
{
float S=R-R12;
float x =-A/pow(R,2)-2.*B*AL*(AL+1.)/pow(R,3);
return x+C*(D/E*exp(S/E)+G/H*exp(S/H))/pow(D*exp(S/E)+G*exp(S/H),2);
}
//********************************************************
/**
*returns the 2nd derivative of the Bass-model potential
* in MeV withrespect to R
\param R radius in fm
\param AL is orbital angular momentum
*/
float CFus::FFF(float R,float AL)
{
float S=R-R12;
float x=2.*A/pow(R,3)+6.*B*AL*(AL+1.)/pow(R,4);
float GGG=-2.*C*pow(D/E*exp(S/E)+G/H*exp(S/H),2);
GGG=GGG/pow(D*exp(S/E)+G*exp(S/H),3);
float HHH=C*(D/E/E*exp(S/E)+G/H/H*exp(S/H));
HHH=HHH/pow(D*exp(S/E)+G*exp(S/H),2);
return x + GGG + HHH;
}
//**********************************************************
/**
*returns the 3nd derivative of the Bass-model potential
* in MeV withrespect to R
\param R radius in fm
\param AL is orbital angular momentum
*/
float CFus::FFFF(float R, float AL)
{
float S=R-R12;
float X=-6.*A/pow(R,4)-24.*B*AL*(AL+1.)/pow(R,5);
float Y=D*exp(S/E)+G*exp(S/H);
float Z=D/E*exp(S/E)+G/H*exp(S/H);
float XX=D/E/E*exp(S/E)+G/H/H*exp(S/H);
float YY=D/pow(E,3)*exp(S/E)+G/pow(H,3)*exp(S/H);
float ZZ=-6.*C*pow(Z,3)/pow(Y,4)+6.*C*Z*XX/pow(Y,3)-C*YY/pow(Y,2);
return X-ZZ;
}
//*******************************************************
/**
* returns the critical orbital angular momentum in the Bass model
* [Nucl Phys A231 (1974) 45 ] USING THE 1977
* BASS NUCLEAR POTENTIAL [Phys Rev Letts 39 (1977) 265 ]
*
*/
float CFus::getBassL()
{
const float AF=0.75;
float AP3 = pow((float)iAp,(float)(1./3.));
float AT3 = pow((float)iAt,(float)(1./3.));
float AP = (float)iAp;
float AT = (float)iAt;
A = 1.4399*(float)(iZp*iZt);
B=20.90*(AP+AT)/(AP*AT);
float AL,R,DR,DDB=0.;
float RP=1.16*AP3-1.27/AP3;
float RT=1.16*AT3-1.27/AT3;
int MIN=0;
R12=RP+RT;
U=AP*AT/(AP+AT);
C=RP*RT/R12;
if (FF(R12,0.) < 0.)
{
CL1=0.;
return 0.;
}
else
{
CL1=sqrt(0.25+FF(R12,0.)*pow(R12,3)/(2.*B))-0.5;
if (FFF(R12,CL1) > 0.)
{
//*********** DETERMINATION OF CRITICAL L AT WHICH POCKET VANISHES***
float R=R12;
MIN= (int)CL1;
float AJ = 0.;
float FFB = 0.;
for (int J=MIN; J<=200;J++)
{
AJ= (float)J;
for (;;)
{
float DR=FFF(R,AJ)/FFFF(R,AJ);
R=R-DR;
if(fabs(DR) <= 0.00001) break;
}
if(FF(R,AJ) <0.) break;
FFB=FF(R,AJ);
}
CL1=AJ-1.+FFB/(FFB-FF(R,AJ));
// cout << " Potential at contact separation " <<
// "becomes repulsive at "<< CLO << " hbar\n" <<
// " pocket vanishes at " << CL1 << " habr" << endl;
}
//********* CALCULATION OF FUSION BARRIERS FOR EACH L VALUE**
MAX=(int) (CL1+1.);
R=R12+2.;
for (int J=1; J<= MAX; J++)
{
AL= (float) J-1;
for (;;)
{
DR=FF(R,AL)/FFF(R,AL);
R=R-DR;
if (fabs(DR) <= 0.00001) break;
}
W[J]=F(R,AL);
}
//**********DETERMINATION OF THE CRITICAL ANGULAR MOMENTUM L1 **
if (MIN > 0)
{
for ( int I=MIN; I <=MAX-1; I++)
{
float AJ= (float) I;
float DD=W[I+1]-F(R12,AJ);
if (DD < 0.)
{
CL1=AJ-1.+DDB/(DDB-DD);
break;
}
DDB=DD;
}
}
CL2=CL1/AF;
E1=F(R12,CL1);
E2=F(R12,CL2);
}
if (Ecm < W[1]) return 0.; //below the barrier
else if (Ecm > E2) return CL2;
else if (Ecm > E1) return sqrt(0.25+(Ecm-F(R12,0.))*R12*R12/B)-0.5;
else
{
int i;
for (i=1;i<MAX;i++)
{
if (W[i] > Ecm) break;
}
float DEL=W[i]-W[i-1];
return (float)(i-2)+(Ecm-W[i-1])/DEL;
}
}
//*********************************************************************
/**
* returns the Bass model fusion cross section in mb
*/
float CFus::getBassXsec()
{
float L = getBassL();
return plb*(L*L+2*L);
}
<file_sep>OBJECTS = Nucleus.o Mass.o Chart.o Yrast.o TlArray.o LevelDensity.o Angle.o Nuclide.o LightP.o Evap.o AngleDist.o Random.o TlBarDist.o Scission.o SigBarDist.o SigCharged.o Gdr.o Fus.o Run.o Weight.o RunThick.o RunAlpha.o AlphaOM.o Scatter.o Waves.o PotPara.o Merson.o Coul.o Avrigeanu.o
OBJECTS0 = Nucleus.o Mass.o Chart.o Yrast.o TlArray.o LevelDensity.o Angle.o Nuclide.o LightP.o Evap.o AngleDist.o Random.o TlBarDist.o Scission.o Gdr.o
ALLOBJECTS := $(patsubst %.cpp,%.o,$(wildcard *.cpp))
FOBJECTS:=$(patsubst %.f,%.o,$(wildcard *.f))
CFLAGS= -c -Wall -W -O2 -I$(shell root-config --incdir)
COMPILER= c++
LINKOPTION = $(shell root-config --libs)
testDecay: testDecay.o $(OBJECTS)
$(COMPILER) -o testDecay testDecay.o $(OBJECTS) $(LINKOPTION)
testFusion: testFusion.o $(OBJECTS)
$(COMPILER) -o testFusion testFusion.o $(OBJECTS) $(LINKOPTION)
fusion: fusion.o $(OBJECTS)
$(COMPILER) -o fusion fusion.o $(OBJECTS) $(LINKOPTION)
fusionThick: fusionThick.o $(OBJECTS)
$(COMPILER) -o fusionThick fusionThick.o $(OBJECTS) $(LINKOPTION)
testGemini:: testGemini.o gemini.o $(OBJECTS0)
f77 -o testGemini testGemini.o gemini.o $(OBJECTS0) -lstdc++
gemini.a: $(OBJECTS)
ar rcs gemini.a $(OBJECTS)
ranlib gemini.a
$(ALLOBJECTS): %.o : %.cpp
$(COMPILER) $(CFLAGS) $< -o $@
$(FOBJECTS): %.o : %.f
f77 $(CFLAGS) $< -o $@
clean:
rm -f *.o
| 92c7e3b4687631a87e98471a3760f5fb1ad8dc0d | [
"Markdown",
"CMake",
"C++",
"Makefile"
] | 65 | C++ | jdfrankland/gemini | e8fbfa6f60c22414695a06ef434a88033ba1046a | dfbf79a6f3c9fc24f48b3694c940487ab026fec6 |
refs/heads/master | <repo_name>tanaton/chuden_teiden<file_sep>/README.md
# chuden_teiden
[中部電力の停電情報](http://teiden.chuden.jp/p/sizuoka.html)を町名ごとにまとめて表示します。
遠州地方のみに対応しています。
個人の私的利用の範囲でお使いください。
## 使い方
1. `git clone https://github.com/tanaton/chuden_teiden.git`
1. `cd chuden_teiden`
1. `go build chuden_teiden.go`
1. `./chuden_teiden`
1. ブラウザで[http://127.0.0.1/](http://127.0.0.1/)にアクセスする
## スクリーンショット



<file_sep>/chuden_teiden.go
package main
import (
"encoding/xml"
"fmt"
"log"
"net/http"
"path"
"strings"
"sync"
"text/template"
"time"
)
const (
ServerAddr = ":80"
ChudenXmlURL = "http://teiden.chuden.jp/p/resource/xml/"
ShortForm = "2006/01/02 15:04"
HttpDir = "./public_html"
TeidenCycle = 5 * time.Minute
)
type CustomTime time.Time
type TeidenRiyu struct {
Code string `xml:"teiden_riyu_c"` // なんかJSの関数が入ってる事があるので
Naiyou string `xml:"teiden_riyu_n"`
}
type KanrenMotoEigyosho struct {
Code int `xml:"kanren_moto_eigyosho_c"`
Name string `xml:"kanren_moto_eigyosho_n"`
}
type ChomeiInfo struct {
Cond int `xml:"teisoden_cond"`
Address1 string `xml:"address1_n"`
Address2 string `xml:"address2_n,omitempty"`
Address3 string `xml:"address3_n,omitempty"`
Address4 string `xml:"address4_n,omitempty"`
}
type KoshoKenmei struct {
Type int `xml:"type,attr"`
No string `xml:"kenmei_no"`
Flag int `xml:"ijo_flg,omitempty"`
Cond int `xml:"kenmei_cond"`
TeidenHasseiDate *CustomTime `xml:"teiden_hassei_d,omitempty"`
ZensoDate *CustomTime `xml:"zenso_d,omitempty"`
ChomeiInfo []*ChomeiInfo `xml:"chomei_info,omitempty"`
HasseijiTeidenKosu int `xml:"hasseiji_teiden_kosu,omitempty"`
GenzaiTeidenKosu int `xml:"genzai_teiden_kosu"`
FukkyuMikomiDate *CustomTime `xml:"fukkyu_mikomi_d,omitempty"`
KanrenMotoEigyosho *KanrenMotoEigyosho `xml:"kanren_moto_eigyosho,omitempty"`
TeidenRiyu *TeidenRiyu `xml:"teiden_riyu,omitempty"`
}
type Eigyosho struct {
Code int `xml:"eigyosho_c"`
Name string `xml:"eigyosho_n"`
}
type TeidenInfo struct {
DataMakeDate *CustomTime `xml:"data_make_d,omitempty"`
Eigyosho *Eigyosho `xml:"eigyosho,omitempty"`
KoshoKenmei []*KoshoKenmei `xml:"kosho_kenmei,omitempty"`
}
type chudenTeidenHandle struct {
sync.RWMutex
file http.Handler
date time.Time
til []*TeidenInfo
}
type Office struct {
Code int
Name string
}
var JST = time.FixedZone("Asia/Tokyo", 9*60*60)
var Tmpl = template.Must(template.ParseFiles("ken.tmpl", "shi.tmpl", "ban.tmpl"))
var OfficeList = []int64{
250, // 浜松
255, // 細江
256, // 浜北
240, // 掛川
241, // 磐田
}
func main() {
cth := &chudenTeidenHandle{
file: http.FileServer(http.Dir(HttpDir)),
}
cth.teiden(time.Now())
go func() {
c := time.Tick(TeidenCycle)
for now := range c {
cth.teiden(now)
}
}()
h := &http.Server{
Addr: ServerAddr,
Handler: cth,
}
log.Fatal(h.ListenAndServe())
}
func (cth *chudenTeidenHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
p := path.Clean(r.URL.Path)
if p == "/" || p == "/index.html" {
// トップページが無いのでリダイレクト
http.Redirect(w, r, "/静岡県", http.StatusMovedPermanently)
} else if strings.Index(p, "/") == 0 {
q := strings.Split(p[1:], "/")
switch len(q) {
case 0:
ken := cth.ken("静岡県")
Tmpl.ExecuteTemplate(w, "ken.tmpl", &ken)
case 1:
ken := cth.ken(q[0])
Tmpl.ExecuteTemplate(w, "ken.tmpl", &ken)
case 2:
shi := cth.shi(q[0], q[1])
Tmpl.ExecuteTemplate(w, "shi.tmpl", &shi)
case 3, 4:
ban := cth.banchi(q)
Tmpl.ExecuteTemplate(w, "ban.tmpl", &ban)
default:
http.NotFound(w, r)
}
} else {
// ファイルサーバにお任せ
cth.file.ServeHTTP(w, r)
}
}
func (cth *chudenTeidenHandle) teiden(now time.Time) error {
til := []*TeidenInfo{}
for _, code := range OfficeList {
ti, err := teidenGet(code, now)
if err != nil {
continue
}
til = append(til, ti)
}
cth.Lock()
cth.til = til
cth.date = now
cth.Unlock()
return nil
}
func teidenGet(code int64, now time.Time) (*TeidenInfo, error) {
resp, err := http.Get(fmt.Sprintf("%s%d.xml?%d", ChudenXmlURL, code, now.Unix()))
if err != nil {
return nil, err
}
defer resp.Body.Close()
ti := &TeidenInfo{}
err = xml.NewDecoder(resp.Body).Decode(ti)
if err != nil {
return nil, err
}
return ti, nil
}
type Count struct {
Hassei int
Genzai int
}
type Item struct {
ChomeiInfo []*ChomeiInfo
HasseijiTeidenKosu int
GenzaiTeidenKosu int
TeidenHasseiDate string
ZensoDate string
FukkyuMikomiDate string
}
type Ken struct {
Count
Date string
Ken string
Shi map[string]struct{}
}
type Shi struct {
Count
Date string
Ken string
Shi string
Cho map[string]struct{}
}
type Loc struct {
Count
Date string
Ken string
Shi string
Cho string
Banchi string
BanchiList map[string]struct{}
Item []Item
}
func (cth *chudenTeidenHandle) ken(k string) Ken {
cth.RLock()
defer cth.RUnlock()
ken := Ken{
Date: cth.date.Format(ShortForm),
Ken: k,
Shi: map[string]struct{}{},
}
for _, ti := range cth.til {
for _, kosho := range ti.KoshoKenmei {
found := false
var chomei *ChomeiInfo
for _, chomei = range kosho.ChomeiInfo {
if chomei.Address1 == k {
found = true
if chomei.Address2 != "" {
ken.Shi[chomei.Address2] = struct{}{}
}
}
}
if found {
ken.Hassei += kosho.HasseijiTeidenKosu
ken.Genzai += kosho.GenzaiTeidenKosu
}
}
}
return ken
}
func (cth *chudenTeidenHandle) shi(k, s string) Shi {
cth.RLock()
defer cth.RUnlock()
shi := Shi{
Date: cth.date.Format(ShortForm),
Ken: k,
Shi: s,
Cho: map[string]struct{}{},
}
for _, ti := range cth.til {
for _, kosho := range ti.KoshoKenmei {
found := false
var chomei *ChomeiInfo
for _, chomei = range kosho.ChomeiInfo {
if chomei.Address1 == k && chomei.Address2 == s {
found = true
if chomei.Address3 != "" {
shi.Cho[chomei.Address3] = struct{}{}
}
}
}
if found {
shi.Hassei += kosho.HasseijiTeidenKosu
shi.Genzai += kosho.GenzaiTeidenKosu
}
}
}
return shi
}
func (cth *chudenTeidenHandle) banchi(q []string) Loc {
cth.RLock()
defer cth.RUnlock()
loc := Loc{
Date: cth.date.Format(ShortForm),
Ken: q[0],
Shi: q[1],
Cho: q[2],
BanchiList: map[string]struct{}{},
Item: []Item{},
}
for _, ti := range cth.til {
for _, kosho := range ti.KoshoKenmei {
found := false
var chomei *ChomeiInfo
for _, chomei = range kosho.ChomeiInfo {
flag := false
switch len(q) {
case 3:
if chomei.Address1 == q[0] && chomei.Address2 == q[1] && chomei.Address3 == q[2] {
flag = true
if chomei.Address4 != "" {
loc.BanchiList[chomei.Address4] = struct{}{}
}
}
default:
loc.Banchi = q[3]
if chomei.Address1 == q[0] && chomei.Address2 == q[1] && chomei.Address3 == q[2] && chomei.Address4 == q[3] {
flag = true
}
}
if flag {
found = true
}
}
if found {
loc.Hassei += kosho.HasseijiTeidenKosu
loc.Genzai += kosho.GenzaiTeidenKosu
var TeidenHasseiDate string
var ZensoDate string
var FukkyuMikomiDate string
if kosho.TeidenHasseiDate != nil {
TeidenHasseiDate = time.Time(*kosho.TeidenHasseiDate).Format(ShortForm)
}
if kosho.ZensoDate != nil {
ZensoDate = time.Time(*kosho.ZensoDate).Format(ShortForm)
}
if kosho.FukkyuMikomiDate != nil {
FukkyuMikomiDate = time.Time(*kosho.FukkyuMikomiDate).Format(ShortForm)
}
loc.Item = append(loc.Item, Item{
ChomeiInfo: kosho.ChomeiInfo,
HasseijiTeidenKosu: kosho.HasseijiTeidenKosu,
GenzaiTeidenKosu: kosho.GenzaiTeidenKosu,
TeidenHasseiDate: TeidenHasseiDate,
ZensoDate: ZensoDate,
FukkyuMikomiDate: FukkyuMikomiDate,
})
}
}
}
return loc
}
// https://stackoverflow.com/questions/17301149/golang-xml-unmarshal-and-time-time-fields
func (c *CustomTime) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var v string
xerr := d.DecodeElement(&v, &start)
if xerr != nil {
return xerr
}
parse, err := time.ParseInLocation(ShortForm, v, JST)
if err != nil {
return err
}
*c = CustomTime(parse)
return nil
}
func (c *CustomTime) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
s := time.Time(*c).Format(ShortForm)
return e.EncodeElement(s, start)
}
| 404938a07ad4cb975fd43a3954eee3cd3f19de2f | [
"Markdown",
"Go"
] | 2 | Markdown | tanaton/chuden_teiden | bb872215034c142519a24ae9c003e67dc916401b | b092424e48a60c95a94088b4dd8434dc8fb3830f |
refs/heads/master | <file_sep>Music-Clustering
================
The goal of this project is to develop algorithms to perform automatic
playlist generation via music clustering.
Given all the music on a computer we cluster the songs/artists
into k playlists such that the music in each playlist is similar.
To do so, we use data mining techniques and information about artists
from a downloaded dataset.
We use a dataset from the social music website Last.fm :
The dataset used is a Many-to-many relational database between artists
and tags (genres) imported in a MySQL database.

We implement two algorithms to perform music cluster :
1) Bag-of-words representation + k-means algorithm
--------------------------------------------------
The Bag-of-words representation constists in choosing some tags as a
basis for all the artists.
We then use the k-means algorithm to cluster the artists.
2) Weighted Jacquard distance + k-medoids algorithm
---------------------------------------------------
Artists can be seen as buckets of genres ⇒ Jacquard index : http://en.wikipedia.org/wiki/Jaccard_index
The Weighted Jacquard similarity can be computed with a SQL query (WeightedJacquard.java), we obtain a distance matrix for all our artists.
We then use the k-medoids algorithm to cluster the artits.
<file_sep>package musicClustering;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
public class Kmeans{
public static double distance(double c1[],double c2[]){
double sum=0;
for(int i=0;i<c1.length;i++){
sum+=Math.pow(c1[i]-c2[i], 2);
}
return sum;
}
public static double[] barycenter(ArrayList<Artist> artists,int dimension){
double[] b=new double[dimension];
double count=0;
for(Artist a:artists){
for(int i=0;i<dimension;i++){
b[i]+=a.coefficients[i];
}
count++;
}
for(int i=0;i<dimension;i++){
b[i]/=count;
}
return b;
}
static ArrayList<Artist>[] kmeans(Artist[] artists,int k){
int dimension=artists[0].coefficients.length;
double[][] centerPoints=new double[k][dimension];
ArrayList<Artist>[] clusters=new ArrayList[k];
for(int i=0;i<k;i++){
clusters[i]=new ArrayList<Artist>();
clusters[i].add(artists[i]);
}
for(int j=0;j<10;j++){
// We compute the center points and empty the clusters
for(int i=0;i<k;i++){
centerPoints[i]=barycenter(clusters[i],dimension);
clusters[i]=new ArrayList<Artist>();
}
// Put each artist in a cluster
for(Artist a:artists){
double minDist=a.distanceTo(centerPoints[0]);
int minDistCluster=0;
for(int i=1;i<k;i++){
double d=a.distanceTo(centerPoints[i]);
if(d<minDist){
minDist=d;
minDistCluster=i;
}
}
clusters[minDistCluster].add(a);
}
}
return clusters;
}
}
<file_sep>package musicClustering;
public class Artist {
String name;
double[] coefficients;
public Artist(String s){
name=s;
}
double distanceTo(double[] c){
double sum=0;
for(int i=0;i<coefficients.length;i++){
sum+=Math.pow(c[i]-coefficients[i], 2);
}
return sum;
}
}
<file_sep>package musicClustering;
import java.util.ArrayList;
public class Kmedoids {
static ArrayList<Artist>[] kmeans(Artist[] artists,double[][] dist,int k){
int N=dist.length;
int[] centerPoints=new int[k];
ArrayList<Integer>[] clusters=new ArrayList[k];
for(int i=0;i<k;i++){
clusters[i]=new ArrayList<Integer>();
clusters[i].add(i);
}
for(int j=0;j<20;j++){
// We compute the center points and empty the clusters
for(int i=0;i<k;i++){
centerPoints[i]=barycenter(clusters[i],dist);
clusters[i]=new ArrayList<Integer>();
}
for(int i=0;i<N;i++){
double minDist=dist[i][centerPoints[0]];
double minDistCluster=0;
for(int l=1;l<k;l++){
double d=dist[i][centerPoints[l]];
if(d<minDist){minDist=d;minDistCluster=l;}
}
clusters[(int) minDistCluster].add(i);
}
}
ArrayList<Artist>[] clustersArtist=new ArrayList[k];
int i=0;
for(ArrayList<Integer> c:clusters){
clustersArtist[i]=new ArrayList<Artist>();
for(int j:c){
clustersArtist[i].add(artists[j]);
}
i++;
}
return clustersArtist;
}
private static int barycenter(ArrayList<Integer> cluster, double[][] dist) {
// This method compute the new medoids
int N=cluster.size();
double minTotalDist=10000;
int minTotalDistIndex=-1;
for(int i:cluster){
double totalDist=0;
for(int j:cluster){
totalDist+=dist[i][j];
}
if(totalDist<minTotalDist){minTotalDist=totalDist;minTotalDistIndex=i;}
}
return minTotalDistIndex;
}
}
<file_sep>package musicClustering;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
public class DatabaseConnector {
private Connection connect = null;
Statement statement = null;
public void setConnection(String a,String b,String c) {
try{
Class.forName("com.mysql.jdbc.Driver");
connect= DriverManager.getConnection(a,b,c);
statement = connect.createStatement();
}catch(Exception e){
e.printStackTrace();
}
}
public void query(){
try {
ResultSet s=statement.executeQuery("select artist,sum(count) as c from artisttags group by artist order by c desc limit 10");
s.first();
while(!s.isAfterLast()){
System.out.println(s.getString(1));
s.next();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String[] getTopTags(String artists,int k){
String[] topTags=new String[k];
String query="select tag,sum(count) as c from artisttags where artist in ("+artists+") group by tag order by c desc limit "+k;
System.out.println(query);
try {
ResultSet s=statement.executeQuery(query);
s.first();
while(!s.isAfterLast()){
System.out.println(s.getString(1));
s.next();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return topTags;
}
}
| a345774b539588f2195f25341c17e68dea66eb63 | [
"Markdown",
"Java"
] | 5 | Markdown | guillaumedupre/Music-Clustering | 3cfb1ae43b04136060f64f2a3d4bedd66e429a7c | f18bcfbf806dedfac7257468cd499f6162704438 |
refs/heads/master | <file_sep><h3>src/simpleBean/DBConnectionMgr.java</h3>
여기에서 DB 서버 재설정
<file_sep>package simpleBean;
public class OrderBean {
private String ID;
private String name;
private String quantity;
private String buyerName;
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getBuyerName() {
return buyerName;
}
public void setBuyerName(String buyerName) {
this.buyerName = buyerName;
}
}
<file_sep>package simpleBean;
import java.io.Console;
import java.sql.*;
import java.util.*;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import com.sun.org.apache.xml.internal.resolver.helpers.Debug;
public class ItemMgr {
private DBConnectionMgr pool = null;
public ItemMgr() {
try {
pool = DBConnectionMgr.getInstance();
} catch (Exception e) {
System.out.println("Error : 커넥션 가져오기 실패!!");
}
}
public String updateQuantity(String name,String quantity)
{
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs=null;
boolean flag = false;
String oldQuantity=null;
int result=0;
String state=null;
try {
con = pool.getConnection();
String strQuery = "select quantity from item where name=?";
pstmt = con.prepareStatement(strQuery);
pstmt.setString(1, name);
rs = pstmt.executeQuery();
if (rs.next()) {
oldQuantity=rs.getString("quantity");
}
result=Integer.parseInt(oldQuantity)-Integer.parseInt(quantity);
if(result <0)
{
state="buyed too many";
return state;
}
strQuery = "update item set quantity = ? where name = ?";
pstmt = con.prepareStatement(strQuery);
pstmt.setString(1, Integer.toString(result ));
pstmt.setString(2, name);
int count = pstmt.executeUpdate();
if(count >0)
{
state="true";
}
} catch (Exception ex) {
System.out.println("Exception" + ex);
} finally {
pool.freeConnection(con, pstmt);
}
return state;
}
public boolean insertItem(ItemBean item) {
Connection con = null;
PreparedStatement pstmt = null;
boolean flag = false;
try {
con = pool.getConnection();
String strQuery = "insert into item values(?,?,?,?,?,?,?,?,?,?,?)";
pstmt = con.prepareStatement(strQuery);
pstmt.setString(1, item.getName());
pstmt.setString(2, item.getPrice());
pstmt.setString(3, item.getRelease());
pstmt.setString(4, item.getMain_category());
pstmt.setString(5, item.getSub_category());
pstmt.setString(6, item.getDesc());
pstmt.setString(7, item.getImgURL());
pstmt.setString(8, item.getIsDiscount());
pstmt.setString(9, item.getPercentage());
pstmt.setString(10, item.getIsHot());
pstmt.setString(11, item.getQuantity());
int count = pstmt.executeUpdate();
if (count == 1) {
flag = true;
}
} catch (Exception ex) {
System.out.println("Exception" + ex);
} finally {
pool.freeConnection(con, pstmt);
}
return flag;
}
public Vector getItemList(String MainOrder,String SubOrder,String curPageName)
{
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Vector vecList = new Vector();
String sub=null;
if(curPageName.equals("GIFT"))
{
sub="sub_gift";
}
else
{
sub="sub_genre";
}
if(SubOrder.equals("null"))
{
SubOrder="all";
}
if(MainOrder.equals("null"))
{
MainOrder="RECENT";
}
try {
con = pool.getConnection();
String strQuery="";
strQuery = "select item.* from item,main_platform ";
if(!SubOrder.equals("all"))
{
strQuery+=","+sub+" ";
}
strQuery+= "where item.main_category=main_platform.id ";
strQuery+="and main_platform.name=? ";
if(!SubOrder.equals("all"))
{
strQuery+="and item.sub_category="+sub+".id ";
strQuery+="and "+sub+".name=? ";
}
String IsHotSql="and item.IsHot=1 ";
String IsDiscountSql="and item.IsDiscount=1 ";
String orderbySql="order by item.release desc ";
if(MainOrder.equals("HOT"))
{
strQuery+=IsHotSql;
}
else if(MainOrder.equals("DISCOUNT"))
{
strQuery+=IsDiscountSql;
}
strQuery+=orderbySql;
pstmt=con.prepareStatement(strQuery);
pstmt.setString(1, curPageName);
if(!SubOrder.equals("all"))
{
pstmt.setString(2, SubOrder);
}
rs = pstmt.executeQuery();
while (rs.next()) {
ItemBean itemBean = new ItemBean();
itemBean.setName(rs.getString("name"));
itemBean.setPrice(rs.getString("price"));
itemBean.setRelease(rs.getString("release"));
itemBean.setMain_category(rs.getString("main_category"));
itemBean.setSub_category(rs.getString("sub_category"));
itemBean.setDesc(rs.getString("desc"));
itemBean.setImgURL(rs.getString("imgURL"));
itemBean.setIsDiscount(rs.getString("IsDiscount"));
itemBean.setPercentage(rs.getString("percentage"));
itemBean.setIsHot(rs.getString("IsHot"));
itemBean.setQuantity(rs.getString("quantity"));
vecList.add(itemBean);
}
} catch (Exception ex) {
System.out.println("Exception" + ex);
} finally {
pool.freeConnection(con, pstmt, rs);
}
return vecList;
}
public ItemBean getItemInfo(String ItemName)
{
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ItemBean item = null;
try {
con = pool.getConnection();
String strQuery = "select * from item where name=?";
pstmt = con.prepareStatement(strQuery);
pstmt.setString(1, ItemName);
rs = pstmt.executeQuery();
if (rs.next()) {
item = new ItemBean();
item.setName(rs.getString("name"));
item.setPrice(rs.getString("price"));
item.setRelease(rs.getString("release"));
item.setMain_category(rs.getString("main_category"));
item.setSub_category(rs.getString("sub_category"));
item.setDesc(rs.getString("desc"));
item.setImgURL(rs.getString("imgURL"));
item.setIsDiscount(rs.getString("IsDiscount"));
item.setPercentage(rs.getString("percentage"));
item.setIsHot(rs.getString("IsHot"));
item.setQuantity(rs.getString("quantity"));
}
} catch (Exception ex) {
System.out.println("Exception" + ex);
} finally {
pool.freeConnection(con, pstmt, rs);
}
return item;
}
}
<file_sep>package simpleBean;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
public class SubmitMgr {
private DBConnectionMgr pool = null;
public SubmitMgr() {
try {
pool = DBConnectionMgr.getInstance();
} catch (Exception e) {
System.out.println("Error : 커넥션 가져오기 실패!!");
}
}
public boolean removeSubmit(String title)
{
Connection con = null;
PreparedStatement pstmt = null;
boolean flag = false;
try {
con = pool.getConnection();
String strQuery = "DELETE FROM gameshop.submit WHERE title=?";
pstmt = con.prepareStatement(strQuery);
pstmt.setString(1, title);
int count = pstmt.executeUpdate();
if (count == 1) {
flag = true;
}
} catch (Exception ex) {
System.out.println("Exception" + ex);
} finally {
pool.freeConnection(con, pstmt);
}
return flag;
}
public boolean addSubmit(SubmitBean submit,int isNotice)
{
Connection con = null;
PreparedStatement pstmt = null;
boolean flag = false;
ResultSet rs=null;
int num=0;
try {
con = pool.getConnection();
String strQuery = "select * from submit";
pstmt = con.prepareStatement(strQuery);
rs = pstmt.executeQuery();
rs.last();
num=rs.getRow();
num++;
strQuery = "INSERT INTO `gameshop`.`submit` (`num`, `title`, `content`,`isNotice`) VALUES (?,?,?,?)";
pstmt = con.prepareStatement(strQuery);
pstmt.setString(1, Integer.toString(num));
pstmt.setString(2, submit.getTitle());
pstmt.setString(3, submit.getContent());
pstmt.setString(4, Integer.toString(isNotice));
int count = pstmt.executeUpdate();
if (count == 1) {
flag = true;
}
} catch (Exception ex) {
System.out.println("Exception" + ex);
} finally {
pool.freeConnection(con, pstmt);
}
return flag;
}
public Vector getSubmitList(int isNotice)
{
Vector list=new Vector();
SubmitBean submitBean=null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs=null;
try {
con = pool.getConnection();
String strQuery = "select * from submit where isNotice = ?";
pstmt = con.prepareStatement(strQuery);
pstmt.setString(1, Integer.toString(isNotice));
rs = pstmt.executeQuery();
while(rs.next())
{
submitBean=new SubmitBean();
submitBean.setTitle(rs.getString("title"));
submitBean.setContent(rs.getString("content"));
list.add(submitBean);
}
}catch (Exception ex) {
System.out.println("Exception" + ex);
} finally {
pool.freeConnection(con, pstmt);
}
return list;
}
}
<file_sep>package simpleBean;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
public class OrderMgr {
private DBConnectionMgr pool = null;
public OrderMgr()
{
try {
pool = DBConnectionMgr.getInstance();
} catch (Exception e) {
System.out.println("Error : 커넥션 가져오기 실패!!");
}
}
public boolean insertOrder(OrderBean order) {
Connection con = null;
PreparedStatement pstmt = null;
boolean flag = false;
ResultSet rs=null;
int num=0;
try {
con = pool.getConnection();
String strQuery = "select * from itemorder";
pstmt = con.prepareStatement(strQuery);
rs = pstmt.executeQuery();
rs.last();
num=rs.getRow();
num++;
strQuery = "INSERT INTO `gameshop`.`itemorder` "
+ "(`num`, `ID`, `name`, `quantity`, `buyerName`) VALUES (?, ?, ?, ?, ?)";
pstmt = con.prepareStatement(strQuery);
pstmt.setString(1, Integer.toString(num));
pstmt.setString(2, order.getID());
pstmt.setString(3, order.getName());
pstmt.setString(4, order.getQuantity());
pstmt.setString(5, order.getBuyerName());
int count = pstmt.executeUpdate();
if (count == 1) {
flag = true;
}
} catch (Exception ex) {
System.out.println("Exception" + ex);
} finally {
pool.freeConnection(con, pstmt);
}
return flag;
}
public Vector getOrderList(String ID)
{
Vector list=new Vector();
OrderBean orderBean=null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs=null;
try {
con = pool.getConnection();
String strQuery = "select * from itemorder where ID = ?";
pstmt = con.prepareStatement(strQuery);
pstmt.setString(1, ID);
rs = pstmt.executeQuery();
while(rs.next())
{
orderBean=new OrderBean();
orderBean.setID(ID);
orderBean.setBuyerName(rs.getString("buyerName"));
orderBean.setName(rs.getString("name"));
orderBean.setQuantity(rs.getString("quantity"));
list.add(orderBean);
}
}catch (Exception ex) {
System.out.println("Exception" + ex);
} finally {
pool.freeConnection(con, pstmt);
}
return list;
}
}
<file_sep>package simpleBean;
public class ItemBean {
private String name;
private String price;
private String release;
private String main_category;
private String sub_category;
private String desc;
private String imgURL;
private String IsDiscount;
private String percentage;
private String IsHot;
private String quantity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getRelease() {
return release;
}
public void setRelease(String release) {
this.release = release;
}
public String getMain_category() {
return main_category;
}
public void setMain_category(String main_category) {
this.main_category = main_category;
}
public String getSub_category() {
return sub_category;
}
public void setSub_category(String sub_category) {
this.sub_category = sub_category;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImgURL() {
return imgURL;
}
public void setImgURL(String imgURL) {
this.imgURL = imgURL;
}
public String getIsDiscount() {
return IsDiscount;
}
public void setIsDiscount(String isDiscount) {
IsDiscount = isDiscount;
}
public String getPercentage() {
return percentage;
}
public void setPercentage(String percentage) {
this.percentage = percentage;
}
public String getIsHot() {
return IsHot;
}
public void setIsHot(String isHot) {
IsHot = isHot;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
}
| 12336b8e41a2e2c7debe3556791848b3daf78061 | [
"Markdown",
"Java"
] | 6 | Markdown | RamRam-V/dyUniv__AJH__jspWebproj | ee7d3a8d9c5bc1c4199f97d48826f9ea4bf529fe | d343e109b4f894709d12c9b86c9642a5e7109ed2 |
refs/heads/master | <repo_name>sarah-Abdulaziz/spot_price<file_sep>/naive.py
# -*- coding: utf-8 -*-
"""
Created on Sun May 21 11:58:57 2017
@author: sara
"""
from pandas import Series
import glob
from sklearn.metrics import mean_squared_error
from math import sqrt
import numpy as np
def file_name():
p="/*.2xlarge_linux"
mypath=r'path'
allFiles = glob.glob(mypath + p)
result=list()
file_list=list()
for files in allFiles:
FilesName=files.split('m4')
FileName=FilesName[1]
readfiles= Series.from_csv(files ,header =0 )
df=readfiles.values
train=df[:2879]
until= len(df)-12
sumArmse=list()
for _ in df:
train=df[:len(train)+1]
test = df[len(train):len(train)+12]
if len(train) == until:
break
# print (FileName,len(train),len(test))
window = train[-1:]
predictions =[window]*12
rmse = sqrt(mean_squared_error(test, predictions))
sumArmse.append(rmse)
result_ave = np.average(sumArmse)
result.append(result_ave)
file_list.append(FileName)
with open(r'file name', 'wb') as outfile:
for i in range(len(result)) :
out_list =" "
out_list += file_list[i] + ", the RMSE is : " + str(result[i])+"\n"
out_list += "\n"
outfile.write( out_list )
outfile.close()
file_name()
<file_sep>/arima.py
# -*- coding: utf-8 -*-
"""
Created on Sat May 06 04:42:44 2017
@author: sara
"""
import pandas as pd
import glob
from sklearn.metrics import mean_squared_error
from math import sqrt
from pandas import datetime
#from matplotlib import pyplot
from statsmodels.tsa.arima_model import ARIMA
import numpy as np
def parser(x):
return datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
def file_name():
p="/*.2xlarge_linux"
mypath=r'2x'
allFiles = glob.glob(mypath + p)
result=list()
traning=list()
file_list=list()
for files in allFiles:
FilesName=files.split('.')
FileName=FilesName[0]
readfiles= pd.read_csv(files ,header =0 ,parse_dates=[0], index_col=0,squeeze=True, date_parser=parser)
df=readfiles.values
train=df[:2879]
until= len(df)-12
sumArmse=list()
sumtraning=list()
for _ in df:
train=df[:len(train)+1]
test = df[len(train):len(train)+12]
if len(train) == until:
break
history = [x for x in train]
model = ARIMA(history, order=(0,1,1)).fit(disp=0)
print len(train)
history.pop(0)
train_output=np.asarray(model.fittedvalues)
history=np.asarray(history)
traning_error=sqrt(mean_squared_error(history, train_output))
sumtraning.append(traning_error)
output = model.forecast(steps=12)
yhat= output[0]
rmse = sqrt(mean_squared_error(test, yhat))
sumArmse.append(rmse)
result_ave = np.average(sumArmse)
result.append(result_ave)
result_train=np.average(sumtraning)
traning.append(result_train)
file_list.append(FileName)
with open('2xrmse/m011output.txt', 'w') as outfile:
for i in range(len(result)) :
out_list =" "
out_list += file_list[i] + ", the RMSE is : " + str(result[i]) +"training error : "+ str(traning[i])
out_list += "\n"
outfile.write( out_list )
outfile.close()
file_name()
| dbbc55cfd849713c95cd00b3f7b9c654be14d777 | [
"Python"
] | 2 | Python | sarah-Abdulaziz/spot_price | 2c93d578b92b2497400949015f555dec0dd3df49 | 8edb5a5a6af81d5282f74406bc11d2132e5a55cc |
refs/heads/master | <file_sep>
describe( 'Triangle', function() {
it("checks if is a triangle", function() {
var testTriangle = new Triangle(12,12,12);
expect(testTriangle.isTriangle( ) ).to.equal(true)
});
it("checks if is NOT a triangle", function() {
var testTriangle = new Triangle(3,3,12);
expect(testTriangle.isTriangle( ) ).to.equal(false)
});
it("checks if is a equilateral triangle", function() {
var testTriangle = new Triangle(12,12,12);
expect(testTriangle.equilateral( ) ).to.equal(true)
});
it("checks if is a scalene triangle", function() {
var testTriangle = new Triangle(12,12,8);
expect(testTriangle.isosceles( ) ).to.equal(true)
});
it("checks if is a isosceles triangle", function() {
var testTriangle = new Triangle(8,10,11);
expect(testTriangle.scalene( ) ).to.equal(true)
});
});<file_sep>/*
equilateral: all sides are equal;
isosceles: exactly 2 sides are equal;
scalene: no sides are equal.
NOT a triangle: the sum of the lengths of any two sides of a triangle is less than or equal to the length of the third side.
*/
function Triangle( x, y, z ) {
this.x = parseInt( x );
this.y = parseInt( y );
this.z = parseInt( z );
}
Triangle.prototype.isTriangle = function( ) {
if( this.x + this.y > this.z && this.y + this.z > this.x && this.z + this.x > this.y )
{
return true;
}
return false;
}
Triangle.prototype.equilateral = function( ) {
if( this.x == this.y && this.z == this.x && this.z == this.y )
{
return true;
}
return false;
}
Triangle.prototype.isosceles = function( ) {
if( this.x == this.y || this.y == this.x || this.x == this.z )
{
return true;
}
return false;
}
Triangle.prototype.scalene = function( ) {
if( this.x != this.y && this.z != this.x && this.z != this.y )
{
return true;
}
return false;
}
$(document).ready( function( ) {
$("form#triangle").submit( function(event) {
event.preventDefault( );
var x = $("#new-triangle-x").val( );
var y = $("#new-triangle-y").val( );
var z = $("#new-triangle-z").val( );
var checkTriangle = new Triangle(x, y, z);
console.log( checkTriangle.isTriangle( ) );
if( checkTriangle.isTriangle( ) )
{
if( checkTriangle.equilateral( ) )
{
$("ul#triangles").append("<li><span class='year'>" + "Equilateral Triangle" + "</span></li>" );
}
else if( checkTriangle.isosceles( ) )
{
$("ul#triangles").append("<li><span class='year'>" + "Isosceles Triangle" + "</span></li>" );
}
else if( checkTriangle.scalene( ) )
{
$("ul#triangles").append("<li><span class='year'>" + "Scalene Triangle" + "</span></li>" );
}
}
else
{
$("ul#triangles").append("<li><span class='year'>" + "NOT A TRIANGLE" + "</span></li>" );
}
});
}); | f7e783ea111c3f13024a3552543ced06a4f82149 | [
"JavaScript"
] | 2 | JavaScript | Vawx/javascript_Triangle | 09a5b8b188aaefc57fcf7c627e7f9943de01f351 | ea3cfe24d8f4ee38eee501f917839bf422dab982 |
refs/heads/master | <repo_name>pepedeka/shaka-player-embedded<file_sep>/shaka/include/shaka/js_manager.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_MANAGER_H_
#define SHAKA_EMBEDDED_JS_MANAGER_H_
#include <memory>
#include <string>
#include "async_results.h"
#include "macros.h"
namespace shaka {
class JsManagerImpl;
/**
* @defgroup exported Public Types
* Types exported by the library.
*/
/**
* @defgroup externs JavaScript Externs
* @ingroup exported
* Types defined in the JavaScript player and exposed directly.
*/
/**
* @defgroup player Player Types
* @ingroup exported
* Types use for media playback.
*/
/**
* Manages the JavaScript engine. There must be exactly one instance per
* program. This manages a single V8 instance, but can support any number
* of Player or Video instances.
*
* @ingroup player
*/
class SHAKA_EXPORT JsManager final {
public:
struct StartupOptions final {
// This type is stack allocated, so the size is part of the public ABI;
// fields can't be added without breaking compatibility.
/**
* The path to store persistent data (e.g. IndexedDB data). This directory
* needs write access, but can be initially empty. It is assumed that we
* have complete control over this directory (i.e. other programs won't
* create/modify files here).
*
* If the path is relative, then it is relative to the working directory.
*/
std::string dynamic_data_dir;
/**
* The path to static library data (e.g. shaka-player.compiled.js). This
* directory only needs read access.
*
* See |is_static_relative_to_bundle| for handling of relative paths.
*/
std::string static_data_dir;
/**
* If set, then |static_data_dir| is relative to the iOS app bundle,
* otherwise the path is relative to the working directory. This flag is
* ignored for non-iOS targets (always relative to working directory).
*/
bool is_static_relative_to_bundle = false;
};
JsManager();
JsManager(const StartupOptions& options);
JsManager(JsManager&&);
JsManager(const JsManager&) = delete;
~JsManager();
JsManager& operator=(JsManager&&);
JsManager& operator=(const JsManager&) = delete;
/**
* Stops the JavaScript engine and all background threads. It is invalid
* to call any methods on this class after this returns.
*/
void Stop();
/**
* Blocks the current thread until all scheduled work is finished. This is
* used by the tests to detect when they are done. This should not be called
* if there are alive Player instances as they use setInterval which means
* there will always be pending work.
*/
void WaitUntilFinished();
/**
* Executes the given script in JavaScript. This can be used to register
* plugins or to run tests. This cannot be called after Stop(). The script
* will be scheduled to run on the event loop.
*/
AsyncResults<void> RunScript(const std::string& path);
private:
std::unique_ptr<JsManagerImpl> impl_;
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_JS_MANAGER_H_
<file_sep>/shaka/src/media/base_frame.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_BASE_FRAME_H_
#define SHAKA_EMBEDDED_MEDIA_BASE_FRAME_H_
#include "src/util/macros.h"
namespace shaka {
namespace media {
enum class FrameType {
Unknown,
FFmpegEncodedFrame,
FFmpegDecodedFrame,
};
/**
* This is the base class for a single media frame. This contains common fields
* between the encoded frames and the decoded frames. These frames are created
* by the Demuxer/Decoder and given to Stream. Stream then maintains the
* lifetime of the object. See Stream for more info.
*/
class BaseFrame {
public:
BaseFrame(double pts, double dts, double duration, bool is_key_frame);
virtual ~BaseFrame();
NON_COPYABLE_OR_MOVABLE_TYPE(BaseFrame);
/**
* This gets the type of frame stored. This is used to assert that the
* correct frame types are being used.
*/
virtual FrameType frame_type() const;
/** @return An estimate of the number of bytes of memory this frame uses. */
virtual size_t EstimateSize() const;
const double pts;
const double dts;
const double duration;
const bool is_key_frame;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_BASE_FRAME_H_
<file_sep>/shaka/src/js/js_error.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/js_error.h"
#include "src/core/ref_ptr.h"
#include "src/js/dom/dom_exception.h"
#include "src/mapping/convert_js.h"
namespace shaka {
namespace js {
namespace {
#if defined(USING_JSC)
ReturnVal<JsValue> CreateError(const std::string& message,
const std::string& type) {
JSContextRef cx = GetContext();
JSValueRef ctor = GetMemberRaw(JSContextGetGlobalObject(cx), type);
Handle<JsString> str(JsStringFromUtf8(message));
JSValueRef args[] = {JSValueMakeString(GetContext(), str)};
return JSObjectCallAsConstructor(cx, UnsafeJsCast<JsObject>(ctor), 1, args,
nullptr);
}
#endif
} // namespace
std::string JsError::GetJsStack() {
#if defined(USING_V8)
v8::Local<v8::String> empty = v8::String::Empty(GetIsolate());
v8::Local<v8::Value> except = v8::Exception::Error(empty);
CHECK(!except.IsEmpty());
DCHECK(except->IsObject());
return ConvertToString(GetMemberRaw(except.As<v8::Object>(), "stack"));
#elif defined(USING_JSC)
// TODO: Get the call stack.
return "";
#endif
}
JsError JsError::RangeError(const std::string& message) {
#if defined(USING_V8)
return JsError(v8::Exception::RangeError(JsStringFromUtf8(message)));
#elif defined(USING_JSC)
return JsError(CreateError(message, "RangeError"));
#endif
}
JsError JsError::ReferenceError(const std::string& message) {
#if defined(USING_V8)
return JsError(v8::Exception::ReferenceError(JsStringFromUtf8(message)));
#elif defined(USING_JSC)
return JsError(CreateError(message, "ReferenceError"));
#endif
}
JsError JsError::TypeError(const std::string& message) {
#if defined(USING_V8)
return JsError(v8::Exception::TypeError(JsStringFromUtf8(message)));
#elif defined(USING_JSC)
return JsError(CreateError(message, "TypeError"));
#endif
}
JsError JsError::SyntaxError(const std::string& message) {
#if defined(USING_V8)
return JsError(v8::Exception::SyntaxError(JsStringFromUtf8(message)));
#elif defined(USING_JSC)
return JsError(CreateError(message, "SyntaxError"));
#endif
}
JsError JsError::Error(const std::string& message) {
#if defined(USING_V8)
return JsError(v8::Exception::Error(JsStringFromUtf8(message)));
#elif defined(USING_JSC)
return JsError(CreateError(message, "Error"));
#endif
}
#ifdef USING_V8
JsError JsError::Rethrow(const v8::TryCatch& trycatch) {
return JsError(trycatch.Exception());
}
#endif
JsError JsError::DOMException(ExceptionCode code) {
// Careful here. We are creating a new object but we won't hold a reference
// to it. We are running on the event thread, so a GC run cannot happen yet.
// We will throw the wrapper which will keep the object alive.
RefPtr<dom::DOMException> except = new dom::DOMException(code);
except->stack = GetJsStack();
return JsError(except->JsThis());
}
JsError JsError::DOMException(ExceptionCode code, const std::string& message) {
RefPtr<dom::DOMException> except = new dom::DOMException(code, message);
except->stack = GetJsStack();
return JsError(except->JsThis());
}
JsError::JsError(ReturnVal<JsValue> error) : error_(error) {}
JsError::JsError(JsError&&) = default;
JsError::~JsError() {}
} // namespace js
} // namespace shaka
<file_sep>/shaka/src/media/video_renderer.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/video_renderer.h"
#include <algorithm>
#include <utility>
#include "src/media/stream.h"
namespace shaka {
namespace media {
namespace {
/** The minimum delay, in seconds, to delay between drawing frames. */
constexpr const double kMinDelay = 1.0 / 120;
/** The maximum delay, in seconds, to delay between drawing frames. */
constexpr const double kMaxDelay = 1.0 / 15;
} // namespace
VideoRenderer::VideoRenderer(std::function<double()> get_time, Stream* stream)
: mutex_("VideoRenderer"),
stream_(stream),
get_time_(std::move(get_time)),
drawer_(new FrameDrawer),
prev_time_(-1),
is_seeking_(false) {}
VideoRenderer::~VideoRenderer() {}
Frame VideoRenderer::DrawFrame(int* dropped_frame_count, bool* is_new_frame,
double* delay) {
std::unique_lock<Mutex> lock(mutex_);
// Discard any old frames, except when seeking.
if (!is_seeking_ && prev_time_ >= 0)
stream_->GetDecodedFrames()->Remove(0, prev_time_ - 0.2);
// TODO: Could this usage cause a deadlock? If a remove() is started after
// ideal_frame is locked, the remove() will block and getting next_frame
// will wait for remove().
const double time = get_time_();
// If we are seeking, use the previous frame so we display the same frame
// while the seek is happening.
auto ideal_frame = is_seeking_ && prev_time_ >= 0
? stream_->GetDecodedFrames()->GetFrameNear(prev_time_)
: stream_->GetDecodedFrames()->GetFrameNear(time);
if (!ideal_frame)
return Frame();
// TODO: Consider changing effective playback rate to speed up video when
// behind. This makes playback smoother at the cost of being more complicated
// and sacrificing AV sync.
auto next_frame =
stream_->GetDecodedFrames()->GetFrameAfter(ideal_frame->pts);
const double total_delay = next_frame ? next_frame->pts - time : 0;
*delay = std::max(std::min(total_delay, kMaxDelay), kMinDelay);
*is_new_frame = prev_time_ != ideal_frame->pts;
if (!is_seeking_) {
if (prev_time_ >= 0) {
*dropped_frame_count = stream_->GetDecodedFrames()->FramesBetween(
prev_time_, ideal_frame->pts);
}
prev_time_ = ideal_frame->pts;
}
return drawer_->DrawFrame(ideal_frame.get());
}
void VideoRenderer::OnSeek() {
std::unique_lock<Mutex> lock(mutex_);
is_seeking_ = true;
}
void VideoRenderer::OnSeekDone() {
std::unique_lock<Mutex> lock(mutex_);
is_seeking_ = false;
prev_time_ = -1;
// Now that the seek is done, discard frames from the previous time while
// keeping the newly decoded frames. Don't discard too close to current time
// since we might discard frames that were just decoded.
const double time = get_time_();
stream_->GetDecodedFrames()->Remove(0, time - 1);
stream_->GetDecodedFrames()->Remove(time + 1, HUGE_VAL);
}
void VideoRenderer::SetDrawerForTesting(std::unique_ptr<FrameDrawer> drawer) {
std::unique_lock<Mutex> lock(mutex_);
swap(drawer_, drawer);
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/js/test_type.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
// Allow struct fields so we can test the GC. This should only be used in this
// file since struct fields should not be used normally. This must appear
// before the headers so this is defined when register_member.h is included.
#define ALLOW_STRUCT_FIELDS
#include "src/js/test_type.h"
#include <utility>
#include "src/core/js_manager_impl.h"
#include "src/js/console.h"
#include "src/memory/heap_tracer.h"
namespace shaka {
namespace js {
namespace {
struct ResolvePromise : public memory::Traceable {
explicit ResolvePromise(Promise p) : promise_(p) {}
void Trace(memory::HeapTracer* tracer) const override {
tracer->Trace(&promise_);
}
void operator()() {
LocalVar<JsValue> value(JsUndefined());
promise_.ResolveWith(value);
}
private:
Promise promise_;
};
std::string GetExpectedString() {
// Since this contains embedded nulls, we can't use the normal char*
// constructor. Instead use the size of the array to get the length of the
// string literal and subtract one for the ending '\0'.
return std::string(EXPECTED_STRING,
EXPECTED_STRING + sizeof(EXPECTED_STRING) - 1);
}
} // namespace
TestType::TestType() : int_or_object(0) {}
// \cond Doxygen_Skip
TestType::~TestType() {}
// \endcond Doxygen_Skip
void TestType::Trace(memory::HeapTracer* tracer) const {
BackingObject::Trace(tracer);
tracer->Trace(&optional_object);
tracer->Trace(&int_or_object);
tracer->Trace(&struct_);
tracer->Trace(&array);
tracer->Trace(&callback);
tracer->Trace(&any);
tracer->Trace(&buffer);
}
bool TestType::IsExpectedString(const std::string& arg) const {
return arg == GetExpectedString();
}
bool TestType::IsOptionalPresent(optional<std::string> arg) const {
return arg.has_value();
}
bool TestType::IsExpectedIntWithOr(variant<int, Any> arg) const {
return holds_alternative<int>(arg) && get<int>(arg) == EXPECTED_INT;
}
bool TestType::IsExpectedStructWithOr(variant<int, TestTypeOptions> arg) const {
return holds_alternative<TestTypeOptions>(arg) &&
IsExpectedConvertedStruct(get<TestTypeOptions>(arg));
}
bool TestType::IsExpectedConvertedStruct(TestTypeOptions opts) const {
return opts.string == GetExpectedString() && opts.boolean;
}
bool TestType::IsConvertedStructEmpty(TestTypeOptions opts) const {
return opts.string.empty() && !opts.boolean;
}
bool TestType::IsExpectedNumberEnum(TestNumberEnum e) const {
return e == EXPECTED_NUMBER_ENUM;
}
bool TestType::IsExpectedStringEnum(TestStringEnum e) const {
return e == EXPECTED_STRING_ENUM;
}
bool TestType::IsExpectedArrayOfStrings(
const std::vector<std::string>& data) const {
return data == GetArrayOfStrings();
}
bool TestType::IsExpectedStringWithAny(Any anything) const {
std::string str;
return anything.TryConvertTo(&str) && str == GetExpectedString();
}
bool TestType::IsTruthy(Any anything) const {
return anything.IsTruthy();
}
void TestType::InvokeCallbackWithString(Callback callback) const {
Callback call_copy = // NOLINT(performance-unnecessary-copy-initialization)
callback;
call_copy(GetExpectedString());
}
void TestType::StoreByteBuffer(ByteBuffer buffer) {
this->buffer = std::move(buffer);
}
ExceptionOr<void> TestType::ThrowException(const std::string& message) const {
return JsError::Error(message);
}
Promise TestType::PromiseAcceptString(const std::string& /* value */) const {
LocalVar<JsValue> value(JsUndefined());
return Promise::Resolved(value);
}
Promise TestType::PromiseResolveWith(Any value) const {
LocalVar<JsValue> rooted(value.ToJsValue());
return Promise::Resolved(rooted);
}
Promise TestType::PromiseResolveAfter(uint64_t delay) const {
Promise ret;
JsManagerImpl::Instance()->MainThread()->AddTimer(delay, ResolvePromise(ret));
return ret;
}
std::string TestType::GetString() const {
return GetExpectedString();
}
optional<std::string> TestType::GetOptionalString(bool has_value) const {
if (!has_value)
return nullopt;
return GetExpectedString();
}
variant<int, std::string> TestType::GetIntOrString(bool get_int) const {
if (get_int)
return EXPECTED_INT;
return GetExpectedString();
}
TestTypeOptions TestType::GetStruct() const {
TestTypeOptions ret;
ret.string = GetExpectedString();
ret.boolean = true;
return ret;
}
TestNumberEnum TestType::GetNumberEnum() const {
return EXPECTED_NUMBER_ENUM;
}
TestStringEnum TestType::GetStringEnum() const {
return EXPECTED_STRING_ENUM;
}
std::vector<std::string> TestType::GetArrayOfStrings() const {
return {"abc", "123", GetExpectedString()};
}
std::unordered_map<std::string, std::string> TestType::GetMapOfStrings() const {
std::unordered_map<std::string, std::string> ret;
ret["a"] = "1";
ret["b"] = "2";
return ret;
}
const ByteBuffer& TestType::GetByteBuffer() const {
return buffer;
}
std::string TestType::ToPrettyString(Any anything) const {
LocalVar<JsValue> value = anything.ToJsValue();
return Console::ConvertToPrettyString(value);
}
TestTypeFactory::TestTypeFactory() {
AddMemberFunction("acceptNumber", &TestType::AcceptNumber);
AddMemberFunction("acceptBoolean", &TestType::AcceptBoolean);
AddMemberFunction("acceptString", &TestType::AcceptString);
AddMemberFunction("acceptOptionalString", &TestType::AcceptOptionalString);
AddMemberFunction("acceptOptionalStruct", &TestType::AcceptOptionalStruct);
AddMemberFunction("acceptIntOrStruct", &TestType::AcceptIntOrStruct);
AddMemberFunction("acceptStringEnumOrAnyNumber",
&TestType::AcceptStringEnumOrAnyNumber);
AddMemberFunction("acceptStruct", &TestType::AcceptStruct);
AddMemberFunction("acceptNumberEnum", &TestType::AcceptNumberEnum);
AddMemberFunction("acceptStringEnum", &TestType::AcceptStringEnum);
AddMemberFunction("acceptArrayOfStrings", &TestType::AcceptArrayOfStrings);
AddMemberFunction("acceptCallback", &TestType::AcceptCallback);
AddMemberFunction("acceptAnything", &TestType::AcceptAnything);
AddMemberFunction("acceptByteBuffer", &TestType::AcceptByteBuffer);
AddMemberFunction("isExpectedString", &TestType::IsExpectedString);
AddMemberFunction("isOptionalPresent", &TestType::IsOptionalPresent);
AddMemberFunction("isExpectedIntWithOr", &TestType::IsExpectedIntWithOr);
AddMemberFunction("isExpectedStructWithOr",
&TestType::IsExpectedStructWithOr);
AddMemberFunction("isExpectedConvertedStruct",
&TestType::IsExpectedConvertedStruct);
AddMemberFunction("isConvertedStructEmpty",
&TestType::IsConvertedStructEmpty);
AddMemberFunction("isExpectedNumberEnum", &TestType::IsExpectedNumberEnum);
AddMemberFunction("isExpectedStringEnum", &TestType::IsExpectedStringEnum);
AddMemberFunction("isExpectedArrayOfStrings",
&TestType::IsExpectedArrayOfStrings);
AddMemberFunction("isExpectedStringWithAny",
&TestType::IsExpectedStringWithAny);
AddMemberFunction("isTruthy", &TestType::IsTruthy);
AddMemberFunction("invokeCallbackWithString",
&TestType::InvokeCallbackWithString);
AddMemberFunction("storeByteBuffer", &TestType::StoreByteBuffer);
AddMemberFunction("throwException", &TestType::ThrowException);
AddMemberFunction("promiseAcceptString", &TestType::PromiseAcceptString);
AddMemberFunction("promiseResolveWith", &TestType::PromiseResolveWith);
AddMemberFunction("promiseResolveAfter", &TestType::PromiseResolveAfter);
AddMemberFunction("getString", &TestType::GetString);
AddMemberFunction("getOptionalString", &TestType::GetOptionalString);
AddMemberFunction("getIntOrString", &TestType::GetIntOrString);
AddMemberFunction("getStruct", &TestType::GetStruct);
AddMemberFunction("getNumberEnum", &TestType::GetNumberEnum);
AddMemberFunction("getStringEnum", &TestType::GetStringEnum);
AddMemberFunction("getArrayOfStrings", &TestType::GetArrayOfStrings);
AddMemberFunction("getMapOfStrings", &TestType::GetMapOfStrings);
AddMemberFunction("getByteBuffer", &TestType::GetByteBuffer);
AddMemberFunction("toPrettyString", &TestType::ToPrettyString);
AddReadWriteProperty("optionalObject", &TestType::optional_object);
AddReadWriteProperty("intOrObject", &TestType::int_or_object);
AddReadWriteProperty("struct", &TestType::struct_);
AddReadWriteProperty("array", &TestType::array);
AddReadWriteProperty("callback", &TestType::callback);
AddReadWriteProperty("any", &TestType::any);
AddReadWriteProperty("buffer", &TestType::buffer);
}
} // namespace js
} // namespace shaka
<file_sep>/shaka/tools/webidl/tests/types_test.py
#!/usr/bin/python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
import unittest
from . import test_common
from webidl import parser
class TypesTest(test_common.TestBase):
def _parse_type(self, code):
"""Returns the parsed type."""
results = self.parser.parse('', 'dictionary F {%s foo;};' % code)
self.assertEqual(1, len(results.types))
self.assertEqual(1, len(results.types[0].attributes))
self.assertEqual('foo', results.types[0].attributes[0].name)
return results.types[0].attributes[0].type
def test_simple_types(self):
types = [
'foo',
'any',
'DOMString',
'long',
'long long',
'unsigned long',
'unsigned long long',
'short',
'double',
'unrestricted double',
]
for name in types:
t = self._parse_type(name)
self.assertEqual(name, t.name)
self.assertIs(t.nullable, False)
self.assertIs(t.element_type, None)
def test_nullable(self):
t = self._parse_type('foo?')
self.assertEqual('foo', t.name)
self.assertIs(t.nullable, True)
self.assertIs(t.element_type, None)
def test_sequence(self):
t = self._parse_type('sequence<Foo>')
self.assertEqual('sequence', t.name)
self.assertIs(t.nullable, False)
self.assertTrue(t.element_type)
self.assertEqual('Foo', t.element_type.name)
self.assertIs(t.element_type.nullable, False)
self.assertIs(t.element_type.element_type, None)
def test_sequence_nullable(self):
t = self._parse_type('sequence<Foo>?')
self.assertIs(t.nullable, True)
self.assertIs(t.element_type.nullable, False)
def test_sequence_nullable_inner(self):
t = self._parse_type('sequence<Foo?>')
self.assertIs(t.nullable, False)
self.assertIs(t.element_type.nullable, True)
def test_frozen_array(self):
t = self._parse_type('FrozenArray<Foo>')
self.assertEqual('FrozenArray', t.name)
self.assertTrue(t.element_type)
self.assertEqual('Foo', t.element_type.name)
def test_promise(self):
t = self._parse_type('Promise<Foo>')
self.assertEqual('Promise', t.name)
self.assertTrue(t.element_type)
self.assertEqual('Foo', t.element_type.name)
def test_promise_void(self):
t = self._parse_type('Promise<void>')
self.assertEqual('Promise', t.name)
self.assertTrue(t.element_type)
self.assertEqual('void', t.element_type.name)
def test_syntax_error(self):
bad_code = [
'',
'void',
'unsigned',
'unsigned float',
'unsigned unsigned long',
'long unsigned',
'unrestricted long',
'unrestricted unsigned float',
'float unrestricted',
'double??',
'?double',
'Promise<double>?',
'Promise',
'Promise<double',
'Promise<>',
'Promise<?>',
'sequence<void>',
'FrozenArray<void>',
'MyType<float>',
]
for code in bad_code:
with self.assertRaises(parser.IdlSyntaxError):
self._parse_type(code)
if __name__ == '__main__':
unittest.main()
<file_sep>/shaka/src/mapping/backing_object_factory.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MAPPING_BACKING_OBJECT_FACTORY_H_
#define SHAKA_EMBEDDED_MAPPING_BACKING_OBJECT_FACTORY_H_
#include <glog/logging.h>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include "src/core/ref_ptr.h"
#include "src/js/events/event_names.h"
#include "src/mapping/exception_or.h"
#include "src/mapping/js_wrappers.h"
#include "src/mapping/register_member.h"
#include "src/mapping/struct.h"
#include "src/util/pseudo_singleton.h"
#include "src/util/templates.h"
namespace shaka {
class BackingObject;
#ifdef USING_V8
using NativeCtor = void (*)(const v8::FunctionCallbackInfo<v8::Value>&);
#elif defined(USING_JSC)
using NativeCtor = JSObjectRef (*)(JSContextRef, JSObjectRef, size_t,
const JSValueRef*, JSValueRef*);
#endif
namespace impl {
/**
* A helper class that handles indexing a JavaScript object. Having this
* interface allows the factory to store a pointer to this. This is required
* since the types of the members are only known inside the AddIndexer method.
*/
class IndexerHandler {
public:
virtual ~IndexerHandler() {}
virtual ReturnVal<JsValue> GetIndex(Handle<JsObject> that, size_t index) = 0;
virtual void SetIndex(Handle<JsObject> that, size_t index,
Handle<JsValue> value) = 0;
};
template <typename This, typename T>
class IndexerHandlerImpl : public IndexerHandler {
public:
IndexerHandlerImpl(const std::string& type_name,
bool (This::*get)(size_t, T*) const,
void (This::*set)(size_t, T))
: type_name_(type_name), get_(get), set_(set) {}
ReturnVal<JsValue> GetIndex(Handle<JsObject> that, size_t index) override {
RefPtr<T> obj;
if (!obj.TryConvert(that)) {
ThrowError</* ReturnPromise */ false>::IllegalInvocation(
nullptr, "indexer", type_name_);
return JsUndefined();
}
T value;
if (!((obj.get())->*get_)(index, &value))
return JsUndefined(); // Not found.
return ToJsValue(value);
}
void SetIndex(Handle<JsObject> that, size_t index,
Handle<JsValue> given) override {
RefPtr<T> obj;
if (!obj.TryConvert(that)) {
ThrowError</* ReturnPromise */ false>::IllegalInvocation(
nullptr, "indexer", type_name_);
return;
}
if (!set_) {
ThrowError</* ReturnPromise */ false>::General(
nullptr, "indexer", type_name_,
"Indexer on '" + type_name_ + "' is read-only.");
return;
}
T value;
if (!FromJsValue(given, &value)) {
ThrowError</* ReturnPromise */ false>::CannotConvert(
nullptr, "indexer", type_name_, ConvertToString(given),
TypeName<T>::name());
return;
}
((obj.get())->*set_)(index, std::move(value));
}
private:
const std::string type_name_;
bool (This::*get_)(size_t, T*) const;
void (This::*set_)(size_t, T);
};
} // namespace impl
namespace util {
#ifdef USING_JSC
template <>
struct RefTypeTraits<JSClassRef> {
// The API docs for JSClassCreate says it follows the "Create" rule, which
// suggests we shouldn't have to acquire; however, if we don't, we will
// occasionally get crashes that appear like the class is getting deleted
// while we reference it. Setting this to true seems to workaround it.
// TODO: Investigate this further and fix or file a bug.
static constexpr const bool AcquireWithRaw = true;
static JSClassRef Duplicate(JSClassRef arg) {
if (arg)
return JSClassRetain(arg);
else
return nullptr;
}
static void Release(JSClassRef arg) {
if (arg)
JSClassRelease(arg);
}
};
#endif
} // namespace util
/**
* A base type that defines a factory that creates BackingObject instances.
* This has several helper methods to register member functions and properties.
*
* For each type exposed to JavaScript, create one type that inherits from
* BackingObject that defines members that will be exposed to Javascript and a
* factory that inherits from BackingObjectFactory<T> for the object type T.
* The factory constructor should call methods defined here to register the
* member pointers of the object.
*
* The type T must define one namespace item:
* - A constexpr name field containing the name of the type.
* - An optional static Create method.
*/
class BackingObjectFactoryBase {
public:
virtual ~BackingObjectFactoryBase();
/** @return The name of the type being generated. */
const std::string& name() const {
return type_name_;
}
/** @return The base factory for the base type of this object, or nullptr. */
const BackingObjectFactoryBase* base() const {
return base_;
}
/** @return The value containing the constructor function. */
ReturnVal<JsValue> GetConstructor() const {
return RawToJsValue(Handle<JsFunction>(constructor_));
}
#if defined(USING_JSC)
JSClassRef GetClass() const {
return class_definition_;
}
#endif
/**
* @return Whether the objects being generated are derived from the given
* type. Note that this returns true if name() is passed.
*/
bool DerivedFrom(const std::string& name) const;
/**
* Wraps the given backing instance in a JavaScript object. This is can
* only be called on the event thread. The argument is assumed to be
* of the correct type.
*/
ReturnVal<JsValue> WrapInstance(BackingObject* object);
/**
* This is called when an object created by this factory is indexed.
* @param that The JavaScript value |this|.
* @param index The index that was requested.
* @return The value at that index, or |undefined|.
*/
ReturnVal<JsValue> GetIndex(Handle<JsObject> that, size_t index);
/**
* This is called when an object created by this factory is indexed.
* @param that The JavaScript value |this|.
* @param index The index that was requested.
* @param value The value that was set to.
*/
void SetIndex(Handle<JsObject> that, size_t index, Handle<JsValue> value);
protected:
BackingObjectFactoryBase(const std::string& name, NativeCtor ctor,
const BackingObjectFactoryBase* base);
template <typename Callback>
void AddMemberFunction(const std::string& name, Callback callback) {
LocalVar<JsFunction> js_function =
CreateMemberFunction(type_name_, name, MakeMemFn<void>(callback));
LocalVar<JsValue> value(RawToJsValue(js_function));
SetMemberRaw(prototype_, name, value);
}
template <typename Ret, typename... Args>
void AddStaticFunction(const std::string& name, Ret (*callback)(Args...)) {
LocalVar<JsFunction> js_function = CreateStaticFunction(
type_name_, name, std::function<Ret(Args...)>(callback));
LocalVar<JsValue> value(RawToJsValue(js_function));
SetMemberRaw(constructor_, name, value);
}
/**
* Registers a field that is the on- listener for the given event. You MUST
* call AddListenerField in the object's constructor ALSO.
*/
template <typename Prop>
void AddListenerField(js::EventType type, Prop member) {
AddReadWriteProperty("on" + to_string(type), member);
}
template <typename This, typename Prop>
void AddReadOnlyProperty(const std::string& name, Prop This::*member) {
#ifndef ALLOW_STRUCT_FIELDS
static_assert(
!std::is_base_of<Struct, typename std::decay<Prop>::type>::value,
"Cannot store Structs in fields");
#endif
std::function<Prop&(RefPtr<This>)> getter =
[=](RefPtr<This> that) -> Prop& { return that.get()->*member; };
LocalVar<JsFunction> js_getter =
CreateMemberFunction(type_name_, "get_" + name, getter);
LocalVar<JsFunction> setter;
SetGenericPropertyRaw(prototype_, name, js_getter, setter);
}
template <typename This, typename Prop>
void AddReadWriteProperty(const std::string& name, Prop This::*member) {
#ifndef ALLOW_STRUCT_FIELDS
static_assert(
!std::is_base_of<Struct, typename std::decay<Prop>::type>::value,
"Cannot store Structs in fields");
#endif
std::function<Prop&(RefPtr<This>)> getter =
[=](RefPtr<This> that) -> Prop& { return that->*member; };
LocalVar<JsFunction> js_getter =
CreateMemberFunction(type_name_, "get_" + name, getter);
std::function<void(RefPtr<This>, Prop)> setter = [=](RefPtr<This> that,
Prop value) {
that->*member = std::move(value);
};
LocalVar<JsFunction> js_setter =
CreateMemberFunction(type_name_, "set_" + name, setter);
SetGenericPropertyRaw(prototype_, name, js_getter, js_setter);
}
template <typename Derived = void, typename This = void,
typename GetProp = void>
void AddGenericProperty(const std::string& name,
GetProp (This::*get)() const) {
LocalVar<JsFunction> getter = CreateMemberFunction(
type_name_, "get_" + name, MakeMemFn<Derived>(get));
LocalVar<JsFunction> setter;
SetGenericPropertyRaw(prototype_, name, getter, setter);
}
template <typename Derived = void, typename This = void,
typename GetProp = void, typename SetProp = void,
typename SetPropRet = void>
void AddGenericProperty(const std::string& name, GetProp (This::*get)() const,
SetPropRet (This::*set)(SetProp)) {
// Use two different types so the setter can accept a const-reference.
static_assert(util::decay_is_same<GetProp, SetProp>::value,
"Getter and setter must use the same type.");
static_assert(std::is_same<void, SetPropRet>::value ||
std::is_same<ExceptionOr<void>, SetPropRet>::value,
"Setter can only return void.");
LocalVar<JsFunction> getter = CreateMemberFunction(
type_name_, "get_" + name, MakeMemFn<Derived>(get));
LocalVar<JsFunction> setter = CreateMemberFunction(
type_name_, "set_" + name, MakeMemFn<Derived>(set));
SetGenericPropertyRaw(prototype_, name, getter, setter);
}
template <typename T>
void AddConstant(const std::string& name, T value) {
LocalVar<JsValue> js_value = ToJsValue(value);
SetMemberRaw(prototype_, name, js_value);
SetMemberRaw(constructor_, name, js_value);
}
template <typename This, typename T>
void AddIndexer(bool (This::*get)(size_t, T*) const,
void (This::*set)(size_t, T) = nullptr) {
CHECK(!indexer_);
indexer_.reset(new impl::IndexerHandlerImpl<This, T>(type_name_, get, set));
}
void NotImplemented(const std::string& name);
private:
template <typename Derived, typename This>
using get_this = typename std::conditional<std::is_same<Derived, void>::value,
This, Derived>::type;
template <typename Derived, typename Callback>
struct MakeMemFnImpl;
template <typename Derived, typename This, typename Ret, typename... Args>
struct MakeMemFnImpl<Derived, Ret (This::*)(Args...)> {
using ArgThis = get_this<Derived, This>;
using type = std::function<Ret(RefPtr<ArgThis>, Args...)>;
static type Make(Ret (This::*callback)(Args...)) {
return [=](RefPtr<ArgThis> that, Args... args) -> Ret {
return ((that.get())->*(callback))(std::move(args)...);
};
}
};
template <typename Derived, typename This, typename Ret, typename... Args>
struct MakeMemFnImpl<Derived, Ret (This::*)(Args...) const> {
using ArgThis = get_this<Derived, This>;
using type = std::function<Ret(RefPtr<ArgThis>, Args...)>;
static type Make(Ret (This::*callback)(Args...) const) {
return [=](RefPtr<ArgThis> that, Args... args) -> Ret {
return ((that.get())->*(callback))(std::move(args)...);
};
}
};
template <typename Derived, typename Callback>
static typename MakeMemFnImpl<Derived, Callback>::type MakeMemFn(
Callback callback) {
return MakeMemFnImpl<Derived, Callback>::Make(callback);
}
const std::string type_name_;
const BackingObjectFactoryBase* const base_;
std::unique_ptr<impl::IndexerHandler> indexer_;
Global<JsFunction> constructor_;
Global<JsObject> prototype_;
#ifdef USING_V8
Global<v8::FunctionTemplate> class_definition_;
#elif defined(USING_JSC)
JSClassDefinition definition_;
util::CFRef<JSClassRef> class_definition_;
#endif
};
/**
* An intermediate type that allows getting the singleton instance for a given
* BackingObject type. The instance can't be stored in BackingObjectFactory
* since doing so would require knowing the base type. To be able to be used
* in this way, it is valid to use the Instance() method when T is void, but it
* is invalid to create an instance when T is void.
*/
template <typename T>
class BackingObjectFactoryRegistry
: public BackingObjectFactoryBase,
private PseudoSingleton<BackingObjectFactoryRegistry<T>> {
public:
explicit BackingObjectFactoryRegistry(BackingObjectFactoryBase* base)
: BackingObjectFactoryBase(T::name(), &impl::JsConstructor<T>::Call,
base) {}
/**
* Returns the instance of the factory that will generate objects of type T.
* Instance() will CHECK for the value not being null. There is a
* specialization below for T == void so this will still return null on that
* case.
*/
static BackingObjectFactoryBase* CheckedInstance() {
return BackingObjectFactoryRegistry::Instance();
}
private:
friend class PseudoSingleton<BackingObjectFactoryRegistry<T>>;
};
template <>
inline BackingObjectFactoryBase*
BackingObjectFactoryRegistry<void>::CheckedInstance() {
return nullptr;
}
template <typename T, typename Base = void>
class BackingObjectFactory : public BackingObjectFactoryRegistry<T> {
public:
BackingObjectFactory()
: BackingObjectFactoryRegistry<T>(
BackingObjectFactoryRegistry<Base>::CheckedInstance()) {}
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_MAPPING_BACKING_OBJECT_FACTORY_H_
<file_sep>/shaka/include/shaka/eme/implementation.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_EME_IMPLEMENTATION_H_
#define SHAKA_EMBEDDED_EME_IMPLEMENTATION_H_
#include <functional>
#include <string>
#include <vector>
#include "../macros.h"
#include "configuration.h"
#include "data.h"
#include "eme_promise.h"
namespace shaka {
namespace eme {
/**
* Defines a pair of a key ID and its key status.
* @ingroup eme
*/
struct SHAKA_EXPORT KeyStatusInfo final {
KeyStatusInfo();
KeyStatusInfo(const std::vector<uint8_t>& key_id, MediaKeyStatus status);
// Needed to satisfy Chromium-style.
KeyStatusInfo(KeyStatusInfo&&);
KeyStatusInfo(const KeyStatusInfo&);
KeyStatusInfo& operator=(KeyStatusInfo&&);
KeyStatusInfo& operator=(const KeyStatusInfo&);
~KeyStatusInfo();
std::vector<uint8_t> key_id;
MediaKeyStatus status;
};
inline KeyStatusInfo::KeyStatusInfo() : status(MediaKeyStatus::Usable) {}
inline KeyStatusInfo::KeyStatusInfo(const std::vector<uint8_t>& key_id,
MediaKeyStatus status)
: key_id(std::move(key_id)), status(status) {}
inline KeyStatusInfo::KeyStatusInfo(KeyStatusInfo&&) = default;
inline KeyStatusInfo::KeyStatusInfo(const KeyStatusInfo&) = default;
inline KeyStatusInfo& KeyStatusInfo::operator=(KeyStatusInfo&&) = default;
inline KeyStatusInfo& KeyStatusInfo::operator=(const KeyStatusInfo&) = default;
inline KeyStatusInfo::~KeyStatusInfo() {}
/**
* An interface for an EME implementation instance. This represents an adapter
* to a CDM instance. This is a one-to-one mapping to a MediaKeys object in
* EME. This should create and manage a single CDM instance. This object must
* remain alive until the Destroy() method is called.
*
* This can spawn background threads as needed to monitor the system. These
* thread(s) must be deleted inside Destroy().
*
* It is ok to manipulate the filesystem, but it should be done inside the
* ImplementationHelper::DataPathPrefix directory.
*
* Many of the actions here are asynchronous. Some are completed by the end
* of the call here, but are run asynchronously with respect to JavaScript. In
* either case, those methods are given a |promise|. Once the operation is
* complete (error or success), one of the methods on it MUST be called.
* It is ok to synchronously call those methods.
*
* @ingroup eme
*/
class SHAKA_EXPORT Implementation {
public:
// Since this is intended to be subclassed by the app, this type cannot be
// changed without breaking ABI compatibility. This includes adding
// new virtual methods.
virtual ~Implementation();
/**
* Destroys the object and frees up any memory (including |*this|). This will
* be called when the respective EME instances are garbage collected.
*/
virtual void Destroy() = 0;
/**
* Gets the expiration of the session. This should give the time in
* milliseconds since the epoch, or -1 if the session never expires.
*
* @param session_id The ID of the session to get the expiration for.
* @param expiration [OUT] Where to put the expiration time.
* @returns True on success, false on error.
*/
virtual bool GetExpiration(const std::string& session_id,
int64_t* expiration) const = 0;
/**
* Gets the status of each key in the given session. These values can be
* cached to avoid extra overhead. This means that the key status may have
* changed but not be reflected yet (e.g. they may have expired).
*
* @param session_id The ID of the session to query.
* @param statuses [OUT] Where to put the resulting statuses.
* @returns True on success, false on error.
*/
virtual bool GetKeyStatuses(const std::string& session_id,
std::vector<KeyStatusInfo>* statuses) const = 0;
/**
* Sets the server certificate for the CDM.
*
* This should use EmePromise::ResolveWith() and pass true for supported and
* false for not supported. This should only reject for errors in the
* certificate.
*
* @param promise The Promise object.
* @param cert The data contents of the certificate.
*/
virtual void SetServerCertificate(EmePromise promise, Data cert) = 0;
/**
* This method creates a new session and generates a license request. This
* is only called for new session, not for loading persistent sessions.
*
* This should call @a set_session_id before sending any messages so the
* session ID is set. The function must only be called once.
*
* This method should create a message to send the license request. This will
* only be called with init data types where
* ImplementationFactory::SupportsInitDataType() returns true.
*
* The Promise should be resolved when the request has been generated, NOT
* when the response comes back. This should call
* ImplementationHelper::OnMessage() before resolving the Promise.
*
* There are situations where this may not generate the license request
* immediately, for example if the device isn't provisioned. This will still
* generate a message, but it may not be a license request.
*
* @param promise The Promise object.
* @param set_session_id A function that accepts the session ID of the new
* session.
* @param session_type The type of session to create.
* @param init_data_type The type of init data given
* @param data The data contents of the request.
*/
virtual void CreateSessionAndGenerateRequest(
EmePromise promise,
std::function<void(const std::string&)> set_session_id,
MediaKeySessionType session_type, MediaKeyInitDataType init_data_type,
Data data) = 0;
/**
* Loads the given session from persistent storage.
*
* This should use ResolveWith() and pass true if the session was found, false
* if the session didn't exist. This should still reject for errors.
*
* @param session_id The session ID to load.
* @param promise The Promise object.
*/
virtual void Load(const std::string& session_id, EmePromise promise) = 0;
/**
* Updates the given session with a response from the server.
*
* @param session_id The session ID to use.
* @param promise The Promise object.
* @param data The data contents of the response.
*/
virtual void Update(const std::string& session_id, EmePromise promise,
Data data) = 0;
/**
* Closes the given session. This does NOT delete persistent sessions, it
* only closes the current running session and any runtime data.
*
* @param session_id The session ID to close.
* @param promise The Promise object.
*/
virtual void Close(const std::string& session_id, EmePromise promise) = 0;
/**
* Removes any persistent data associated with the given session.
*
* This should generate a 'license-release' message. The session should not
* actually be deleted until the response is given to Update(). However, the
* Promise should be resolved once the message is generated.
*
* @param session_id The session ID to delete.
* @param promise The Promise object.
*/
virtual void Remove(const std::string& session_id, EmePromise promise) = 0;
/**
* Decrypts the given data. This is only passed encrypted data, any clear
* data is ignored. This method doesn't need to handle containers or codecs,
* all it needs to do is decrypt the data. If the data needs to be processed
* before decryption (e.g. for MPEG2-TS), it is done by the caller.
*
* If pattern is (0, 0), then this is not using pattern encryption (e.g. for
* "cenc" or "cbc1").
*
* If not using subsample encryption, |block_offset| should always be 0.
* Otherwise, the first subsample in a sample should use 0. Then for each
* subsample it should increment by |data_size| and mod by 16.
*
* @param scheme The encryption scheme used to decrypt the data.
* @param pattern The encryption pattern.
* @param block_offset The offset within the AES block, only used for
* subsample encryption.
* @param key_id The ID of the key to use.
* @param key_id_size The number of bytes in |key_id|, will always be 16.
* @param iv The initialization vector.
* @param iv_size The number of bytes in |iv|, will always be 16.
* @param data The data to decrypt.
* @param data_size The size of |data|.
* @param dest The destination buffer to hold the decrypted data. Is at least
* |data_size| bytes large.
* @returns The resulting status code.
*/
virtual DecryptStatus Decrypt(EncryptionScheme scheme,
EncryptionPattern pattern,
uint32_t block_offset, const uint8_t* key_id,
size_t key_id_size, const uint8_t* iv,
size_t iv_size, const uint8_t* data,
size_t data_size, uint8_t* dest) const = 0;
};
} // namespace eme
} // namespace shaka
#endif // SHAKA_EMBEDDED_EME_IMPLEMENTATION_H_
<file_sep>/shaka/include/shaka/player.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_PLAYER_H_
#define SHAKA_EMBEDDED_PLAYER_H_
#include <math.h>
#include <memory>
#include <string>
#include <type_traits>
#include "async_results.h"
#include "error.h"
#include "js_manager.h"
#include "macros.h"
#include "manifest.h"
#include "player_externs.h"
#include "stats.h"
#include "track.h"
#include "video.h"
namespace shaka {
/** @ingroup player */
struct DefaultValueType final {};
/**
* A signal value used to set a configuration value to the default value.
* @ingroup player
*/
extern SHAKA_EXPORT const DefaultValueType DefaultValue;
/**
* Represents a JavaScript shaka.Player instance. This handles loading
* manifests and changing tracks.
*
* @ingroup player
*/
class SHAKA_EXPORT Player final {
public:
/**
* Defines an interface for listening for Player events. These callbacks are
* invoked on a background thread by the Player object.
*/
class Client {
public:
Client();
Client(const Client&);
Client(Client&&);
virtual ~Client();
Client& operator=(const Client&);
Client& operator=(Client&&);
/**
* Called when an error occurs asynchronously.
* @param error The error that occurred.
*/
virtual void OnError(const Error& error);
/**
* Called when the current buffering state changes.
* @param is_buffering Whether we are currently in a buffering state.
*/
virtual void OnBuffering(bool is_buffering);
};
/**
* Creates a new Player instance.
* @param engine The JavaScript engine to use.
*/
Player(JsManager* engine);
Player(const Player&) = delete;
Player(Player&&);
~Player();
Player& operator=(const Player&) = delete;
Player& operator=(Player&&);
enum class LogLevel : uint8_t {
// These have the same values as shaka.log.Level.
None = 0,
Error = 1,
Warning = 2,
Info = 3,
Debug = 4,
V1 = 5,
V2 = 6,
};
/**
* Sets the log level of the JavaScript Shaka Player. This only works if the
* Shaka Player JS file is a debug build.
*
* @param engine The JavaScript engine to use.
* @param level The log level to set to.
*/
static AsyncResults<void> SetLogLevel(JsManager* engine, LogLevel level);
/**
* Gets the log level of the Shaka Player JavaScript.
*
* @param engine The JavaScript engine to use.
* @return A future to the log level.
*/
static AsyncResults<LogLevel> GetLogLevel(JsManager* engine);
/**
* Gets the version string of the Shaka Player JavaScript.
*
* @param engine The JavaScript engine to use.
* @return A future to the version string.
*/
static AsyncResults<std::string> GetPlayerVersion(JsManager* engine);
/**
* Initializes the Player instance to play video from the given element. This
* must be called once before any other method.
*
* This is given a callback for asynchronous errors. This callback will be
* invoked on a background thread. This thread is also the JavaScript event
* loop, so it is important not to block the call for long. This also means
* you cannot make calls on Player or Video since it would deadlock.
*
* @param video The video element to output to.
* @param client The client that handles asynchronous events.
*/
AsyncResults<void> Initialize(Video* video, Client* client);
/**
* Destroys the contained Player instance. This is called automatically in
* the destructor, but calling it explicitly allows for handling of possible
* errors.
*/
AsyncResults<void> Destroy();
/** @return A future to whether the stream is currently audio-only. */
AsyncResults<bool> IsAudioOnly() const;
/** @return A future to whether the Player is in a buffering state. */
AsyncResults<bool> IsBuffering() const;
/** @return A future to whether the stream is an in-progress recording. */
AsyncResults<bool> IsInProgress() const;
/** @return A future to whether the stream is live. */
AsyncResults<bool> IsLive() const;
/** @return A future to whether the text track is visible. */
AsyncResults<bool> IsTextTrackVisible() const;
/** @return A future to whether we are using an embedded text tracks. */
AsyncResults<bool> UsingEmbeddedTextTrack() const;
/** @return A future to the manifest URI given to load(), or null. */
AsyncResults<optional<std::string>> AssetUri() const;
/**
* @return A future to the DrmInfo used to initialize EME. This returns null
* when not using EME.
*/
AsyncResults<optional<DrmInfo>> DrmInfo() const;
/**
* @return A future to list of audio language-role combinations available for
* the current Period.
*/
AsyncResults<std::vector<LanguageRole>> GetAudioLanguagesAndRoles() const;
/** @return A future to the current buffered ranges. */
AsyncResults<BufferedInfo> GetBufferedInfo() const;
/**
* @return A future to the next known expiration time of any EME sessions.
* This returns Infinity if there are no sessions or they never expire.
*/
AsyncResults<double> GetExpiration() const;
/** Return playback and adaptation stats. */
AsyncResults<Stats> GetStats() const;
/**
* Return a list of text tracks available for the current Period. If there are
* multiple Periods, then you must seek to the Period before being able to
* switch.
*/
AsyncResults<std::vector<Track>> GetTextTracks() const;
/**
* Return a list of variant tracks available for the current Period. If there
* are multiple Periods, then you must seek to the Period before being able to
* switch.
*/
AsyncResults<std::vector<Track>> GetVariantTracks() const;
/**
* @return A future to list of text language-role combinations available for
* the current Period.
*/
AsyncResults<std::vector<LanguageRole>> GetTextLanguagesAndRoles() const;
/**
* @return A future to the key system name being used by EME, or the empty
* string if not using EME.
*/
AsyncResults<std::string> KeySystem() const;
/** @return A future to the currently seekable range. */
AsyncResults<BufferedRange> SeekRange() const;
/**
* Loads the given manifest. Returns a future that will resolve when the
* load is complete.
*
* @param manifest_uri The URI of the manifest to load.
* @param start_time The time to start playing at, in seconds.
*/
AsyncResults<void> Load(const std::string& manifest_uri,
double start_time = NAN);
/** Unload the current manifest and make the Player available for re-use. */
AsyncResults<void> Unload();
//@{
/**
* Sets a configuration value on the Player instance. This is simply
* forwarded to the JavaScript instance. No error is returned if the
* requested configuration isn't present or is an invalid type, see the logs
* for errors. The path is a '.' separated list of names to reach the
* configuration. For example:
*
* 'abr.enabled' => {abr: {enabled: value}}
*
* @return A future to whether the configuration path was valid.
*/
AsyncResults<bool> Configure(const std::string& name_path, DefaultValueType);
AsyncResults<bool> Configure(const std::string& name_path, bool value);
AsyncResults<bool> Configure(const std::string& name_path, double value);
AsyncResults<bool> Configure(const std::string& name_path,
const std::string& value);
template <typename T, typename = typename std::enable_if<
std::is_arithmetic<T>::value>::type>
AsyncResults<bool> Configure(const std::string& name_path, T value) {
// Since there are both bool and double overloads, any other number type
// will cause an ambiguous call. This disambiguates the calls.
return Configure(name_path, static_cast<double>(value));
}
AsyncResults<bool> Configure(const std::string& name_path,
const char* value) {
// For some reason, the compiler tries to use the bool overload over the
// std::string one when passing a char pointer.
return Configure(name_path, std::string(value));
}
//@}
/** Reset configuration to default. */
AsyncResults<void> ResetConfiguration();
/**
* Retry streaming after a failure. Does nothing if not in a failure state.
*/
AsyncResults<void> RetryStreaming();
/**
* Sets currentAudioLanguage and currentVariantRole to the selected language
* and role, and chooses a new variant if need be.
*/
AsyncResults<void> SelectAudioLanguage(const std::string& language,
optional<std::string> role = nullopt);
/**
* Use the embedded text for the current stream, if present. CEA 608/708
* captions data is embedded inside the video stream.
*/
AsyncResults<void> SelectEmbeddedTextTrack();
/**
* Sets currentTextLanguage and currentTextRole to the selected language and
* role, and chooses a new text stream if need be.
*/
AsyncResults<void> SelectTextLanguage(const std::string& language,
optional<std::string> role = nullopt);
/**
* Select a specific text track. Note that AdaptationEvents are not fired for
* manual track selections.
*/
AsyncResults<void> SelectTextTrack(const Track& track);
/**
* Select a specific track. Note that AdaptationEvents are not fired for
* manual track selections.
*/
AsyncResults<void> SelectVariantTrack(const Track& track,
bool clear_buffer = false);
/**
* Sets whether the text track should be visible or not, if any exists.
*
* @param visibility True if the text track should be visible.
*/
AsyncResults<void> SetTextTrackVisibility(bool visibility);
//@{
/**
* Gets a configuration value from the Player instance. This is simply
* forwarded to the JavaScript instance. No error is returned if the
* requested configuration isn't present or is an invalid type, see the logs
* for errors. The path is a '.' separated list of names to reach the
* configuration. For example:
*
* 'abr.enabled' => {abr: {enabled: value}}
*
* TODO: These will be replaced with a more general GetConfiguration() method
* in the future.
*
* @return A future to the value.
*/
AsyncResults<bool> GetConfigurationBool(const std::string& name_path);
AsyncResults<double> GetConfigurationDouble(const std::string& name_path);
AsyncResults<std::string> GetConfigurationString(
const std::string& name_path);
//@}
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_PLAYER_H_
<file_sep>/shaka/src/mapping/any.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MAPPING_ANY_H_
#define SHAKA_EMBEDDED_MAPPING_ANY_H_
#include <string>
#include "src/mapping/convert_js.h"
#include "src/mapping/generic_converter.h"
#include "src/mapping/js_wrappers.h"
#include "src/mapping/weak_js_ptr.h"
namespace shaka {
/**
* Defines any JavaScript value. This allows accepting any value and includes
* methods to convert to different types.
*/
class Any : public GenericConverter, public memory::Traceable {
public:
static std::string name() {
return "anything";
}
Any();
explicit Any(std::nullptr_t);
template <typename T>
explicit Any(const T& value) {
value_ = ::shaka::ToJsValue(value);
is_number_ = GetValueType(value_.handle()) == JSValueType::Number;
}
~Any() override;
// Chromium style complains without these.
Any(const Any&);
Any(Any&&);
Any& operator=(const Any&);
Any& operator=(Any&&);
/**
* Returns whether the value contained is a "truthy" value. The following
* values are falsy, everything else is truthy:
* - undefined
* - null
* - "" (empty string)
* - false (boolean)
* - NaN (number)
* - 0 (number)
*/
bool IsTruthy() const;
/**
* Tries to convert the current value into the given type. This can only
* be called on the event thread.
*
* @param result [OUT] Where to put the converted value.
* @return True on success, false on failure.
*/
template <typename T>
bool TryConvertTo(T* result) const {
return FromJsValue(value_.handle(), result);
}
bool TryConvert(Handle<JsValue> value) override;
ReturnVal<JsValue> ToJsValue() const override;
void Trace(memory::HeapTracer* tracer) const override;
private:
WeakJsPtr<JsValue> value_;
bool is_number_;
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_MAPPING_ANY_H_
<file_sep>/shaka/src/public/eme_promise_impl.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_EME_PROMISE_IMPL_H_
#define SHAKA_EMBEDDED_EME_PROMISE_IMPL_H_
#include <atomic>
#include <string>
#include "shaka/eme/eme_promise.h"
#include "src/core/ref_ptr.h"
#include "src/mapping/promise.h"
namespace shaka {
namespace eme {
class EmePromise::Impl {
public:
Impl(const Promise& promise, bool has_value);
Impl(const Impl& other) = delete;
Impl(Impl&& other) = delete;
virtual ~Impl();
Impl& operator=(const Impl& other) = delete;
Impl& operator=(Impl&& other) = delete;
virtual void Resolve();
virtual void ResolveWith(bool value);
virtual void Reject(ExceptionType except_type, const std::string& message);
protected:
Impl();
private:
RefPtr<Promise> promise_;
std::atomic<bool> is_pending_;
bool has_value_;
};
} // namespace eme
} // namespace shaka
#endif // SHAKA_EMBEDDED_EME_PROMISE_IMPL_H_
<file_sep>/shaka/src/memory/v8_heap_tracer.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/memory/v8_heap_tracer.h"
#include <glog/logging.h>
#include "src/mapping/backing_object.h"
#include "src/memory/object_tracker.h"
#include "src/util/clock.h"
namespace shaka {
namespace memory {
V8HeapTracer::V8HeapTracer(HeapTracer* heap_tracer,
ObjectTracker* object_tracker)
: heap_tracer_(heap_tracer), object_tracker_(object_tracker) {}
V8HeapTracer::~V8HeapTracer() {}
void V8HeapTracer::AbortTracing() {
VLOG(2) << "GC run aborted";
heap_tracer_->ResetState();
fields_.clear();
}
void V8HeapTracer::TracePrologue() {
VLOG(2) << "GC run started";
DCHECK(fields_.empty());
heap_tracer_->BeginPass();
}
void V8HeapTracer::TraceEpilogue() {
VLOG(2) << "GC run ended";
CHECK(fields_.empty());
object_tracker_->FreeDeadObjects(heap_tracer_->alive());
heap_tracer_->ResetState();
}
void V8HeapTracer::EnterFinalPause() {}
void V8HeapTracer::RegisterV8References(
const InternalFieldList& internal_fields) {
VLOG(2) << "GC add " << internal_fields.size() << " objects";
fields_.insert(fields_.end(), internal_fields.begin(), internal_fields.end());
}
bool V8HeapTracer::AdvanceTracing(double /* deadline_ms */,
AdvanceTracingActions /* actions */) {
VLOG(2) << "GC run step";
util::Clock clock;
const uint64_t start = clock.GetMonotonicTime();
heap_tracer_->TraceCommon(object_tracker_->GetAliveObjects());
for (auto& pair : fields_) {
heap_tracer_->Trace(reinterpret_cast<BackingObject*>(pair.first));
}
VLOG(2) << "Tracing " << heap_tracer_->alive().size() << " objects took "
<< ((clock.GetMonotonicTime() - start) / 1000.0) << " seconds";
fields_.clear();
return false;
}
} // namespace memory
} // namespace shaka
<file_sep>/shaka/src/memory/v8_heap_tracer.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEMORY_V8_HEAP_TRACER_H_
#define SHAKA_EMBEDDED_MEMORY_V8_HEAP_TRACER_H_
#include <utility>
#include <vector>
#include "src/memory/heap_tracer.h"
namespace shaka {
namespace memory {
class ObjectTracker;
/**
* This wraps the normal HeapTracer in an interface that can be used by V8
* to track objects. Methods defined here will be called by V8 when it decides
* that a GC needs to be run.
*
* This explains how the V8 GC works and how we interact with it:
*
* There are two kinds of objects that are managed by different GCs, a
* JavaScript object (v8::Value) which is handled by the V8 gc, and
* BackingObject's which are handled by ObjectTracker. When the V8 GC runs, we
* need to tell it what objects we hold so it knows the V8 objects to delete.
* That is the purpose of this class.
*
* When a V8 pass start, V8 will call TracePrologue. Then it will traverse
* its objects, marking alive objects. Any object that looks like a wrapper
* will be added to a list. Once the traversal is done, it will call
* RegisterV8References passing in the list. Then it will call AdvanceTracing
* to allow us to traverse our heap. We should traverse our alive objects
* and any wrapper objects given to us. We should then (a) mark these object
* as alive so we don't free them, and (b) tell V8 about any objects we hold.
*
* When we tell V8 about alive objects, it may need to do some more traversals,
* which may in turn find more wrappers. If this happens, it will call
* RegisterV8References and AdvanceTracing again.
*
* At points between method calls, it is possible for JavaScript to run.
* Because this runs on the event thread, it is not possible for JavaScript to
* run while one of these methods are being called, but between it is possible.
* V8 monitors all the objects and will ensure that any new objects will be
* given to us.
*
* After V8 has traced every object TraceEpilogue is called. We use this to
* free any object that is not marked as alive.
*/
class V8HeapTracer : public v8::EmbedderHeapTracer {
using InternalFieldList = std::vector<std::pair<void*, void*>>;
public:
V8HeapTracer(HeapTracer* heap_tracer, ObjectTracker* object_tracker);
~V8HeapTracer() override;
/** Called by V8 when a GC is aborted. */
void AbortTracing() override;
/** Called by V8 when a GC pass begins. */
void TracePrologue() override;
/** Called by V8 when a GC pass ends. */
void TraceEpilogue() override;
/**
* Called by V8 when entering the final marking phase. There will be no more
* incremental marking calls.
*/
void EnterFinalPause() override;
/**
* Called by V8 to tell us about wrapper objects. The pair contains the
* internal field values of the wrapper object. We should store the values
* and process them only in AdvanceTracing.
*/
void RegisterV8References(const InternalFieldList& internal_fields) override;
/**
* Called by V8 to advance the GC run. We should only take |deadline_ms|
* time to complete, telling V8 whether there is more work to do.
* @return True if there is more work to do, false if done.
*/
bool AdvanceTracing(double deadline_ms, AdvanceTracingActions) override;
private:
InternalFieldList fields_;
HeapTracer* heap_tracer_;
ObjectTracker* object_tracker_;
};
} // namespace memory
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEMORY_V8_HEAP_TRACER_H_
<file_sep>/shaka/src/media/hardware_support.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/hardware_support.h"
#include <glog/logging.h>
#include <mutex>
#include <unordered_map>
#include "src/util/macros.h"
#if defined(OS_IOS)
# include <VideoToolbox/VideoToolbox.h>
# include "src/util/cfref.h"
# ifndef kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder
// If this were split onto two lines, the \ at the end would be at 81
// characters, and would fail the linter. So put this on one line and disable
// linting. This also needs to disable clang-format from fixing it.
// clang-format off
# define kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder CFSTR("RequireHardwareAcceleratedVideoDecoder") // NOLINT
// clang-format on
# endif
#endif
namespace shaka {
namespace media {
namespace {
/** A helper class that memoizes values for the support check. */
class SupportCache {
public:
bool TryGet(const std::string& codec, int width, int height, bool* result) {
std::unique_lock<std::mutex> lock(mutex_);
CheckArgs args(codec, width, height);
if (results_.count(args) > 0) {
*result = results_.at(args);
return true;
} else {
return false;
}
}
void Insert(const std::string& codec, int width, int height, bool result) {
std::unique_lock<std::mutex> lock(mutex_);
results_[CheckArgs(codec, width, height)] = result;
}
private:
struct CheckArgs {
CheckArgs(const std::string& codec, int width, int height)
: codec(codec), width(width), height(height) {}
const std::string codec;
const int width;
const int height;
bool operator==(const CheckArgs& other) const noexcept {
return codec == other.codec && width == other.width &&
height == other.height;
}
};
struct CheckArgsHash {
size_t operator()(const CheckArgs& args) const noexcept {
return std::hash<std::string>()(args.codec) ^ (args.width << 16) ^
args.height;
}
};
std::mutex mutex_;
std::unordered_map<CheckArgs, bool, /* Hash */ CheckArgsHash> results_;
};
#ifdef OS_IOS
util::CFRef<CFMutableDictionaryRef> GetExtraData(CMVideoCodecType codec,
int profile) {
util::CFRef<CFMutableDictionaryRef> avc_info = CFDictionaryCreateMutable(
kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
switch (codec) {
case kCMVideoCodecType_H264: {
// This is just a common SPS and PPS that doesn't use any "unusual"
// features; this is believed to be commonly supported. We can't just
// pass 0 SPS or PPS, the decoder requires at least one of each.
uint8_t extra_data[] = {
// Disable formatting so clang-format doesn't put each element on its
// own line.
// clang-format off
0x01, // version
(profile >> 16) & 0xff, // profile
(profile >> 8) & 0xff, // profile compat
(profile >> 0) & 0xff, // level
0xff, // 6 reserved bits + 2 bits nalu size length - 1
0xe1, // 3 reserved bits + 5 bits SPS count
0x00, 0x1c, // SPS size
0x67, 0x42, 0xc8, 0x1e, 0xd9, 0x01, 0x03, 0xfe, 0xbf, 0xf0,
0x06, 0xe0, 0x06, 0xd1, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00,
0x00, 0x03, 0x00, 0x30, 0x0f, 0x16, 0x2e, 0x48,
0x01, // PPS count
0x00, 0x04, // PPS size
0x68, 0xcb, 0x8c, 0xb2,
// clang-format on
};
util::CFRef<CFDataRef> buffer =
CFDataCreate(kCFAllocatorDefault, extra_data, sizeof(extra_data));
if (buffer)
CFDictionarySetValue(avc_info, CFSTR("avcC"), buffer);
break;
}
default:
LOG(FATAL) << "Unknown codec type: " << codec;
}
return avc_info;
}
void IosDecoderCallback(void*, void*, OSStatus, VTDecodeInfoFlags,
CVImageBufferRef, CMTime, CMTime) {}
bool IosHardwareSupport(CMVideoCodecType codec, int profile, int width,
int height) {
if (width * height > 5000000) {
// VideoToolbox doesn't handle out of memory correctly and has a tendency to
// just crash with a memory error if we run out of memory. This only seems
// to happen with 4k, so just blacklist it for now.
// TODO: Find a better solution or file a bug.
return false;
}
auto NewDict = []() {
return CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
};
util::CFRef<CFMutableDictionaryRef> decoder_config = NewDict();
CFDictionarySetValue(
decoder_config,
kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder,
kCFBooleanTrue);
CFDictionarySetValue(
decoder_config,
kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms,
GetExtraData(codec, profile));
CMFormatDescriptionRef cm_fmt_desc;
if (CMVideoFormatDescriptionCreate(kCFAllocatorDefault, codec, width, height,
decoder_config, &cm_fmt_desc) != 0) {
return false;
}
// Create a dictionary of buffer properties.
util::CFRef<CFNumberRef> w =
CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &width);
util::CFRef<CFNumberRef> h =
CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &height);
const OSType pix_fmt = kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
util::CFRef<CFNumberRef> cv_pix_fmt =
CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pix_fmt);
util::CFRef<CFMutableDictionaryRef> buffer_attributes = NewDict();
util::CFRef<CFMutableDictionaryRef> io_surface_properties = NewDict();
CFDictionarySetValue(buffer_attributes, kCVPixelBufferPixelFormatTypeKey,
cv_pix_fmt);
CFDictionarySetValue(buffer_attributes, kCVPixelBufferIOSurfacePropertiesKey,
io_surface_properties);
CFDictionarySetValue(buffer_attributes, kCVPixelBufferWidthKey, w);
CFDictionarySetValue(buffer_attributes, kCVPixelBufferHeightKey, h);
// Try to create the decompression session, which will tell us whether it
// supports these settings.
VTDecompressionOutputCallbackRecord decoder_cb = {
.decompressionOutputCallback = &IosDecoderCallback,
.decompressionOutputRefCon = nullptr,
};
VTDecompressionSessionRef session = nullptr;
const OSStatus status =
VTDecompressionSessionCreate(nullptr, cm_fmt_desc, decoder_config,
buffer_attributes, &decoder_cb, &session);
CFRelease(cm_fmt_desc);
if (session)
CFRelease(session);
switch (status) {
case 0:
return true;
case kVTCouldNotFindVideoDecoderErr:
case kVTVideoDecoderNotAvailableNowErr:
LOG(INFO) << "Hardware decoder not available";
return false;
case kVTVideoDecoderUnsupportedDataFormatErr:
VLOG(1) << "Video not supported: size=" << width << "x" << height
<< ", profile=" << std::hex << profile;
return false;
default:
LOG(DFATAL) << "Bad hardware acceleration query: status=" << status;
return false;
}
}
#endif
bool InternalHardwareSupport(const std::string& codec, int width, int height) {
#ifdef OS_IOS
if (codec.substr(0, 5) == "avc1.") {
long profile = strtol(codec.substr(5).c_str(), nullptr, 16); // NOLINT
if (profile == 0)
profile = 0x42001e;
return IosHardwareSupport(kCMVideoCodecType_H264, profile, width, height);
} else if (codec.substr(0, 5) == "mp4a.") {
return true;
} else {
LOG(ERROR) << "Unable to query support for codec: " << codec;
return false;
}
#else
# error "This platform doesn't have a unique hardware decoder to query."
#endif
}
} // namespace
bool DoesHardwareSupportCodec(const std::string& codec, int width, int height) {
if (width == 0)
width = 720;
if (height == 0)
height = 480;
BEGIN_ALLOW_COMPLEX_STATICS
static SupportCache cache_;
END_ALLOW_COMPLEX_STATICS
bool result;
if (!cache_.TryGet(codec, width, height, &result)) {
result = InternalHardwareSupport(codec, width, height);
cache_.Insert(codec, width, height, result);
}
return result;
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/util/dynamic_buffer.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/util/dynamic_buffer.h"
#include <glog/logging.h>
#include <cstring>
namespace shaka {
namespace util {
DynamicBuffer::DynamicBuffer() {}
DynamicBuffer::~DynamicBuffer() {}
DynamicBuffer::DynamicBuffer(DynamicBuffer&&) = default;
DynamicBuffer& DynamicBuffer::operator=(DynamicBuffer&&) = default;
size_t DynamicBuffer::Size() const {
size_t size = 0;
for (auto& buffer : buffers_)
size += buffer.size;
return size;
}
void DynamicBuffer::AppendCopy(const void* buffer, size_t size) {
auto* ptr = new uint8_t[size];
std::memcpy(ptr, buffer, size);
buffers_.emplace_back(ptr, size);
}
std::string DynamicBuffer::CreateString() const {
std::string ret(Size(), '\0');
CopyDataTo(reinterpret_cast<uint8_t*>(&ret[0]), ret.size());
return ret;
}
void DynamicBuffer::CopyDataTo(uint8_t* dest, size_t size) const {
for (auto& buffer : buffers_) {
CHECK_GE(size, buffer.size);
std::memcpy(dest, buffer.buffer.get(), buffer.size);
dest += buffer.size;
size -= buffer.size;
}
}
DynamicBuffer::SubBuffer::SubBuffer(uint8_t* buffer, size_t size)
: buffer(buffer), size(size) {}
DynamicBuffer::SubBuffer::~SubBuffer() {}
} // namespace util
} // namespace shaka
<file_sep>/shaka/src/debug/thread.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/debug/thread.h"
#include <glog/logging.h>
#include <utility>
#include "src/debug/waiting_tracker.h"
#include "src/util/utils.h"
namespace shaka {
namespace {
void ThreadMain(const std::string& name, std::function<void()> callback) {
DCHECK_LT(name.size(), 16u) << "Name too long: " << name;
#if defined(OS_MAC) || defined(OS_IOS)
pthread_setname_np(name.c_str());
#elif defined(OS_POSIX)
pthread_setname_np(pthread_self(), name.c_str());
#else
# error "Not implemented for Windows"
#endif
#ifdef DEBUG_DEADLOCKS
util::Finally scope(&WaitingTracker::ThreadExit);
#endif
callback();
}
} // namespace
Thread::Thread(const std::string& name, std::function<void()> callback)
: name_(name), thread_(&ThreadMain, name, std::move(callback)) {
#ifdef DEBUG_DEADLOCKS
original_id_ = thread_.get_id();
WaitingTracker::AddThread(this);
#endif
}
Thread::~Thread() {
DCHECK(!thread_.joinable());
#ifdef DEBUG_DEADLOCKS
WaitingTracker::RemoveThread(this);
#endif
}
} // namespace shaka
<file_sep>/shaka/test/src/media/video_renderer_unittest.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/video_renderer.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "src/media/base_frame.h"
#include "src/media/stream.h"
namespace shaka {
namespace media {
using testing::_;
using testing::InSequence;
using testing::MockFunction;
using testing::Return;
namespace {
class MockFrameDrawer : public FrameDrawer {
public:
MOCK_METHOD1(DrawFrame, Frame(const BaseFrame* frame));
};
std::unique_ptr<BaseFrame> MakeFrame(double start) {
BaseFrame* ret = new BaseFrame(start, start, 0.01, true);
return std::unique_ptr<BaseFrame>(ret);
}
constexpr const double kMinDelay = 1.0 / 120;
} // namespace
class VideoRendererTest : public testing::Test {
protected:
void SetDrawer(VideoRenderer* renderer, FrameDrawer* drawer) {
renderer->SetDrawerForTesting(std::unique_ptr<FrameDrawer>(drawer));
}
};
TEST_F(VideoRendererTest, WorksWithNoNextFrame) {
Stream stream;
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.00));
MockFunction<double()> get_time;
auto* drawer = new MockFrameDrawer;
{
#define FRAME_AT(i) (stream.GetDecodedFrames()->GetFrameNear(i).get())
InSequence seq;
EXPECT_CALL(get_time, Call()).WillRepeatedly(Return(0));
EXPECT_CALL(*drawer, DrawFrame(FRAME_AT(0))).Times(1);
#undef GET_FRAME
}
VideoRenderer renderer(std::bind(&MockFunction<double()>::Call, &get_time),
&stream);
SetDrawer(&renderer, drawer); // Takes ownership.
int dropped_frame_count = 0;
bool is_new_frame = false;
double delay = 0;
renderer.DrawFrame(&dropped_frame_count, &is_new_frame, &delay);
EXPECT_EQ(dropped_frame_count, 0);
EXPECT_TRUE(is_new_frame);
EXPECT_EQ(delay, kMinDelay);
}
TEST_F(VideoRendererTest, WorksWithNoFrames) {
Stream stream;
MockFunction<double()> get_time;
auto* drawer = new MockFrameDrawer;
{
InSequence seq;
EXPECT_CALL(get_time, Call()).WillRepeatedly(Return(0));
EXPECT_CALL(*drawer, DrawFrame(_)).Times(0);
}
VideoRenderer renderer(std::bind(&MockFunction<double()>::Call, &get_time),
&stream);
SetDrawer(&renderer, drawer); // Takes ownership.
int dropped_frame_count = 0;
bool is_new_frame = false;
double delay = 0;
renderer.DrawFrame(&dropped_frame_count, &is_new_frame, &delay);
}
TEST_F(VideoRendererTest, DrawsFrameInPast) {
Stream stream;
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.00));
MockFunction<double()> get_time;
auto* drawer = new MockFrameDrawer;
{
#define FRAME_AT(i) (stream.GetDecodedFrames()->GetFrameNear(i).get())
InSequence seq;
EXPECT_CALL(get_time, Call()).WillRepeatedly(Return(4));
EXPECT_CALL(*drawer, DrawFrame(FRAME_AT(0))).Times(1);
#undef GET_FRAME
}
VideoRenderer renderer(std::bind(&MockFunction<double()>::Call, &get_time),
&stream);
SetDrawer(&renderer, drawer); // Takes ownership.
int dropped_frame_count = 0;
bool is_new_frame = false;
double delay = 0;
renderer.DrawFrame(&dropped_frame_count, &is_new_frame, &delay);
EXPECT_EQ(dropped_frame_count, 0);
EXPECT_TRUE(is_new_frame);
EXPECT_DOUBLE_EQ(delay, kMinDelay);
}
TEST_F(VideoRendererTest, WillDropFrames) {
Stream stream;
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.00));
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.01));
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.02));
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.03));
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.04));
MockFunction<double()> get_time;
auto* drawer = new MockFrameDrawer;
{
#define FRAME_AT(i) (stream.GetDecodedFrames()->GetFrameNear(i).get())
InSequence seq;
EXPECT_CALL(get_time, Call()).WillRepeatedly(Return(0));
EXPECT_CALL(*drawer, DrawFrame(FRAME_AT(0))).Times(1);
EXPECT_CALL(get_time, Call()).WillRepeatedly(Return(0.03));
EXPECT_CALL(*drawer, DrawFrame(FRAME_AT(0.03))).Times(1);
#undef GET_FRAME
}
VideoRenderer renderer(std::bind(&MockFunction<double()>::Call, &get_time),
&stream);
SetDrawer(&renderer, drawer); // Takes ownership.
int dropped_frame_count = 0;
bool is_new_frame = false;
double delay = 0;
// Time: 0
renderer.DrawFrame(&dropped_frame_count, &is_new_frame, &delay);
EXPECT_EQ(dropped_frame_count, 0);
EXPECT_TRUE(is_new_frame);
EXPECT_DOUBLE_EQ(delay, 0.01);
// Time: 0.03
renderer.DrawFrame(&dropped_frame_count, &is_new_frame, &delay);
EXPECT_EQ(dropped_frame_count, 2);
EXPECT_TRUE(is_new_frame);
EXPECT_DOUBLE_EQ(delay, 0.01);
}
TEST_F(VideoRendererTest, HandlesSeeks) {
Stream stream;
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.00));
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.01));
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.02));
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.03));
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.04));
MockFunction<double()> get_time;
auto* drawer = new MockFrameDrawer;
{
#define FRAME_AT(i) (stream.GetDecodedFrames()->GetFrameNear(i).get())
InSequence seq;
EXPECT_CALL(get_time, Call()).WillRepeatedly(Return(0));
EXPECT_CALL(*drawer, DrawFrame(FRAME_AT(0))).Times(1);
// Seek
EXPECT_CALL(get_time, Call()).WillRepeatedly(Return(0.03));
EXPECT_CALL(*drawer, DrawFrame(FRAME_AT(0.03))).Times(1);
#undef GET_FRAME
}
VideoRenderer renderer(std::bind(&MockFunction<double()>::Call, &get_time),
&stream);
SetDrawer(&renderer, drawer); // Takes ownership.
int dropped_frame_count = 0;
bool is_new_frame = false;
double delay = 0;
// Time: 0
renderer.DrawFrame(&dropped_frame_count, &is_new_frame, &delay);
EXPECT_EQ(dropped_frame_count, 0);
EXPECT_TRUE(is_new_frame);
EXPECT_DOUBLE_EQ(delay, 0.01);
renderer.OnSeek();
renderer.OnSeekDone();
// Time: 0.04
renderer.DrawFrame(&dropped_frame_count, &is_new_frame, &delay);
EXPECT_EQ(dropped_frame_count, 0); // Skipped over frames, but don't count.
EXPECT_TRUE(is_new_frame);
EXPECT_DOUBLE_EQ(delay, 0.01);
}
TEST_F(VideoRendererTest, TracksNewFrames) {
Stream stream;
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.00));
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.02));
stream.GetDecodedFrames()->AppendFrame(MakeFrame(0.04));
MockFunction<double()> get_time;
auto* drawer = new MockFrameDrawer;
{
#define FRAME_AT(i) (stream.GetDecodedFrames()->GetFrameNear(i).get())
InSequence seq;
EXPECT_CALL(get_time, Call()).WillRepeatedly(Return(0));
EXPECT_CALL(*drawer, DrawFrame(FRAME_AT(0))).Times(1);
EXPECT_CALL(get_time, Call()).WillRepeatedly(Return(0.006));
EXPECT_CALL(*drawer, DrawFrame(FRAME_AT(0))).Times(1);
EXPECT_CALL(get_time, Call()).WillRepeatedly(Return(0.006));
EXPECT_CALL(*drawer, DrawFrame(FRAME_AT(0))).Times(1);
EXPECT_CALL(get_time, Call()).WillRepeatedly(Return(0.025));
EXPECT_CALL(*drawer, DrawFrame(FRAME_AT(0.02))).Times(1);
EXPECT_CALL(get_time, Call()).WillRepeatedly(Return(0.031));
EXPECT_CALL(*drawer, DrawFrame(FRAME_AT(0.02))).Times(1);
EXPECT_CALL(get_time, Call()).WillRepeatedly(Return(0.044));
EXPECT_CALL(*drawer, DrawFrame(FRAME_AT(0.04))).Times(1);
#undef GET_FRAME
}
VideoRenderer renderer(std::bind(&MockFunction<double()>::Call, &get_time),
&stream);
SetDrawer(&renderer, drawer); // Takes ownership.
int dropped_frame_count = 0;
bool is_new_frame = false;
double delay = 0;
// Time: 0
renderer.DrawFrame(&dropped_frame_count, &is_new_frame, &delay);
EXPECT_EQ(dropped_frame_count, 0);
EXPECT_TRUE(is_new_frame);
EXPECT_DOUBLE_EQ(delay, 0.02);
for (int i = 0; i < 2; i++) {
// Time: 0.006
renderer.DrawFrame(&dropped_frame_count, &is_new_frame, &delay);
EXPECT_EQ(dropped_frame_count, 0);
EXPECT_FALSE(is_new_frame);
EXPECT_DOUBLE_EQ(delay, 0.014);
}
// Time: 0.025
renderer.DrawFrame(&dropped_frame_count, &is_new_frame, &delay);
EXPECT_EQ(dropped_frame_count, 0);
EXPECT_TRUE(is_new_frame);
EXPECT_DOUBLE_EQ(delay, 0.015);
// Time: 0.031
renderer.DrawFrame(&dropped_frame_count, &is_new_frame, &delay);
EXPECT_EQ(dropped_frame_count, 0);
EXPECT_FALSE(is_new_frame);
EXPECT_DOUBLE_EQ(delay, 0.009);
// Time: 0.044
renderer.DrawFrame(&dropped_frame_count, &is_new_frame, &delay);
EXPECT_EQ(dropped_frame_count, 0);
EXPECT_TRUE(is_new_frame);
EXPECT_DOUBLE_EQ(delay, kMinDelay);
}
} // namespace media
} // namespace shaka
<file_sep>/configure
#!/usr/bin/python
# Copyright 2017 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Generates build files for a given configuration.
This works similar to any normal ./configure script. This generates build files
to build the project using the given command-line options.
This doesn't use the make program to compile the project, this uses ninja.
However, there is a Makefile that simply calls ./build.py for you. You don't
have to re-run ./configure if you edit BUILD.gn files.
This doesn't support in-tree configures. You have two options: (1) create
another directory (or sub-directory) to do the configure in; or (2) use the
--config-name option. --config-name will create a subdirectory in the source
root called "out" to hold that configuration. If --config-name is used, the
Makefile will be generated in the working directory, but the generated files
will be put in out/$CONFIG_NAME. Multiple parallel configurations can exist, so
you can have one for Debug and one for Release.
You can use the generated Makefile or ./build.py to build. If you used the
--config-name parameter, be sure to pass that to ./build.py also.
"""
from __future__ import print_function
import argparse
import errno
import logging
import os
import platform
import re
import subprocess
import sys
ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
DEFAULT_SETTINGS = {
'use_cxx11': True,
# The embedded sysroot in V8 has bugs in <chrono> meaning we cannot use
# <thread> or <condition_variable>.
'use_sysroot': False,
'use_custom_libcxx': False,
# Even though we don't compile Chromium, there is some global scripts that
# try to find glib. This ensures we can build without glib installed.
'use_glib': False,
}
PLATFORM_SPECIFIC_SETTINGS = {
'darwin': {
'enable_dsyms': True,
},
}
V8_SETTINGS = {
'v8_extra_library_files': [],
'v8_experimental_extra_library_files': [],
# TODO: Building V8 in debug mode is currently broken.
'v8_enable_debugging_features': False,
}
sys.path.append(os.path.join(ROOT_DIR, 'build'))
sys.path.append(os.path.join(ROOT_DIR, 'shaka', 'tools'))
import run_configure
import utils
def _SilentRun(*cmd, **kwargs):
"""Runs the given subprocess and only prints output on error."""
try:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
**kwargs)
except OSError as e:
if e.errno == errno.ENOENT:
logging.error('Required command not found: %s', cmd[0])
return 1
raise
out, err = proc.communicate()
if proc.returncode != 0:
logging.error('Standard output:')
logging.error(out)
logging.error('')
logging.error('Standard error:')
logging.error(err)
return proc.returncode
# Setting up GN arguments
#{{{
class _MaybeUseCcache(argparse.Action):
"""An argparse Action that searches for ccache on PATH."""
def __init__(self, *args, **kwargs):
super(_MaybeUseCcache, self).__init__(*args, **kwargs)
self.nargs = 0
def _IsNewEnough(self, cmd):
"""Returns whether ccache is new enough."""
try:
output = subprocess.check_output([cmd, '--version'],
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
logging.error('Error executing |ccache --version|:')
logging.error(e.output)
sys.exit(1)
match = re.search(r'ccache version ([0-9.]+)', output)
if not match:
logging.error('Unable to parse |ccache --version| output.')
return False
version = tuple(int(s) for s in match.group(1).split('.'))
if version >= (3, 2):
# See comment in //build/toolchain/cc_wrapper.gni about the minimum
# version.
return True
else:
logging.error('ccache is too old, upgrade to at least version 3.2')
return False
def __call__(self, parser, ns, values, option_string=None):
if utils.ExistsOnPath('ccache'):
exe = 'ccache'
elif utils.ExistsOnPath('ccache.exe'):
exe = 'ccache.exe'
else:
logging.error('Unable to find ccache on PATH')
return
if self._IsNewEnough(exe):
setattr(ns, self.dest, exe)
_REQUIRED_SUBMODULES = [
'base/trace_event/common',
'build',
'buildtools',
'testing',
'third_party/boringssl/src',
'third_party/curl/src',
'third_party/ffmpeg/src',
'third_party/gflags/src',
'third_party/glog/src',
'third_party/googletest/src',
'third_party/libxml/src',
'third_party/ply/src',
'third_party/pymake/src',
'third_party/sdl2/src',
'third_party/zlib/src',
'tools/clang',
]
_V8_SUBMODULES = [
'third_party/icu',
'third_party/jinja2',
'third_party/markupsafe',
'v8',
]
def _LoadSubmodules(has_v8):
"""Loads the required submodules to build."""
logging.error('Loading required submodules...')
modules = _REQUIRED_SUBMODULES
if has_v8:
modules += _V8_SUBMODULES
for module in modules:
utils.LoadSubmodule(module)
def _DownloadGn():
"""Downloads the GN binary from cloud storage."""
logging.error('Downloading GN from cloud storage...')
platform_name = platform.uname()[0]
if platform_name == 'Linux':
path = 'buildtools/linux64/gn.sha1'
elif platform_name == 'Darwin':
path = 'buildtools/mac/gn.sha1'
elif platform_name == 'Windows' or 'CYGWIN' in platform_name:
path = 'buildtools/win/gn.exe.sha1'
else:
raise RuntimeError('Unknown platform type')
# TODO: Consider an alternative that doesn't use depot_tools. This would
# allow us to only depend on ninja, which can be installed separately.
return _SilentRun('download_from_google_storage', '--no_auth', '--bucket',
'chromium-gn', '-s', os.path.join(ROOT_DIR, path))
def _ConstructGnArgs(parsed_args):
"""Constructs a GN args list from the given parsed command-line arguments."""
obj = DEFAULT_SETTINGS.copy()
obj.update(PLATFORM_SPECIFIC_SETTINGS.get(sys.platform, {}))
if parsed_args.js_engine == 'v8':
obj.update(V8_SETTINGS)
for k, v in vars(parsed_args).iteritems():
if k[-1] != '_' and v is not None:
obj[k] = v
import gn_helpers # Don't import until we have downloaded the submodule.
return gn_helpers.ToGNString(obj) + ' ' + parsed_args.gn_args_
def GenGn(config_name, args, gen_ide=None):
"""Calls 'gn gen' with the given GN arguments."""
cmd = [utils.FindGn(), 'gen', '--root=' + ROOT_DIR, '--args=' + args,
utils.ConfigPath(config_name)]
if gen_ide:
cmd += ['--ide=' + gen_ide]
return _SilentRun(*cmd)
def RecoverGn(config_name):
"""Attempts to regenerate ninja files using an existing configuration."""
return subprocess.call([utils.FindGn(), '--root=' + ROOT_DIR, '-q', 'gen',
utils.ConfigPath(config_name)])
# }}}
# Running third-party configure
# {{{
_CONFIGURE_STEPS = []
def _Step(name):
"""Defines a configure step."""
def Wrapper(func):
_CONFIGURE_STEPS.append((name, func))
return func
return Wrapper
def _RunMake(out_dir, *targets):
return _SilentRun('make', '-j8', '-C', out_dir, *targets)
def _Split(s):
"""Splits the string on commas.
Args:
s: The string to split.
Returns:
A list of strings, or an empty list if the input is empty.
"""
if not s or not s.strip():
return []
return s.strip().split(',')
# TODO: Investigate whether we need to run v8/gypfiles/vs_toolschain.py. Only
# required on windows.
@_Step('binutils')
def _BinutilsSymlink(unused_src_dir, unused_dest_dir, unused_cpu, target_os,
unused_sysroot, unused_parsed_args):
"""Creates a symlink from V8's binutils to our root path."""
if target_os == 'ios':
return 0
utils.SymLink(os.path.join(ROOT_DIR, 'v8', 'third_party', 'binutils'),
os.path.join(ROOT_DIR, 'third_party', 'binutils'))
# Pull binutils for linux, enabled debug fission for faster linking /
# debugging when used with clang on Ubuntu Precise.
# https://code.google.com/p/chromium/issues/detail?id=352046
download = os.path.join(ROOT_DIR, 'v8', 'third_party', 'binutils',
'download.py')
return _SilentRun(sys.executable, download)
@_Step('clang')
def _DownloadClang(*unused_args):
# Pull clang if needed or requested via GYP_DEFINES.
# Note: On Win, this should run after win_toolchain, as it may use it.
# This also needs to be one of the first _Steps so other steps can use clang.
update = os.path.join(ROOT_DIR, 'tools', 'clang', 'scripts', 'update.py')
return _SilentRun(sys.executable, update, '--if-needed')
def _GetSdlPath(obj):
"""Converts an SDL2 object path to a source path."""
# The input will be "build/foo.la", we should return "sdl2/gen/foo.c".
return 'sdl2/gen/%s.c' % os.path.splitext(os.path.basename(obj))[0]
@_Step('sdl2')
def _RunSdlConfigure(src_dir, dest_dir, cpu, target_os, sysroot, parsed_args):
"""Runs configure for SDL2."""
extra_flags = [
# Disable third-party libraries to avoid finding the required paths in GN.
'--disable-libudev',
'--disable-dbus',
'--disable-ime',
'--disable-ibus',
'--disable-fcitx',
'--disable-sndio',
'--includedir=' + os.path.join(dest_dir, 'include'),
# Disable unused features for internal-only build.
'--disable-joystick',
'--disable-haptic',
'--disable-power',
'--disable-filesystem',
'--disable-timers',
'--disable-libsamplerate', # We resample ourselves.
'--disable-libsamplerate-shared',
]
if platform.uname()[0] != 'Darwin':
extra_flags += ['--disable-file']
if not parsed_args.sdl_utils:
extra_flags += [
# When using native textures, disable video output too. We should only
# have audio components now.
'--disable-events',
'--disable-video',
'--disable-render',
]
if run_configure.CrossConfigure(src_dir, dest_dir, cpu, target_os,
sysroot, extra_flags) != 0:
return 1
import parse_makefile # Only import once we have downloaded the submodule.
makefile = parse_makefile.Makefile([os.path.join(dest_dir, 'Makefile')])
base_path = os.path.abspath(os.path.join(src_dir, '..'))
# The SDL Makefile contains a variable OBJECTS that contains a list of targets
# to build. Each target has a dependency which is the file that will be built
# For example:
# OBJECTS=Foo.lo Bar.lo
# Foo.lo: src/audio/Foo.c
# $(CC) "$*"
objects = makefile.GetListVariable('OBJECTS')
sources = [makefile.GetTargetDepdency(t) for t in objects]
parsed_args.sdl2_sources = [os.path.relpath(p, base_path) for p in sources]
targets = makefile.GetListVariable('GEN_OBJECTS')
if targets:
parsed_args.sdl2_extra_files = map(_GetSdlPath, targets)
targets += makefile.GetListVariable('GEN_HEADERS')
targets += ['install-hdrs']
return _RunMake(dest_dir, *targets)
def _ConvertFFmpegFlags(parsed_args):
"""Converts the flags for this script into flags for FFmpeg configure."""
if not parsed_args.enable_hardware_decode:
parsed_args.extra_decoders_ = []
parsed_args.hwaccels_ = []
containers = _Split(parsed_args.containers_)
codecs = _Split(parsed_args.codecs_)
flags = ['--enable-demuxer=' + demuxer for demuxer in containers]
flags += ['--enable-parser=' + codec for codec in codecs]
flags += ['--enable-decoder=' + codec for codec in codecs]
flags += ['--enable-decoder=' + codec
for codec in _Split(parsed_args.extra_decoders_)]
flags += ['--enable-hwaccel=' + codec
for codec in _Split(parsed_args.hwaccels_)]
if 'mov' in containers and 'mpeg4video' not in codecs:
flags += ['--enable-parser=mpeg4video']
if parsed_args.is_debug:
flags += [
'--disable-optimizations',
'--enable-debug',
]
else:
flags += [
'--enable-optimizations',
'--disable-debug',
]
return flags
@_Step('ffmpeg')
def _RunFFmpegConfigure(src_dir, dest_dir, cpu, target_os, sysroot,
parsed_args):
"""Generates the required build files."""
third_party_dir = os.path.join(ROOT_DIR, 'third_party')
prefix = os.path.join(third_party_dir, 'llvm-build', 'Release+Asserts', 'bin')
cpu_flags = run_configure.FlagsForCpu(cpu, target_os, sysroot)
flags = [
'--cc=%s/clang %s' % (prefix, cpu_flags),
'--cxx=%s/clang++ %s' % (prefix, cpu_flags),
'--objcc=%s/clang %s' % (prefix, cpu_flags),
'--as=%s/clang %s' % (prefix, cpu_flags),
'--enable-cross-compile',
'--fatal-warnings',
'--disable-shared',
'--enable-static',
'--disable-programs',
'--disable-doc',
'--disable-avdevice',
'--enable-avcodec',
'--enable-avformat',
'--enable-swresample',
'--disable-swscale',
'--disable-postproc',
'--disable-avfilter',
'--disable-avresample',
'--disable-network',
'--disable-everything',
'--disable-bzlib',
'--disable-iconv',
'--disable-libxcb',
'--disable-libxcb-shm',
'--disable-libxcb-xfixes',
'--disable-libxcb-shape',
'--disable-lzma',
'--disable-schannel',
'--disable-sdl2',
'--disable-securetransport',
'--disable-xlib',
'--disable-asm', # TODO(modmaker): Consider using assembly.
]
flags += _ConvertFFmpegFlags(parsed_args)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
# Can't use GPL or non-free licensing. The FFmpeg configure won't enable
# those features without these flags.
assert '--enable-gpl' not in flags, "Can't use GPL licensed code."
assert '--enable-nonfree' not in flags, "Can't use non-free code."
if _SilentRun(os.path.join(src_dir, 'configure'), *flags, cwd=dest_dir) != 0:
return 1
import parse_makefile # Only import once we have downloaded the submodule.
def _GetFiles(prefix):
makefile = parse_makefile.Makefile(
[
os.path.join(dest_dir, 'ffbuild', 'config.mak'),
os.path.join(src_dir, prefix, 'Makefile'),
])
objs = (makefile.GetListVariable('OBJS') +
makefile.GetListVariable('OBJS-yes'))
return [os.path.join('src', prefix, f[:-2] + '.c') for f in set(objs)]
parsed_args.ffmpeg_codec_files = _GetFiles('libavcodec')
parsed_args.ffmpeg_util_files = _GetFiles('libavutil')
parsed_args.ffmpeg_swscale_files = _GetFiles('libswscale')
parsed_args.ffmpeg_swresample_files = _GetFiles('libswresample')
parsed_args.ffmpeg_format_files = _GetFiles('libavformat')
if 'src/libavformat/mov.c' in parsed_args.ffmpeg_format_files:
parsed_args.ffmpeg_format_files.remove('src/libavformat/mov.c')
parsed_args.ffmpeg_patch_mov = True
if 'src/libavformat/matroskadec.c' in parsed_args.ffmpeg_format_files:
parsed_args.ffmpeg_format_files.remove('src/libavformat/matroskadec.c')
parsed_args.ffmpeg_patch_mkv = True
if 'src/libavcodec/opus_parser.c' in parsed_args.ffmpeg_codec_files:
parsed_args.ffmpeg_codec_files.remove('src/libavcodec/opus_parser.c')
parsed_args.ffmpeg_patch_opus = True
if 'src/libavformat/utils.c' in parsed_args.ffmpeg_format_files:
parsed_args.ffmpeg_format_files.remove('src/libavformat/utils.c')
parsed_args.ffmpeg_patch_utils = True
return _RunMake(dest_dir, 'libavformat/ffversion.h')
@_Step('gflags')
def _RunGflagsConfigure(src_dir, dest_dir, cpu, target_os, sysroot, _):
"""Runs configure for gflags."""
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
compiler = os.path.join(ROOT_DIR, 'third_party', 'llvm-build',
'Release+Asserts', 'bin', 'clang')
# Don't pass the sysroot since cmake will also pass in CMAKE_SYSROOT.
flags = run_configure.FlagsForCpu(cpu, target_os, '')
extra_flags = [
'-DCMAKE_C_COMPILER=' + compiler,
'-DCMAKE_CXX_COMPILER=%s++' % compiler,
'-DCMAKE_C_FLAGS=' + flags,
'-DCMAKE_CXX_FLAGS=' + flags,
'-DCMAKE_SYSROOT=' + sysroot,
]
return _SilentRun('cmake', src_dir, *extra_flags, cwd=dest_dir)
@_Step('glog')
def _RunGlogConfigure(src_dir, dest_dir, cpu, target_os, sysroot, _):
"""Runs configure for glog."""
if _SilentRun('autoreconf', '-i', src_dir) != 0:
return 1
extra_flags = [
'--disable-rtti',
'--with-gflags=' + os.path.join(src_dir, '..', '..', 'gflags', 'src'),
]
if run_configure.CrossConfigure(src_dir, dest_dir, cpu, target_os,
sysroot, extra_flags) != 0:
return 1
# glog checks in files generated by autoreconf, so the directory is dirty.
# Now that ./configure is done, we don't need any of the files in src_dir,
# so have git reset everything. This ensures that gclient doesn't complain
# later about changes. See https://github.com/google/glog/issues/308
if _SilentRun('git', '-C', src_dir, 'reset', '--hard') != 0:
return 1
# -d: remove directories, -f: force delete, -x: remove untracked files.
return _SilentRun('git', '-C', src_dir, 'clean', '-dfx')
@_Step('libxml')
def _RunLibxmlConfigure(src_dir, dest_dir, cpu, target_os, sysroot, _):
"""Runs configure for libxml."""
if _SilentRun('autoreconf', '-if', '-Wall', src_dir) != 0:
return 1
extra_flags = [
'--without-c14n',
'--without-catalog',
'--without-debug',
'--without-docbook',
'--without-ftp',
'--without-http',
'--without-iconv',
'--without-iso8859x',
'--without-legacy',
'--without-lzma',
'--without-modules',
'--without-output',
'--without-pattern',
'--without-push',
'--without-reader',
'--without-regexps',
'--without-schemas',
'--without-schematron',
'--without-threads',
'--without-tree',
'--without-valid',
'--without-writer',
'--without-xinclude',
'--without-xpath',
'--without-xptr',
'--without-zlib',
]
return run_configure.CrossConfigure(src_dir, dest_dir, cpu, target_os,
sysroot, extra_flags)
def _RunThirdPartyConfigure(parsed_args):
"""Runs any third-party configure scripts that are needed."""
config_dir = utils.ConfigPath(parsed_args.config_name_)
cpu = (utils.GetGnArg(config_dir, 'target_cpu') or
utils.GetGnArg(config_dir, 'host_cpu'))
target_os = (utils.GetGnArg(config_dir, 'target_os') or
utils.GetGnArg(config_dir, 'host_os'))
gen_dir = utils.GetGnVar(config_dir, 'root_gen_dir')
sysroot = utils.GetGnVar(config_dir, 'sysroot')
if not cpu or not target_os:
logging.error('Error determining CPU or OS')
return 1
for name, func in _CONFIGURE_STEPS:
logging.error('Running configure for %s...', name)
src_dir = os.path.join(ROOT_DIR, 'third_party', name, 'src')
dest_dir = os.path.join(gen_dir, name)
if func(src_dir, dest_dir, cpu, target_os, sysroot, parsed_args) != 0:
return 1
return 0
def _BoringSslGenerated():
"""Generates files for BoringSSL."""
logging.error('Generating files for boringssl...')
ssl_dir = os.path.join(ROOT_DIR, 'third_party', 'boringssl')
env = os.path.join(ssl_dir, 'src', 'util', 'bot', 'go', 'env.py')
generate = os.path.join(ssl_dir, 'src', 'util', 'generate_build_files.py')
return subprocess.call([sys.executable, env, 'python', generate, 'gn'],
cwd=ssl_dir)
# }}}
def _CreateArgParser():
"""Creates the argument parser for this script."""
# Note: dest values that end with '_' are used by this script; keys that do
# not end with '_' are GN argument names and are passed directly to GN.
parser = argparse.ArgumentParser(
description=__doc__, usage='%(prog)s [options]',
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument(
'--config-name', dest='config_name_', metavar='NAME',
help='Do a special in-tree build with this configuration name.')
parser.add_argument(
'--ide', choices=['eclipse', 'vs', 'vs2013', 'vs2015', 'vs2017', 'xcode',
'qtcreator', 'json'],
dest='ide_', help='The name of an IDE to generate project files for.')
parser.add_argument(
'--recover', dest='recover_', action='store_true',
help='Generate ninja files for an existing configuration.')
type_parser = parser.add_argument_group('Build Types')
type_parser.add_argument(
'--debug', action='store_true', dest='is_debug', default=True,
help='Build in debug mode (default).')
type_parser.add_argument(
'--release', action='store_false', dest='is_debug', default=True,
help='Build in release mode.')
type_parser.add_argument(
'--disable-demo', action='store_false', dest='enable_demo', default=True,
help="Don't build the demo app.")
type_parser.add_argument(
'--disable-tests', action='store_false', dest='enable_tests',
default=True, help="Don't build the unit tests.")
type_parser.add_argument(
'--enable-shared', action='store_true', dest='enable_shared',
default=True, help=argparse.SUPPRESS)
type_parser.add_argument(
'--disable-shared', action='store_false', dest='enable_shared',
default=True, help="Don't build a shared library.")
type_parser.add_argument(
'--enable-static', action='store_true', dest='enable_static',
default=False, help='Build a static library.')
type_parser.add_argument(
'--disable-static', action='store_false', dest='enable_static',
default=False, help=argparse.SUPPRESS)
engine_parser = parser.add_argument_group('JavaScript Engines')
engine_parser.add_argument(
'--v8', action='store_const', dest='js_engine', const='v8',
help='Use V8 (Chrome) as the JavaScript engine.')
engine_parser.add_argument(
'--jsc', action='store_const', dest='js_engine', const='jsc',
help='Use JavaScriptCore (Safari) as the JavaScript engine.')
media_parser = parser.add_argument_group(
'Media Options',
description='These settings are passed directly to FFmpeg, so see '
'their documentation for\nsupported values.')
media_parser.add_argument(
'--containers', dest='containers_', metavar='CONTAINERS', default=None,
help='A comma separated list of media containers to support.')
media_parser.add_argument(
'--codecs', dest='codecs_', metavar='CODECS', default=None,
help='A comma separated list of media codecs to support.')
# TODO: Test with other hardware decoders/accelerators.
media_parser.add_argument(
'--extra-decoders', dest='extra_decoders_', metavar='EXTRA_DECODERS',
default='h264_cuvid,hevc_cuvid,vp8_cuvid,vp9_cuvid,aac_at,ac3_at',
help='A comma separated list of extra decoders to use. These should be '
'used for hardware decoders (e.g. "h264_cuvid"), "plain" codecs '
'should be in --codecs. Any unsupported values are removed.')
media_parser.add_argument(
'--hwaccels', dest='hwaccels_', metavar='HWACCELS',
default='h264_nvdec,h264_videotoolbox,hevc_nvdec,hevc_videotoolbox,'
'vp8_nvdec,vp9_nvdec',
help='A comma separated list of hardware acelerators to use. Any '
'unsupported values are removed.')
media_parser.add_argument(
'--disable-hardware-decode', dest='enable_hardware_decode',
action='store_false', help='Disable hardware accelerated decode.')
media_parser.add_argument(
'--force-hardware-decode', dest='force_hardware_decode',
action='store_const', const=True,
help='Require hardware accelerated or OS-provided decoding.')
media_parser.add_argument(
'--no-force-hardware-decode', dest='force_hardware_decode',
action='store_const', const=False,
help="Don't force hardware-decoding on iOS.")
sanitizer = parser.add_argument_group('Sanitizers')
sanitizer.add_argument(
'--asan', dest='is_asan', action='store_true',
help='AddressSanitizer to find memory bugs.')
sanitizer.add_argument(
'--tsan', dest='is_tsan', action='store_true',
help='ThreadSanitizer to detect data races.')
sanitizer.add_argument(
'--ubsan', dest='is_ubsan', action='store_true',
help='UndefinedBehaviorSanitizer to find undefined behavior bugs.')
extra_parser = parser.add_argument_group('Extra arguments')
extra_parser.add_argument(
'--cpu', dest='target_cpu', choices=['x86', 'x64', 'arm', 'arm64'],
help='Sets the target CPU to build for.')
extra_parser.add_argument(
'--ios', action='store_const', dest='target_os', const='ios',
help='Build for iOS devices (only available on Mac).')
extra_parser.add_argument(
'--sdl-utils', action='store_const', dest='sdl_utils', const=True,
help='Include SDL utilities in the Library.')
extra_parser.add_argument(
'--no-sdl-utils', action='store_const', dest='sdl_utils', const=False,
help="Don't include SDL utilities in the Library.")
extra_parser.add_argument(
'--ios-sdl-demo', action='store_const', dest='ios_sdl_demo', const=True,
help='Use SDL for the iOS demo app.')
extra_parser.add_argument(
'--eme-impl', action='append', dest='eme_impls_',
help='Include the given EME implementation in the build. Can be given '
'multiple times.')
extra_parser.add_argument(
'--ccache-if-possible', dest='cc_wrapper', action=_MaybeUseCcache,
help='Use ccache to speed up builds, if found on PATH.')
extra_parser.add_argument(
'--v8-debug', action='store_false', dest='v8_optimized_debug',
default=None,
help='Enable debugging symbols and disable optimizations in V8.')
extra_parser.add_argument(
'--gn-args', dest='gn_args_', default='', metavar='ARGS',
help='A space separated list of extra arguments for GN.')
extra_parser.add_argument(
'--no-makefile', dest='makefile_', action='store_false',
help="Don't create a Makefile in the working directory.")
return parser
def _ParseArgs(args):
"""Parses the given command-line args and validates them."""
parser = _CreateArgParser()
parsed_args = parser.parse_args(args)
is_ios = parsed_args.target_os == 'ios'
if (parsed_args.v8_optimized_debug is not None and
parsed_args.js_engine != 'v8'):
parser.error('--v8-debug is only valid with --v8.')
if is_ios and platform.uname()[0] != 'Darwin':
parser.error('Can only build for iOS on Mac.')
if parsed_args.is_ubsan and parsed_args.is_debug:
parser.error('Can only use --ubsan with --release.')
if not parsed_args.enable_shared and not parsed_args.enabled_static:
parser.error('Not configured to build something; use --enable-static or '
'--enable-shared.')
if (os.path.abspath(os.getcwd()) == os.path.abspath(ROOT_DIR) and
not parsed_args.config_name_):
parser.error('Either do an out-of-tree build or use --config-name.')
if parsed_args.sdl_utils is False and parsed_args.enable_demo and not is_ios:
parser.error('Cannot disable SDL utils with the default demo; disable it '
'with --disable-demo.')
if parsed_args.sdl_utils is False and parsed_args.ios_sdl_demo:
parser.error('Cannot pass both --ios-sdl-demo and --no-sdl-utils')
if not parsed_args.enable_demo and parsed_args.ios_sdl_demo:
parser.error('Cannot pass both --disable-demo and --ios-sdl-demo')
if parsed_args.cc_wrapper and (parsed_args.is_asan or parsed_args.is_tsan or
parsed_args.is_ubsan):
logging.warning('Using ccache with sanitizers is not advised since '
'it will not recompile if you change the blacklists.')
if parsed_args.js_engine is None:
parsed_args.js_engine = 'jsc' if is_ios else 'v8'
if not is_ios and parsed_args.sdl_utils is None:
parsed_args.sdl_utils = True
if parsed_args.ios_sdl_demo:
parsed_args.sdl_utils = True
if parsed_args.is_ubsan:
parsed_args.is_ubsan_null = True
parsed_args.is_ubsan_vptr = True
if parsed_args.eme_impls_:
parsed_args.eme_implementations = []
for impl in parsed_args.eme_impls_:
if not os.path.exists(impl):
parser.error('Unable to find EME implementation %r' % impl)
parsed_args.eme_implementations.append(
os.path.relpath(os.path.abspath(impl), ROOT_DIR))
if not parsed_args.containers_:
if is_ios:
parsed_args.containers_ = 'mov'
else:
parsed_args.containers_ = 'matroska,mov'
if not parsed_args.codecs_:
if is_ios:
parsed_args.codecs_ = 'h264,hevc,aac'
else:
parsed_args.codecs_ = 'h264,hevc,vp8,vp9,aac,aac_latm,ac3,opus,vorbis'
return parsed_args
def main(args):
parsed_args = _ParseArgs(args)
# We can't ask GN what the default JavaScript engine is because we haven't
# downloaded it yet. We can't download it first because we need to load the
# submodule that contains its hash.
_LoadSubmodules(parsed_args.js_engine == 'v8')
# Download GN before we do anything else.
if _DownloadGn() != 0:
return 1
# Need to generate boringssl before running GN since this generates .gni
# files needed by GN.
if _BoringSslGenerated() != 0:
return 1
if parsed_args.recover_:
return RecoverGn(parsed_args.config_name_)
# We need to generate GN files first so we can query things like target_os.
gn_args = _ConstructGnArgs(parsed_args)
if GenGn(parsed_args.config_name_, gn_args, parsed_args.ide_) != 0:
return 1
if _RunThirdPartyConfigure(parsed_args) != 0:
return 1
# After we have generated third-party dependencies, we need to update the GN
# configurations for extra third-party files.
logging.error('Generating build files...')
gn_args = _ConstructGnArgs(parsed_args)
if GenGn(parsed_args.config_name_, gn_args, parsed_args.ide_) != 0:
return 1
if parsed_args.makefile_:
with open(os.path.join(ROOT_DIR, 'Makefile.in')) as f:
with open('Makefile', 'w') as out:
out.write(f.read()
.replace('{{SOURCE_ROOT}}', ROOT_DIR)
.replace('{{CONFIG_NAME}}', parsed_args.config_name_ or '')
.replace('{{TARGET_OS}}', parsed_args.target_os or ''))
return 0
if __name__ == '__main__':
logging.basicConfig(format='')
sys.exit(main(sys.argv[1:]))
<file_sep>/shaka/src/media/types.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/types.h"
#include "src/util/utils.h"
namespace shaka {
namespace media {
std::ostream& operator<<(std::ostream& os, const BufferedRange& range) {
return os << util::StringPrintf("{ start: %.2f, end: %.2f }", range.start,
range.end);
}
std::string GetErrorString(Status status) {
switch (status) {
case Status::Success:
return "The operation succeeded";
case Status::Detached:
return "The MediaSource/SourceBuffer has been detached and destroyed";
case Status::EndOfStream:
return "INTERNAL BUG: Unexpected end of stream";
case Status::QuotaExceeded:
return "Attempted to append media that would exceed the allowed quota";
case Status::OutOfMemory:
return "The system wasn't able to allocate the required memory";
case Status::NotSupported:
return "The specified action is not supported";
case Status::NotAllowed:
return "The specified action is not allowed";
case Status::UnknownError:
return "An unknown error occurred; see log for system codes";
case Status::CannotOpenDemuxer:
return "Unable to initialize the demuxer";
case Status::NoStreamsFound:
return "The input stream didn't have any elementary streams";
case Status::MultiplexedContentFound:
return "The input stream contained multiplexed content";
case Status::InvalidContainerData:
return "The container data was in an invalid format";
case Status::DecoderMismatch:
return "The codec in the content didn't match the value initialized with";
case Status::DecoderFailedInit:
return "Unable to initialize the decoder";
case Status::InvalidCodecData:
return "The codec data was in an invalid format";
case Status::KeyNotFound:
return "The required encryption key was not found";
}
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/js/events/event_target.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_EVENTS_EVENT_TARGET_H_
#define SHAKA_EMBEDDED_JS_EVENTS_EVENT_TARGET_H_
#include <list>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include "shaka/optional.h"
#include "src/core/js_manager_impl.h"
#include "src/core/member.h"
#include "src/core/ref_ptr.h"
#include "src/debug/thread_event.h"
#include "src/js/events/event.h"
#include "src/js/events/event_names.h"
#include "src/mapping/backing_object.h"
#include "src/mapping/backing_object_factory.h"
#include "src/mapping/callback.h"
#include "src/mapping/exception_or.h"
namespace shaka {
namespace js {
namespace events {
class EventTarget : public BackingObject {
DECLARE_TYPE_INFO(EventTarget);
public:
EventTarget();
using Listener = optional<Callback>;
void Trace(memory::HeapTracer* tracer) const override;
/**
* Adds a js-backed event listener to the target.
* @param type The name of the event to listen for.
* @param callback The listener for the event. Must be a function.
*/
void AddEventListener(const std::string& type, Listener callback);
/**
* Adds a not-js-backed event listener to the target.
* There should only be one such event listener per event.
* @param type The name of the event to listen for.
* @param callback The listener for the event. Must be a function.
*/
void SetCppEventListener(EventType type, std::function<void()> callback);
/**
* Removes a js-backed event listener from the target.
* @param type The name of the event to remove.
* @param callback The listener to remove.
*/
void RemoveEventListener(const std::string& type, Listener callback);
/**
* Removes a not-js-backed event listener from the target.
* @param type The name of the event to remove.
*/
void UnsetCppEventListener(EventType type);
/**
* Dispatches the event to the current object. This method blocks until the
* event is complete. The event is treated as not trusted even if it comes
* from internal code (Shaka Player doesn't care). This must be called from
* the event thread.
* @param event The event to dispatch.
* @return False if one listener called preventDefault, otherwise true.
*/
ExceptionOr<bool> DispatchEvent(RefPtr<Event> event);
/**
* Asynchronously raises the given event on this. It is safe to call this
* from any thread. There needs to be an explicit type parameter for the type
* of event to raise, the remaining types should be arguments to its
* constructor. The constructor used does not need to be the one used from
* JavaScript.
*/
template <typename EventType, typename... Args>
std::shared_ptr<ThreadEvent<bool>> ScheduleEvent(Args&&... args) {
RefPtr<EventType> event = new EventType(std::forward<Args>(args)...);
return JsManagerImpl::Instance()->MainThread()->AddInternalTask(
TaskPriority::Events, std::string("Schedule ") + EventType::name(),
ScheduleEventTask<EventType>(this, event));
}
/**
* Synchronously raises the given event on this. This must only be called
* from the event thread.
*/
template <typename EventType, typename... Args>
ExceptionOr<bool> RaiseEvent(Args... args) {
RefPtr<EventType> backing = new EventType(args...);
return this->DispatchEvent(backing);
}
protected:
/** Registers an event on the target. */
void AddListenerField(EventType type, Listener* on_field) {
on_listeners_[to_string(type)] = on_field;
}
private:
template <typename E>
class ScheduleEventTask : public memory::Traceable {
public:
ScheduleEventTask(EventTarget* target, RefPtr<E> event)
: target_(target), event_(event) {}
~ScheduleEventTask() override {}
void Trace(memory::HeapTracer* tracer) const override {
tracer->Trace(&target_);
tracer->Trace(&event_);
}
bool operator()() {
ExceptionOr<bool> val = target_->DispatchEvent(event_);
if (holds_alternative<bool>(val)) {
return get<bool>(val);
} else {
LocalVar<JsValue> except = get<js::JsError>(val).error();
LOG(INFO) << "Exception thrown while raising event: "
<< ConvertToString(except);
return false;
}
}
private:
Member<EventTarget> target_;
Member<E> event_;
};
struct ListenerInfo {
ListenerInfo(Listener listener, const std::string& type);
~ListenerInfo();
Listener callback_;
std::string type_;
bool should_remove_;
};
/** Invokes all the listeners for the given event */
void InvokeListeners(RefPtr<Event> event);
/** Finds the listener info that matches the given callback. */
std::list<ListenerInfo>::iterator FindListener(const Listener& callback,
const std::string& type);
std::unordered_map<std::string, std::function<void()>> cpp_listeners_;
// Elements are stored in insert order. Use a list since we store an iterator
// while invoking and it needs to remain valid with concurrent inserts. This
// will also have faster removals since we only use iterators.
std::list<ListenerInfo> listeners_;
// A map of the on-event listeners (e.g. onerror).
std::unordered_map<std::string, Listener*> on_listeners_;
bool is_dispatching_;
};
class EventTargetFactory : public BackingObjectFactory<EventTarget> {
public:
EventTargetFactory();
};
} // namespace events
} // namespace js
} // namespace shaka
#endif // SHAKA_EMBEDDED_JS_EVENTS_EVENT_TARGET_H_
<file_sep>/shaka/src/js/dom/document.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/dom/document.h"
#include "src/js/dom/comment.h"
#include "src/js/dom/element.h"
#include "src/js/dom/text.h"
#include "src/js/mse/video_element.h"
#include "src/memory/heap_tracer.h"
#include "src/util/clock.h"
namespace shaka {
namespace js {
namespace dom {
std::atomic<Document*> Document::instance_{nullptr};
Document::Document()
: ContainerNode(DOCUMENT_NODE, nullptr),
created_at_(util::Clock::Instance.GetMonotonicTime()) {}
// \cond Doxygen_Skip
Document::~Document() {
if (instance_ == this)
instance_ = nullptr;
}
// \endcond Doxygen_Skip
// static
Document* Document::CreateGlobalDocument() {
DCHECK(instance_ == nullptr);
return (instance_ = new Document());
}
std::string Document::node_name() const {
return "#document";
}
optional<std::string> Document::NodeValue() const {
return nullopt;
}
optional<std::string> Document::TextContent() const {
return nullopt;
}
RefPtr<Element> Document::DocumentElement() const {
for (auto& child : child_nodes()) {
if (child->is_element())
return static_cast<Element*>(child.get());
}
return nullptr;
}
RefPtr<Element> Document::CreateElement(const std::string& name) {
if (name == "video") {
// This should only be used in Shaka Player integration tests.
return new mse::HTMLVideoElement(this);
}
return new Element(this, name, nullopt, nullopt);
}
RefPtr<Comment> Document::CreateComment(const std::string& data) {
return new Comment(this, data);
}
RefPtr<Text> Document::CreateTextNode(const std::string& data) {
return new Text(this, data);
}
DocumentFactory::DocumentFactory() {
AddMemberFunction("createElement", &Document::CreateElement);
AddMemberFunction("createComment", &Document::CreateComment);
AddMemberFunction("createTextNode", &Document::CreateTextNode);
AddGenericProperty("documentElement", &Document::DocumentElement);
// TODO: Consider adding createEvent. Shaka Player only uses it in the
// Microsoft EME polyfill and the unit tests.
NotImplemented("createEvent");
NotImplemented("createElementNS");
NotImplemented("createDocumentFragment");
NotImplemented("createCDATASection");
NotImplemented("createProcessingInstruction");
NotImplemented("createAttribute");
NotImplemented("createAttributeNS");
NotImplemented("createRange");
NotImplemented("createNodeIterator");
NotImplemented("createTreeWalker");
NotImplemented("importNode");
NotImplemented("adoptNode");
}
} // namespace dom
} // namespace js
} // namespace shaka
<file_sep>/shaka/src/mapping/callback.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MAPPING_CALLBACK_H_
#define SHAKA_EMBEDDED_MAPPING_CALLBACK_H_
#include <string>
#include <utility>
#include "src/mapping/convert_js.h"
#include "src/mapping/js_engine.h"
#include "src/mapping/js_wrappers.h"
#include "src/mapping/weak_js_ptr.h"
namespace shaka {
/**
* Defines a helper type that is used to store and call JavaScript functions.
* This wraps a given callback and converts it into a C++ std::function. This
* will swallow exceptions, printing the stack trace in the debug log if one is
* thrown.
*/
class Callback : public GenericConverter, public memory::Traceable {
public:
static std::string name() {
return "function";
}
Callback();
~Callback() override;
Callback(const Callback&);
Callback(Callback&&);
Callback& operator=(const Callback&);
Callback& operator=(Callback&&);
bool empty() const {
return callback_.empty();
}
bool operator==(const Callback& other) const {
return callback_ == other.callback_;
}
bool operator!=(const Callback& other) const {
return callback_ != other.callback_;
}
template <typename... Args>
void operator()(Args&&... args) const {
DCHECK(!empty());
// Add another element to avoid a 0-length array with no arguments. This
// won't change the number of arguments passed in JavaScript.
LocalVar<JsValue> arguments[] = {
::shaka::ToJsValue(std::forward<Args>(args))..., JsUndefined()};
LocalVar<JsValue> except;
if (!InvokeMethod(callback_.handle(), JsEngine::Instance()->global_handle(),
sizeof...(Args), arguments, &except)) {
OnUncaughtException(except, /* in_promise */ false);
}
}
template <typename T, typename... Args>
void CallWithThis(T&& that, Args&&... args) const {
DCHECK(!empty());
LocalVar<JsValue> that_val = ::shaka::ToJsValue(that);
LocalVar<JsObject> that_obj = UnsafeJsCast<JsObject>(that_val);
LocalVar<JsValue> arguments[] = {
::shaka::ToJsValue(std::forward<Args>(args))..., JsUndefined()};
LocalVar<JsValue> except;
if (!InvokeMethod(callback_.handle(), that_obj, sizeof...(Args), arguments,
&except)) {
OnUncaughtException(except, /* in_promise */ false);
}
}
bool TryConvert(Handle<JsValue> given) override;
ReturnVal<JsValue> ToJsValue() const override;
void Trace(memory::HeapTracer* tracer) const override;
private:
WeakJsPtr<JsFunction> callback_;
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_MAPPING_CALLBACK_H_
<file_sep>/shaka/test/src/memory/object_tracker_integration.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/memory/object_tracker.h"
// TODO: Add tests for JSC.
#ifdef USING_V8
# include <gtest/gtest.h>
# include <array>
# include <functional>
# include "src/core/js_manager_impl.h"
# include "src/core/member.h"
# include "src/core/ref_ptr.h"
# include "src/mapping/backing_object.h"
# include "src/mapping/backing_object_factory.h"
# include "src/mapping/js_wrappers.h"
# include "src/mapping/weak_js_ptr.h"
# include "src/memory/heap_tracer.h"
# include "src/memory/v8_heap_tracer.h"
# include "src/test/v8_test.h"
# include "src/util/pseudo_singleton.h"
# define DEFINE_HANDLES(var) v8::HandleScope var(isolate())
namespace shaka {
namespace memory {
namespace {
void Noop() {}
class TestObject : public BackingObject {
DECLARE_TYPE_INFO(TestObject);
public:
TestObject(bool* is_free) : is_free_(is_free) {
*is_free = false;
}
bool has_been_traced() const {
return has_been_traced_;
}
void Trace(HeapTracer* tracer) const override {
BackingObject::Trace(tracer);
has_been_traced_ = true;
tracer->Trace(&member1);
tracer->Trace(&member2);
tracer->Trace(&v8_member);
on_trace();
}
Member<TestObject> member1;
Member<TestObject> member2;
WeakJsPtr<JsObject> v8_member;
std::function<void()> on_destroy = &Noop;
std::function<void()> on_trace = &Noop;
private:
bool* is_free_;
mutable bool has_been_traced_ = false;
};
TestObject::~TestObject() {
EXPECT_FALSE(*is_free_);
*is_free_ = true;
on_destroy();
}
class ReusableTestObject : public TestObject {
public:
ReusableTestObject(int* free_count)
: TestObject(&is_free_), free_count_(free_count) {}
~ReusableTestObject() override {
++*free_count_;
}
static void operator delete(void* ptr) {
// Don't free it since the object is stack allocated.
}
private:
int* free_count_;
bool is_free_;
};
class TestObjectFactory : public BackingObjectFactory<TestObject> {
public:
TestObjectFactory() {}
};
} // namespace
class ObjectTrackerIntegration
: public V8Test,
public PseudoSingleton<ObjectTrackerIntegration> {
public:
static BackingObjectFactoryBase* factory() {
return Instance()->factory_.get();
}
void SetUp() override {
V8Test::SetUp();
isolate()->SetEmbedderHeapTracer(&v8_heap_tracer_);
factory_.reset(new TestObjectFactory);
}
void TearDown() override {
// Perform a full V8 GC to clean up any leftover objects.
tracker_.Dispose();
factory_.reset();
V8Test::TearDown();
}
protected:
ReturnVal<JsValue> Wrap(TestObject* ptr) {
return factory_->WrapInstance(ptr);
}
void SetMember(Handle<JsObject> obj, const std::string& name,
TestObject* ptr) {
DEFINE_HANDLES(handles);
LocalVar<JsValue> value;
if (!ptr)
value = JsUndefined();
else
value = Wrap(ptr);
SetMemberRaw(obj, name, value);
}
void SetMember(WeakJsPtr<JsObject> obj, const std::string& name,
TestObject* ptr) {
DEFINE_HANDLES(handles);
SetMember(obj.handle(), name, ptr);
}
void SetMember(WeakJsPtr<JsObject> obj, const std::string& name,
WeakJsPtr<JsObject> other) {
DEFINE_HANDLES(handles);
LocalVar<JsValue> value(other.value());
SetMemberRaw(obj.handle(), name, value);
}
void SetGlobal(const std::string& name, TestObject* ptr) {
DEFINE_HANDLES(handles);
SetMember(JsEngine::Instance()->global_handle(), name, ptr);
}
WeakJsPtr<JsObject> CreateWeakObject() {
DEFINE_HANDLES(handles);
return CreateObject();
}
void RunGc() {
isolate()->RequestGarbageCollectionForTesting(
v8::Isolate::kFullGarbageCollection);
}
ObjectTracker tracker_;
V8HeapTracer v8_heap_tracer_{tracker_.heap_tracer(), &tracker_};
std::unique_ptr<TestObjectFactory> factory_;
};
BackingObjectFactoryBase* TestObject::factory() const {
return ObjectTrackerIntegration::Instance()->factory();
}
TEST_F(ObjectTrackerIntegration, BasicFlow) {
bool is_free1, is_free2, is_free3;
RefPtr<TestObject> obj1(new TestObject(&is_free1));
{
RefPtr<TestObject> obj2(new TestObject(&is_free2));
new TestObject(&is_free3);
}
EXPECT_FALSE(is_free1);
EXPECT_FALSE(is_free2);
EXPECT_FALSE(is_free3);
// obj1 is still alive, so should not get collected.
RunGc();
EXPECT_FALSE(is_free1);
EXPECT_TRUE(is_free2);
EXPECT_TRUE(is_free3);
obj1.reset();
RunGc();
EXPECT_TRUE(is_free1);
}
TEST_F(ObjectTrackerIntegration, AliveThroughJavaScript) {
bool is_free1, is_free2;
TestObject* obj1(new TestObject(&is_free1));
new TestObject(&is_free2);
SetGlobal("key", obj1);
// We don't hold a C++ reference to it, but JavaScript does so it should not
// be freed.
RunGc();
EXPECT_FALSE(is_free1);
EXPECT_TRUE(is_free2);
// Un-setting the JavaScript variable, then the object should be freed.
SetGlobal("key", nullptr);
RunGc();
EXPECT_TRUE(is_free1);
EXPECT_TRUE(is_free2);
}
TEST_F(ObjectTrackerIntegration, AliveIndirectly) {
bool is_free_root, is_free1, is_free2, is_free3, is_free_dead;
TestObject* root = new TestObject(&is_free_root);
TestObject* obj1 = new TestObject(&is_free1);
TestObject* obj2 = new TestObject(&is_free2);
TestObject* obj3 = new TestObject(&is_free3);
TestObject* dead = new TestObject(&is_free_dead);
root->member1 = obj1;
root->member2 = obj2;
obj1->member1 = obj2;
obj1->member2 = obj3;
obj3->member1 = root;
dead->member1 = root;
RefPtr<TestObject> handle(root);
RunGc();
EXPECT_FALSE(is_free_root);
EXPECT_FALSE(is_free1);
EXPECT_FALSE(is_free2);
EXPECT_FALSE(is_free3);
EXPECT_TRUE(is_free_dead);
handle.reset();
// Should free |root| and all indirect children.
RunGc();
EXPECT_TRUE(is_free_root);
EXPECT_TRUE(is_free1);
EXPECT_TRUE(is_free2);
EXPECT_TRUE(is_free3);
}
TEST_F(ObjectTrackerIntegration, FreesIndirectV8Objects) {
bool is_free_root, is_free1;
TestObject* root = new TestObject(&is_free_root);
TestObject* obj = new TestObject(&is_free1);
root->member1 = root;
// Create a weak pointer to a V8 object. This will become empty if the
// object is destroyed.
WeakJsPtr<JsObject> v8_object = CreateWeakObject();
obj->v8_member = v8_object;
EXPECT_FALSE(is_free_root);
EXPECT_FALSE(is_free1);
EXPECT_FALSE(v8_object.empty());
RunGc();
EXPECT_TRUE(is_free_root);
EXPECT_TRUE(is_free1);
EXPECT_TRUE(v8_object.empty());
}
TEST_F(ObjectTrackerIntegration, AliveIndirectlyThroughJavaScript) {
// An object is alive because it is held by a JavaScript object that is held
// by an alive backing object.
bool is_free_root, is_free_other;
TestObject* root = new TestObject(&is_free_root);
TestObject* other = new TestObject(&is_free_other);
RefPtr<TestObject> handle(root);
WeakJsPtr<JsObject> v8_object = CreateWeakObject();
root->v8_member = v8_object;
SetMember(v8_object, "key", other);
// -> root -> v8_object -> other
// Because we have |handle| all the objects should remain alive.
RunGc();
EXPECT_FALSE(is_free_root);
EXPECT_FALSE(is_free_other);
// Clear |handle| and ensure all the objects are destroyed.
handle.reset();
RunGc();
EXPECT_TRUE(is_free_root);
EXPECT_TRUE(is_free_other);
}
TEST_F(ObjectTrackerIntegration, ComplexReferences) {
// A complex network of JavaScript and backing objects referencing each other.
bool is_free_root, is_free_a, is_free_b, is_free_c, is_free_d, is_free_e;
bool is_free_dead;
TestObject* root = new TestObject(&is_free_root);
TestObject* A = new TestObject(&is_free_a);
TestObject* B = new TestObject(&is_free_b);
TestObject* C = new TestObject(&is_free_c);
TestObject* D = new TestObject(&is_free_d);
TestObject* E = new TestObject(&is_free_e);
TestObject* dead = new TestObject(&is_free_dead);
WeakJsPtr<JsObject> W = CreateWeakObject();
WeakJsPtr<JsObject> X = CreateWeakObject();
WeakJsPtr<JsObject> Y = CreateWeakObject();
WeakJsPtr<JsObject> Z = CreateWeakObject();
WeakJsPtr<JsObject> v8_dead = CreateWeakObject();
RefPtr<TestObject> handle(root);
{
root->member1 = A;
root->member2 = B;
A->member1 = B;
A->member2 = C;
B->v8_member = W;
SetMember(W, "mem", C);
SetMember(W, "mem2", X);
SetMember(X, "mem", D);
D->v8_member = Y;
SetMember(Y, "mem", E);
SetMember(Y, "mem2", root);
E->member1 = D;
E->v8_member = Z;
dead->v8_member = v8_dead;
}
RunGc();
EXPECT_FALSE(is_free_root);
EXPECT_FALSE(is_free_a);
EXPECT_FALSE(is_free_b);
EXPECT_FALSE(is_free_c);
EXPECT_FALSE(is_free_d);
EXPECT_FALSE(is_free_e);
EXPECT_TRUE(is_free_dead);
EXPECT_FALSE(W.empty());
EXPECT_FALSE(X.empty());
EXPECT_FALSE(Y.empty());
EXPECT_FALSE(Z.empty());
EXPECT_TRUE(v8_dead.empty());
handle.reset();
RunGc();
EXPECT_TRUE(is_free_root);
EXPECT_TRUE(is_free_a);
EXPECT_TRUE(is_free_b);
EXPECT_TRUE(is_free_c);
EXPECT_TRUE(is_free_d);
EXPECT_TRUE(is_free_e);
EXPECT_TRUE(is_free_dead);
EXPECT_TRUE(W.empty());
EXPECT_TRUE(X.empty());
EXPECT_TRUE(Y.empty());
EXPECT_TRUE(Z.empty());
EXPECT_TRUE(v8_dead.empty());
}
TEST_F(ObjectTrackerIntegration, SupportsMoveWhileRunning) {
bool is_free_dest, is_free_middle, is_free_source, is_free_extra;
TestObject* dest = new TestObject(&is_free_dest);
TestObject* middle = new TestObject(&is_free_middle);
TestObject* source = new TestObject(&is_free_source);
TestObject* extra = new TestObject(&is_free_extra);
WeakJsPtr<JsObject> dest_v8 = CreateWeakObject();
WeakJsPtr<JsObject> middle_v8 = CreateWeakObject();
WeakJsPtr<JsObject> source_v8 = CreateWeakObject();
RefPtr<TestObject> handle(dest);
{
dest->v8_member = dest_v8;
SetMember(dest_v8, "abc", middle);
middle->v8_member = middle_v8;
SetMember(middle_v8, "abc", source);
source->member1 = extra;
}
middle->on_trace = [&]() {
// We should have already traced |dest|, but |source| should not have been
// traced. This will move |member1| from |source| to |dest|. This would
// normally cause a memory leak since |dest| has already been traced so we
// would lose the member.
//
// This is also testing a number of related bugs such as allocating new
// objects on background threads. This is important since JavaScript
// can run between GC steps. However, this is probably unlikely to
// happen since JavaScript references are handled by V8, so this will
// only happen if our code does something like this.
EXPECT_FALSE(source->has_been_traced());
EXPECT_TRUE(dest->has_been_traced());
dest->member1 = std::move(source->member1);
};
RunGc();
EXPECT_FALSE(is_free_dest);
EXPECT_FALSE(is_free_middle);
EXPECT_FALSE(is_free_source);
EXPECT_FALSE(is_free_extra);
handle.reset();
middle->on_trace = &Noop;
RunGc();
}
TEST_F(ObjectTrackerIntegration, SupportsCreatingNewObjects) {
bool is_free_first, is_free_creator, is_free_createe = false;
new TestObject(&is_free_first);
TestObject* createe = nullptr;
TestObject* creator = new TestObject(&is_free_creator);
creator->on_destroy = [&]() { createe = new TestObject(&is_free_createe); };
RunGc();
EXPECT_TRUE(is_free_first);
EXPECT_TRUE(is_free_creator);
EXPECT_TRUE(createe);
EXPECT_FALSE(is_free_createe);
RunGc();
EXPECT_TRUE(is_free_createe);
}
TEST_F(ObjectTrackerIntegration, CanReusePointers) {
bool is_free_first;
int free_count = 0;
std::array<uint8_t, sizeof(ReusableTestObject)> memory;
// Initialize the existing memory with the TestObject, this should register
// the pointer with the object tracker.
new (memory.data()) ReusableTestObject(&free_count);
TestObject* first = new TestObject(&is_free_first);
first->on_destroy = [&]() {
// The object should be freed already. Initialize the same memory again
// with a new object, which should re-register the same pointer.
ASSERT_EQ(free_count, 1u);
new (memory.data()) ReusableTestObject(&free_count);
};
RunGc();
EXPECT_TRUE(is_free_first);
EXPECT_EQ(free_count, 1u);
RunGc();
EXPECT_EQ(free_count, 2u);
}
TEST_F(ObjectTrackerIntegration, CanReuseObjectsInDispose) {
bool is_free_first;
int free_count = 0;
std::array<uint8_t, sizeof(ReusableTestObject)> memory;
// Initialize the existing memory with the TestObject, this should register
// the pointer with the object tracker.
new (memory.data()) ReusableTestObject(&free_count);
TestObject* first = new TestObject(&is_free_first);
first->on_destroy = [&]() {
// The object should be freed already. Initialize the same memory again
// with a new object, which should re-register the same pointer.
ASSERT_EQ(free_count, 1u);
new (memory.data()) ReusableTestObject(&free_count);
};
tracker_.Dispose();
EXPECT_TRUE(is_free_first);
EXPECT_EQ(free_count, 2u);
}
} // namespace memory
} // namespace shaka
#endif // USING_V8
<file_sep>/shaka/src/js/eme/media_key_session.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/eme/media_key_session.h"
#include <cmath>
#include <vector>
#include "src/js/js_error.h"
namespace shaka {
namespace js {
namespace eme {
MediaKeySession::MediaKeySession(MediaKeySessionType type,
ImplementationFactory* factory,
Implementation* implementation,
ImplementationHelperImpl* helper)
: mutex_("MediaKeySession"),
factory_(factory),
implementation_(implementation),
helper_(helper),
type_(type),
closed_promise_(closed, /* has_value */ false) {
AddListenerField(EventType::KeyStatusesChange, &on_key_statuses_change);
AddListenerField(EventType::Message, &on_message);
}
// \cond Doxygen_Skip
MediaKeySession::~MediaKeySession() {}
// \endcond Doxygen_Skip
void MediaKeySession::Trace(memory::HeapTracer* tracer) const {
EventTarget::Trace(tracer);
tracer->Trace(&closed);
}
std::string MediaKeySession::SessionId() const {
std::unique_lock<Mutex> lock(mutex_);
return session_id_;
}
ExceptionOr<double> MediaKeySession::GetExpiration() const {
const std::string session_id = SessionId();
if (session_id.empty())
return NAN;
int64_t expiration;
if (!implementation_->GetExpiration(session_id, &expiration)) {
return JsError::TypeError("Error getting the expiration");
}
return expiration < 0 ? NAN : expiration / 1000.0;
}
ExceptionOr<std::unordered_map<ByteBuffer, MediaKeyStatus>>
MediaKeySession::GetKeyStatuses() const {
std::vector<KeyStatusInfo> statuses;
const std::string session_id = SessionId();
if (!session_id.empty() &&
!implementation_->GetKeyStatuses(session_id, &statuses)) {
return JsError::TypeError("Error getting the key statuses");
}
std::unordered_map<ByteBuffer, MediaKeyStatus> ret(statuses.size());
for (auto& status : statuses) {
ret.emplace(ByteBuffer(status.key_id.data(), status.key_id.size()),
status.status);
}
return ret;
}
Promise MediaKeySession::GenerateRequest(MediaKeyInitDataType init_data_type,
ByteBuffer init_data) {
if (!SessionId().empty()) {
return Promise::Rejected(JsError::DOMException(
InvalidStateError, "Session already initialized"));
}
if (init_data.size() == 0) {
return Promise::Rejected(
JsError::TypeError("Initialization data is empty"));
}
if (!factory_->SupportsInitDataType(init_data_type)) {
return Promise::Rejected(JsError::DOMException(
NotSupportedError,
"CDM implementation doesn't support this initialization data type"));
}
auto cb = [this](const std::string& session_id) {
std::unique_lock<Mutex> lock(mutex_);
CHECK(session_id_.empty()) << "Cannot call set_session_id() twice.";
session_id_ = session_id;
};
Promise ret;
implementation_->CreateSessionAndGenerateRequest(
EmePromise(ret, /* has_value */ false), cb, type_, init_data_type,
Data(&init_data));
return ret;
}
Promise MediaKeySession::Load(const std::string& session_id) {
if (!SessionId().empty()) {
return Promise::Rejected(JsError::DOMException(
InvalidStateError, "Session already initialized"));
}
if (session_id.empty()) {
return Promise::Rejected(JsError::TypeError("Empty session ID"));
}
if (type_ != MediaKeySessionType::PersistentLicense) {
return Promise::Rejected(JsError::TypeError(
"Cannot load a persistent license in a temporary session"));
}
Promise ret;
implementation_->Load(session_id, EmePromise(ret, /* has_value */ true));
// TODO: This shouldn't be changed if the Promise is rejected.
session_id_ = session_id;
return ret;
}
Promise MediaKeySession::Update(ByteBuffer response) {
const std::string session_id = SessionId();
if (session_id.empty()) {
return Promise::Rejected(
JsError::DOMException(InvalidStateError, "Session not initialized"));
}
if (response.size() == 0) {
return Promise::Rejected(JsError::TypeError("Empty response data"));
}
Promise ret;
implementation_->Update(session_id, EmePromise(ret, /* has_value */ false),
Data(&response));
return ret;
}
Promise MediaKeySession::Close() {
const std::string session_id = SessionId();
if (session_id.empty()) {
return Promise::Resolved();
}
implementation_->Close(session_id, closed_promise_);
return closed;
}
Promise MediaKeySession::Remove() {
const std::string session_id = SessionId();
if (session_id.empty()) {
return Promise::Rejected(
JsError::DOMException(InvalidStateError, "Session not initialized"));
}
Promise ret;
implementation_->Remove(session_id, EmePromise(ret, /* has_value */ false));
return ret;
}
MediaKeySessionFactory::MediaKeySessionFactory() {
AddListenerField(EventType::KeyStatusesChange,
&MediaKeySession::on_key_statuses_change);
AddListenerField(EventType::Message, &MediaKeySession::on_message);
AddGenericProperty("sessionId", &MediaKeySession::SessionId);
AddReadOnlyProperty("closed", &MediaKeySession::closed);
AddGenericProperty("expiration", &MediaKeySession::GetExpiration);
AddGenericProperty("keyStatuses", &MediaKeySession::GetKeyStatuses);
AddMemberFunction("generateRequest", &MediaKeySession::GenerateRequest);
AddMemberFunction("load", &MediaKeySession::Load);
AddMemberFunction("update", &MediaKeySession::Update);
AddMemberFunction("close", &MediaKeySession::Close);
AddMemberFunction("remove", &MediaKeySession::Remove);
}
} // namespace eme
} // namespace js
} // namespace shaka
<file_sep>/shaka/tools/run_ios_tests.py
#!/usr/bin/python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Runs the unit tests on an iOS simulator."""
from __future__ import print_function
import argparse
import contextlib
import json
import os
import subprocess
import sys
_APP_NAME = 'org.chromium.gtest.generic-unit-test'
_IOS_SIM_PREFIX = 'com.apple.CoreSimulator.SimRuntime.iOS-'
_SIMULATOR_PATH = ('/Applications/Xcode.app/Contents/Developer/Applications/'
'Simulator.app/Contents/MacOS/Simulator')
_PASS_SIGNAL_LINE = 'TEST RESULTS: PASS'
_FAIL_SIGNAL_LINE = 'TEST RESULTS: FAIL'
_MIN_VERSION = (10,)
_ROOT_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'..', '..')
@contextlib.contextmanager
def _TerminateProcess(proc):
"""A context manager that terminates the given process at the end."""
yield proc
proc.kill()
def _ConfigPath(config):
"""Returns the path to the given config name."""
return os.path.join(_ROOT_DIR, 'out', config) if config else '.'
def _FindIosSimulator():
"""Returns a tuple of a UUID and whether it is booted."""
try:
output = subprocess.check_output(['xcrun', 'simctl', 'list', '-j',
'devices'])
except OSError:
print('Error running "xcrun", do you have XCode installed? Try running:',
file=sys.stderr)
print(' xcode-select --install', file=sys.stderr)
raise
obj = json.loads(output)
largest_version = None
largest_uuid = None
for key, value in obj['devices'].iteritems():
if key.startswith(_IOS_SIM_PREFIX):
version = key[len(_IOS_SIM_PREFIX):].replace('-', '.')
elif key.startswith('iOS '):
version = key[4:]
else:
continue
version = tuple(int(part) for part in version.split('.'))
for sim in value:
if sim['state'] == 'Booted' and version >= _MIN_VERSION:
return (sim['udid'], True)
if (not largest_version or version > largest_version and
sim['availability'] == '(available)'):
largest_version = version
largest_uuid = sim['udid']
if not largest_uuid:
raise KeyError('Unable to find a usable simulator')
return (largest_uuid, False)
def _InstallApp(uuid, app_dir, is_booted):
"""Installs the given app on the simulator."""
if not is_booted:
subprocess.check_call(['xcrun', 'simctl', 'boot', uuid])
subprocess.check_call(['xcrun', 'simctl', 'install', uuid, app_dir])
def _StartTests(uuid, log_path):
"""Launches the test app on the simulator."""
subprocess.check_call(['xcrun', 'simctl', 'terminate', uuid, _APP_NAME])
subprocess.check_call(['xcrun', 'simctl', 'launch', '--stdout=' + log_path,
'--stderr=' + log_path, uuid, _APP_NAME])
def _PollLog(log_path):
"""Polls the log file and waits for the tests to exit."""
proc = subprocess.Popen(['tail', '-f', log_path], stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline().strip()
if line == _PASS_SIGNAL_LINE:
return 0
elif line == _FAIL_SIGNAL_LINE:
return 1
else:
print(line, file=sys.stderr)
def RunTests(build_dir):
"""Installs the given app, runs the tests, and prints the logs."""
log_path = os.path.join(build_dir, 'ios_tests.log')
try:
os.remove(log_path)
except OSError:
pass
with open(os.devnull, 'w') as null:
with _TerminateProcess(subprocess.Popen([_SIMULATOR_PATH], stdout=null,
stderr=null)):
uuid, is_booted = _FindIosSimulator()
_InstallApp(uuid, os.path.join(build_dir, 'tests.app'), is_booted)
_StartTests(uuid, log_path)
return _PollLog(log_path)
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--config-name', dest='config',
help='The name of the configuration to use.')
ns = parser.parse_args(args)
return RunTests(_ConfigPath(ns.config))
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
<file_sep>/shaka/src/mapping/v8/v8_utils.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/mapping/v8/v8_utils.h"
#include <glog/logging.h>
#include "src/core/js_manager_impl.h"
#include "src/mapping/backing_object.h"
#include "src/mapping/convert_js.h"
#include "src/mapping/js_engine.h"
#include "src/mapping/js_wrappers.h"
namespace shaka {
v8::Isolate* GetIsolate() {
return JsEngine::Instance()->isolate();
}
void PrintStackTrace(const v8::Local<v8::StackTrace>& stack) {
v8::HandleScope handle_scope(GetIsolate());
for (int i = 0; i < stack->GetFrameCount(); ++i) {
const v8::Local<v8::StackFrame> frame = stack->GetFrame(i);
const v8::String::Utf8Value name(frame->GetScriptName());
const v8::String::Utf8Value func(frame->GetFunctionName());
const int row = frame->GetLineNumber();
const int col = frame->GetColumn();
std::string func_or_main = func.length() ? *func : "<anonymous>";
LOG(ERROR) << " at " << func_or_main << " (" << *name << ":" << row << ":"
<< col << ")";
}
}
void OnUncaughtException(const v8::Local<v8::Value>& exception,
bool in_promise) {
if (exception.IsEmpty())
return;
// Print the exception and stack trace.
v8::String::Utf8Value err_str(exception);
if (in_promise)
LOG(ERROR) << "Uncaught (in promise): " << *err_str;
else
LOG(ERROR) << "Uncaught:" << *err_str;
v8::Isolate* isolate = GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::StackTrace> stack =
v8::Exception::CreateMessage(isolate, exception)->GetStackTrace();
PrintStackTrace(stack);
}
} // namespace shaka
<file_sep>/shaka/src/util/utils.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_UTIL_UTILS_H_
#define SHAKA_EMBEDDED_UTIL_UTILS_H_
#include <glog/logging.h>
#include <stdarg.h>
#include <stdint.h>
#include <algorithm>
#include <functional>
#include <mutex>
#include <string>
#include <type_traits>
#include <unordered_set>
#include <utility>
#include <vector>
#include "src/util/macros.h"
namespace shaka {
namespace util {
/**
* A helper type that accepts a function in the constructor and calls that
* method in the destructor. This can be used to execute code whether or not
* an exception has been thrown.
*/
struct Finally {
explicit Finally(std::function<void()> call);
Finally(const Finally&) = delete;
Finally(Finally&&) = delete;
~Finally();
std::function<void()> call_;
};
inline Finally::Finally(std::function<void()> call) : call_(std::move(call)) {}
inline Finally::~Finally() {
call_();
}
/**
* A helper that unlocks the given Lock and in the destructor, locks it again.
*/
template <typename _Mutex>
struct Unlocker {
explicit Unlocker(std::unique_lock<_Mutex>* lock) : lock_(lock) {
DCHECK(lock_->owns_lock());
lock_->unlock();
}
~Unlocker() {
lock_->lock();
}
NON_COPYABLE_OR_MOVABLE_TYPE(Unlocker);
std::unique_lock<_Mutex>* lock_;
};
PRINTF_FORMAT(1, 2)
std::string StringPrintf(const char* format, ...);
PRINTF_FORMAT(1, 0)
std::string StringPrintfV(const char* format, va_list va);
std::vector<std::string> StringSplit(const std::string& source, char split_on);
std::string ToAsciiLower(const std::string& source);
std::string TrimAsciiWhitespace(const std::string& source);
std::string ToHexString(const uint8_t* data, size_t data_size);
template <typename T>
bool contains(const std::vector<T>& vec, const T& elem) {
return std::find(vec.begin(), vec.end(), elem) != vec.end();
}
template <typename T>
bool contains(const std::unordered_set<T>& set, const T& elem) {
return set.count(elem) != 0;
}
template <typename List, typename Elem>
void RemoveElement(List* list, Elem&& elem) {
// std::remove modifies a list to put the desired element at the end.
// The call to erase() then removes the element.
list->erase(std::remove(list->begin(), list->end(), std::forward<Elem>(elem)),
list->end());
}
} // namespace util
} // namespace shaka
#endif // SHAKA_EMBEDDED_UTIL_UTILS_H_
<file_sep>/shaka/src/public/frame.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "shaka/frame.h"
#include <glog/logging.h>
#include <type_traits>
#include "src/media/frame_converter.h"
#include "src/util/macros.h"
namespace shaka {
class Frame::Impl {
public:
explicit Impl(AVFrame* in_frame) : frame(av_frame_alloc()) {
CHECK(frame);
CHECK_EQ(av_frame_ref(frame, in_frame), 0);
frame_data = frame->data;
frame_linesize = frame->linesize;
switch (frame->format) {
case AV_PIX_FMT_YUV420P:
format = PixelFormat::YUV420P;
break;
case AV_PIX_FMT_NV12:
format = PixelFormat::NV12;
break;
case AV_PIX_FMT_RGB24:
format = PixelFormat::RGB24;
break;
case AV_PIX_FMT_VIDEOTOOLBOX:
format = PixelFormat::VIDEO_TOOLBOX;
break;
default:
LOG(FATAL) << "Unknown pixel format: "
<< av_get_pix_fmt_name(
static_cast<AVPixelFormat>(frame->format));
}
}
~Impl() {
av_frame_free(&frame);
}
NON_COPYABLE_OR_MOVABLE_TYPE(Impl);
media::FrameConverter converter;
AVFrame* frame;
uint8_t* const* frame_data;
const int* frame_linesize;
PixelFormat format;
};
Frame::Frame() {}
Frame::Frame(AVFrame* frame) : impl_(new Impl(frame)) {}
Frame::Frame(Frame&&) = default;
Frame::~Frame() {}
Frame& Frame::operator=(Frame&&) = default;
bool Frame::valid() const {
return impl_.get();
}
PixelFormat Frame::pixel_format() const {
return impl_ ? impl_->format : PixelFormat::Unknown;
}
uint32_t Frame::width() const {
return impl_ ? impl_->frame->width : 0;
}
uint32_t Frame::height() const {
return impl_ ? impl_->frame->height : 0;
}
const uint8_t* const* Frame::data() const {
return impl_ ? impl_->frame_data : nullptr;
}
const int* Frame::linesize() const {
return impl_ ? impl_->frame_linesize : nullptr;
}
bool Frame::ConvertTo(PixelFormat format) {
if (!impl_)
return false;
if (impl_->format == format)
return true;
AVPixelFormat pix_fmt;
switch (format) {
case PixelFormat::YUV420P:
pix_fmt = AV_PIX_FMT_YUV420P;
break;
case PixelFormat::NV12:
pix_fmt = AV_PIX_FMT_NV12;
break;
case PixelFormat::RGB24:
pix_fmt = AV_PIX_FMT_RGB24;
break;
case PixelFormat::VIDEO_TOOLBOX:
LOG(ERROR) << "Cannot convert to a hardware-accelerated format.";
return false;
default:
LOG(FATAL) << "Unknown pixel format: "
<< static_cast<std::underlying_type<PixelFormat>::type>(
format);
}
if (!impl_->converter.ConvertFrame(impl_->frame, &impl_->frame_data,
&impl_->frame_linesize, pix_fmt)) {
return false;
}
impl_->format = format;
return true;
}
} // namespace shaka
<file_sep>/shaka/tools/webidl/tests/parser_test.py
#!/usr/bin/python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
import unittest
from . import test_common
from webidl import parser
class OptionsTest(unittest.TestCase):
def test_has_feature(self):
options = parser.Options()
self.assertFalse(options.has_feature('dictionary-required'))
self.assertFalse(options.has_feature(parser.Features.DICTIONARY_REQUIRED))
self.assertFalse(options.has_feature(parser.Features.DICTIONARY_DEFAULT))
options = parser.Options(parser.Features.DICTIONARY_REQUIRED)
self.assertTrue(options.has_feature('dictionary-required'))
self.assertTrue(options.has_feature(parser.Features.DICTIONARY_REQUIRED))
self.assertFalse(options.has_feature(parser.Features.DICTIONARY_DEFAULT))
def test_assumed_feature(self):
tests = [
('dictionary-required', 'dictionary', 'dictionary-default'),
]
for feature, expected, not_added in tests:
options = parser.Options(feature)
self.assertTrue(options.has_feature(feature))
self.assertTrue(options.has_feature(expected))
self.assertFalse(options.has_feature(not_added))
def test_raises_for_bad_feature(self):
with self.assertRaises(ValueError):
parser.Options('foobar')
options = parser.Options()
with self.assertRaises(ValueError):
options.has_feature('foobar')
class DictionaryTest(test_common.TestBase):
def test_empty_file(self):
results = self.parser.parse('', '')
self.assertEqual(results.types, [])
results = self.parser.parse(
'file.idl', '// Copyright 2018 Google Inc.\n \n/* Foobar */')
self.assertEqual(results.types, [])
def test_can_reuse_parser(self):
# Get a syntax error.
with self.assertRaises(parser.IdlSyntaxError):
self.parser.parse('', 'foo bar baz')
# Can reuse the parser and get the correct results.
results = self.parser.parse('', '/** Foobar */ dictionary foo {};')
self.assertEqual(len(results.types), 1)
def test_enforces_options(self):
tests = [
(['dictionary'], 'dictionary Foo { long x; };'),
(['dictionary-required'], 'dictionary Foo { required long x; };'),
(['dictionary-default'], 'dictionary Foo { long x = 123; };'),
]
parse = parser.IdlParser()
for config, code in tests:
# With all options it should work.
parse.options = parser.Options.all()
parse.parse('', code)
# It should also work with just the setting given.
parse.options = parser.Options(*config)
parse.parse('', code)
# Without setting given, should raise an error.
with self.assertRaises(parser.IdlSyntaxError):
parse.options = parser.Options()
parse.parse('', code)
def test_empty_dictionary(self):
results = self.parser.parse(
'', '/** Foobar */ dictionary foo {};')
self.assertEqual(len(results.types), 1)
self.assertEqual(results.types[0].name, 'foo')
self.assertEqual(results.types[0].doc, '/** Foobar */')
self.assertEqual(len(results.types[0].attributes), 0)
self.assertEqual(results.types[0].debug.lineno, 1)
self.assertEqual(results.types[0].debug.col, 15)
self.assertEqual(results.types[0].debug.line,
'/** Foobar */ dictionary foo {};')
self.assertEqual(results.types[0].docDebug.lineno, 1)
self.assertEqual(results.types[0].docDebug.col, 1)
self.assertEqual(results.types[0].docDebug.line,
'/** Foobar */ dictionary foo {};')
def test_members(self):
code = """
dictionary foo {
required double foo;
unsigned long bar;
DOMString baz = "foobar";
};"""
results = self.parser.parse('', code)
self.assertEqual(len(results.types), 1)
self.assertEqual(results.types[0].name, 'foo')
self.assertEqual(len(results.types[0].attributes), 3)
attrs = results.types[0].attributes
self.assertEqual(attrs[0].name, 'foo')
self.assertEqual(attrs[0].type.name, 'double')
self.assertIs(attrs[0].is_required, True)
self.assertIs(attrs[0].default, None)
self.assertEqual(attrs[1].name, 'bar')
self.assertEqual(attrs[1].type.name, 'unsigned long')
self.assertIs(attrs[1].is_required, False)
self.assertIs(attrs[1].default, None)
self.assertEqual(attrs[2].name, 'baz')
self.assertEqual(attrs[2].type.name, 'DOMString')
self.assertIs(attrs[2].is_required, False)
self.assertEqual(attrs[2].default, 'foobar')
def test_handles_multiple_dictionary_errors(self):
try:
self.parser.parse('', 'dictionary foo { x };\ndictionary bar {y};')
self.fail('Should throw syntax error')
except parser.IdlSyntaxError as e:
self.assertEqual(2, len(e.inner_errors))
self.assertEqual(1, e.inner_errors[0].lineno)
self.assertEqual(20, e.inner_errors[0].offset)
self.assertEqual(2, e.inner_errors[1].lineno)
self.assertEqual(18, e.inner_errors[1].offset)
def test_dictionary_syntax_error(self):
bad_code = [
'foo',
'dictionary',
'dictionary Foo {',
'dictionary Foo {}',
'dictionary {};',
'dictionary {;',
]
for code in bad_code:
with self.assertRaises(parser.IdlSyntaxError):
self.parser.parse('', code)
if __name__ == '__main__':
unittest.main()
<file_sep>/shaka/test/src/test/media_files_ios.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/test/media_files.h"
#include <glog/logging.h>
#include "src/util/file_system.h"
namespace shaka {
// Unlike in POSIX, we don't need to search for the media directory.
void InitMediaFiles(const char* arg0) {}
std::vector<uint8_t> GetMediaFile(const std::string& file_name) {
const std::string path =
util::FileSystem::GetPathForStaticFile(".", true, file_name);
util::FileSystem fs;
std::vector<uint8_t> ret;
CHECK(fs.ReadFile(path, &ret));
return ret;
}
} // namespace shaka
<file_sep>/shaka/src/memory/heap_tracer.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEMORY_HEAP_TRACER_H_
#define SHAKA_EMBEDDED_MEMORY_HEAP_TRACER_H_
#include <glog/logging.h>
#include <string>
#include <type_traits>
#include <unordered_set>
#include <vector>
#include "shaka/optional.h"
#include "shaka/variant.h"
#include "src/debug/mutex.h"
#include "src/util/templates.h"
namespace shaka {
class BackingObject;
namespace memory {
class HeapTracer;
/**
* Defines an object that can be traced by the HeapTracer. Any object that
* stores other Traceable objects (e.g. BackingObjects or GenericConverters)
* MUST be Traceable so we can trace the heap.
*/
class Traceable {
public:
/**
* The duration, in milliseconds, that an object is expected to remain
* alive once its C++ ref-count hits zero.
*/
static constexpr const uint64_t kShortLiveDurationMs = 5000;
virtual ~Traceable() {}
/**
* Called during a GC run. This should call HeapTracer::Trace on all
* Traceable members. Be sure to call the base method when overriding.
*/
virtual void Trace(HeapTracer* tracer) const = 0;
/**
* Gets whether this object is defined to be alive because of a JavaScript
* root reference.
*/
virtual bool IsRootedAlive() const;
/**
* Gets whether the object is considered short-lived. This means that once
* the C++ ref-count is zero, the object won't remain alive for long. It
* is important to only set this if the JavaScript object won't be used for
* long.
*
* This exists for JSC which doesn't offer a way for us to track whether a
* JavaScript object is still alive. If the JavaScript object is used after
* the backing object is destroyed, then a JavaScript exception will be
* thrown.
*/
virtual bool IsShortLived() const;
};
/**
* This is used to trace our heap to mark objects as alive and tell the
* JavaScript engine of references we hold.
*/
class HeapTracer {
public:
HeapTracer();
~HeapTracer();
/** @return A set of all the alive objects for this GC pass. */
const std::unordered_set<const Traceable*>& alive() const {
return alive_;
}
/**
* Forces the given pointer to be marked as alive for the current GC run. This
* ensures that when assigning to a Member<T> field in the middle of a GC run,
* the object will not be lost.
*/
void ForceAlive(const Traceable* ptr);
/**
* Called from the Traceable::Trace method. This marks the given member as
* alive and recursively marks child objects as alive.
*/
void Trace(const Traceable* ptr);
template <typename T>
void Trace(const std::vector<T>* array) {
for (const T& item : *array) {
Trace(&item);
}
}
template <typename T>
void Trace(const optional<T>* opt) {
if (opt->has_value())
Trace(&opt->value());
}
template <typename... Types>
void Trace(const variant<Types...>* variant) {
VariantHelper<0, Types...>::Trace(this, variant);
}
// Allow passing other types, just ignore it. This simplifies generic
// converter templates so they don't have to check if the type is special
// or not.
void Trace(const std::string*) {}
void Trace(const bool*) {}
template <typename T,
typename = util::enable_if_t<util::is_number<T>::value ||
std::is_enum<T>::value>>
void Trace(const T*) {}
/** Begins a new GC pass. */
void BeginPass();
/**
* Traces common objects, including the given ref-counted alive objects. This
* MUST be called at least once each GC pass.
*/
void TraceCommon(const std::unordered_set<const Traceable*> ref_alive);
/** Resets the stored state. */
void ResetState();
private:
template <size_t I, typename... Types>
struct VariantHelper {
static void Trace(HeapTracer* tracer, const variant<Types...>* variant) {
if (variant->index() == I)
tracer->Trace(&get<I>(*variant));
else
VariantHelper<I + 1, Types...>::Trace(tracer, variant);
}
};
template <typename... Types>
struct VariantHelper<sizeof...(Types), Types...> {
static void Trace(HeapTracer* tracer, const variant<Types...>* variant) {
CHECK_EQ(variant->index(), sizeof...(Types) - 1);
tracer->Trace(&get<sizeof...(Types) - 1>(*variant));
}
};
Mutex mutex_;
std::unordered_set<const Traceable*> alive_;
std::unordered_set<const Traceable*> pending_;
};
} // namespace memory
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEMORY_HEAP_TRACER_H_
<file_sep>/shaka/test/src/test/js_test_fixture.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "test/src/test/js_test_fixture.h"
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <string>
#include "src/core/js_manager_impl.h"
#include "src/mapping/any.h"
#include "src/mapping/backing_object.h"
#include "src/mapping/callback.h"
#include "src/mapping/promise.h"
#include "src/mapping/register_member.h"
namespace shaka {
namespace {
/**
* A helper that is used to keep a Callback object alive. This will have a
* non-zero ref count so the ObjectTracker will trace this and keep the
* Callback alive.
*/
class CallbackHolder : public BackingObject {
public:
static std::string name() {
return "CallbackHolder";
}
CallbackHolder(Callback callback) : callback(callback) {}
void Trace(memory::HeapTracer* tracer) const override {
tracer->Trace(&callback);
}
BackingObjectFactoryBase* factory() const override {
LOG(FATAL) << "Not reached";
}
Callback callback;
};
class TestImpl : public testing::Test {
public:
TestImpl(RefPtr<CallbackHolder> callback) : callback_(callback) {}
void TestBody() override {
std::promise<void> test_done;
auto task = [this, &test_done]() {
LocalVar<JsValue> value = callback_->callback.ToJsValue();
LocalVar<JsFunction> func = UnsafeJsCast<JsFunction>(value);
LocalVar<JsValue> result;
if (!InvokeMethod(func, JsEngine::Instance()->global_handle(), 0, nullptr,
&result)) {
ADD_FAILURE() << GetStack(result);
test_done.set_value();
return;
}
if (GetValueType(result) == JSValueType::Undefined) {
test_done.set_value();
return;
}
Promise promise;
if (!promise.TryConvert(result)) {
ADD_FAILURE() << "Unable to convert return value to Promise";
test_done.set_value();
return;
}
promise.Then([&](Any) { test_done.set_value(); },
[&](Any err) {
LocalVar<JsValue> val = err.ToJsValue();
ADD_FAILURE() << GetStack(val);
test_done.set_value();
});
};
JsManagerImpl::Instance()->MainThread()->AddInternalTask(
TaskPriority::Immediate, "", PlainCallbackTask(task));
test_done.get_future().get();
}
private:
std::string GetStack(Handle<JsValue> except) {
if (IsObject(except)) {
LocalVar<JsObject> obj = UnsafeJsCast<JsObject>(except);
LocalVar<JsValue> stack = GetMemberRaw(obj, "stack");
return ConvertToString(stack);
}
return ConvertToString(except);
}
RefPtr<CallbackHolder> callback_;
};
class TestFactory : public testing::internal::TestFactoryBase {
public:
TestFactory(Callback callback)
: impl_(new TestImpl(new CallbackHolder(callback))) {}
testing::Test* CreateTest() override {
CHECK(impl_);
auto* ret = impl_;
impl_ = nullptr;
return ret;
}
private:
TestImpl* impl_;
};
void DefineTest(const std::string& test_name, Callback callback) {
// Use gtest internals to dynamically register a new test case.
testing::internal::MakeAndRegisterTestInfo(
"JsTests", test_name.c_str(), nullptr, nullptr,
testing::internal::CodeLocation("", 0),
testing::internal::GetTestTypeId(), &TestImpl::SetUpTestCase,
&TestImpl::TearDownTestCase, new TestFactory(callback));
}
void Fail(const std::string& message, const std::string& file, int line) {
ADD_FAILURE_AT(file.c_str(), line) << message;
}
} // namespace
void RegisterTestFixture() {
RegisterGlobalFunction("test_", &DefineTest);
RegisterGlobalFunction("fail_", &Fail);
}
} // namespace shaka
<file_sep>/shaka/tools/clang_tidy.py
#!/usr/bin/python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Runs clang-tidy over the code to check for errors.
This requires clang-tidy to be installed on PATH.
"""
from __future__ import print_function
import argparse
import json
import os
import subprocess
import sys
import utils
TOOLS_DIR = os.path.dirname(os.path.realpath(__file__))
ROOT_DIR = os.path.join(TOOLS_DIR, '..', '..')
sys.path.append(os.path.join(ROOT_DIR, 'tools', 'clang', 'pylib', 'clang'))
import compile_db
DISABLED_CHECKS = [
# We disabled exceptions.
'cert-err58-cpp',
'hicpp-noexcept-move',
'misc-noexcept-move-constructor',
'performance-noexcept-move-constructor',
# We have some extra flags clang-tidy may not recognize.
'clang-diagnostic-unused-command-line-argument',
# We are safe with new/delete; plus we have a custom 'new' which makes
# ownership hard to determine.
'cppcoreguidelines-owning-memory',
# We are safe with uninitialized structs.
'cppcoreguidelines-pro-type-member-init',
'hicpp-member-init',
# We need to do reinterpret_cast for low-level interactions.
'cppcoreguidelines-pro-type-reinterpret-cast',
# We use util::StringPrintf, which we can't whitelist.
'cppcoreguidelines-pro-type-vararg',
'hicpp-vararg',
# We are safe with pointer arithmetic.
'cppcoreguidelines-pro-bounds-array-to-pointer-decay',
'cppcoreguidelines-pro-bounds-constant-array-index',
'cppcoreguidelines-pro-bounds-pointer-arithmetic',
'hicpp-no-array-decay',
# We can't use dynamic_cast<T> since we don't have RTTI.
'cppcoreguidelines-pro-type-static-cast-downcast',
# We allow default arguments.
'fuchsia-default-arguments',
# We allow operator overloading.
'fuchsia-overloaded-operator',
# We are safe with signed bitwise math; plus there is a lot of third-party
# macros that use it.
'hicpp-signed-bitwise',
# This suggests =default for constructors too, which seems weird.
'hicpp-use-equals-default',
'modernize-use-equals-default',
# This doesn't allow single statement bodies.
'google-readability-braces-around-statements',
'hicpp-braces-around-statements',
'readability-braces-around-statements',
# Allow missing owner of TODO.
'google-readability-todo',
# We can't use make_unique since it is C++14.
'modernize-make-unique',
# Google style is pass-by reference.
'modernize-pass-by-value',
# We use value parameters for "simple" types like RefPtr<T>.
'performance-unnecessary-value-param',
# This seems to says the static field definitions are redundant, which they
# aren't.
'readability-redundant-declaration',
# TODO: Consider enabling this. It doesn't allow pointers in conditionals.
# Even with options, it still won't allow (ptr && ptr->foo()).
'readability-implicit-bool-cast',
'readability-implicit-bool-conversion',
# TODO: Consider enabling this.
'modernize-use-default-member-init',
# TODO: This gives a number of false-positives when the upcast is useful.
'misc-misplaced-widening-cast',
# TODO: This causes several false-positives.
'clang-analyzer-core.UndefinedBinaryOperatorResult',
# TODO: This causes errors from std::shared_ptr<T>.
'clang-analyzer-core.uninitialized.UndefReturn',
# TODO: This causes errors from std::mutex.
'clang-analyzer-core.StackAddressEscape',
]
CHECKS = '*,-' + ',-'.join(DISABLED_CHECKS)
def _GenerateDatabase(build_dir):
"""Generates the compile_commands.json database file."""
# Patch GetNinjaPath since we assume it is globally installed.
compile_db.GetNinjaPath = lambda: 'ninja'
db = json.dumps(compile_db.GenerateWithNinja(build_dir))
db = (db.replace('-Wno-enum-compare-switch', '')
.replace('-Wno-unused-lambda-capture', '')
.replace('-Wno-ignored-pragma-optimize', '')
.replace('-Wno-null-pointer-arithmetic', '')
.replace('-Wno-return-std-move-in-c++11', ''))
with open(os.path.join(build_dir, 'compile_commands.json'), 'w') as f:
f.write(db)
def RunClangTidy(build_dir, clang_tidy, fix):
"""Runs clang-tidy for the given build directory."""
_GenerateDatabase(build_dir)
files = utils.GetSourceFiles(os.path.join(ROOT_DIR, 'shaka', 'src'))
files = [os.path.relpath(f, build_dir) for f in files]
cmd = [clang_tidy, '-checks=' + CHECKS, '-warnings-as-errors=*', '-p', '.']
if fix:
cmd += ['-fix', '-fix-errors']
return subprocess.call(cmd + files, cwd=build_dir)
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'--config-name', dest='config',
help='Do a special in-tree build with this configuration name.')
parser.add_argument('--fix', action='store_true',
help='Automatically apply fixes to issues.')
parser.add_argument('--clang-tidy', dest='clang_tidy',
help='The path to a clang-tidy executable to use.')
parsed_args = parser.parse_args(args)
utils.CheckConfigName(parsed_args.config)
build_dir = utils.ConfigPath(parsed_args.config)
return RunClangTidy(build_dir, parsed_args.clang_tidy or 'clang-tidy',
parsed_args.fix)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
<file_sep>/shaka/src/mapping/byte_string.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/mapping/byte_string.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "src/mapping/js_wrappers.h"
namespace shaka {
ByteString::ByteString(const char* source)
: vector(source, source + strlen(source)) {}
ByteString::ByteString(const std::string& source)
: vector(source.begin(), source.end()) {}
bool ByteString::TryConvert(Handle<JsValue> value) {
#if defined(USING_V8)
if (value.IsEmpty() || !value->IsString())
return false;
v8::String::Value value_raw(value);
const uint16_t* data = *value_raw;
const size_t length = value_raw.length();
if (length == 0 && value.As<v8::String>()->Length() != 0)
return false;
#elif defined(USING_JSC)
JSContextRef cx = GetContext();
if (!value || !JSValueIsString(cx, value))
return false;
// TODO: Avoid this copy if possible.
LocalVar<JsString> str(JSValueToStringCopy(cx, value, nullptr));
if (!str)
return false;
const uint16_t* data = JSStringGetCharactersPtr(str);
const size_t length = JSStringGetLength(str);
#endif
std::vector<uint8_t> results(length);
DCHECK_EQ(results.size(), length);
for (size_t i = 0; i < length; i++) {
if (data[i] > 0xFF) {
LOG(WARNING) << "The string to be encoded contains characters outside "
"the Latin1 range.";
return false;
}
results[i] = static_cast<uint8_t>(data[i]);
}
swap(results);
return true;
}
ReturnVal<JsValue> ByteString::ToJsValue() const {
#if defined(USING_V8)
return v8::String::NewFromOneByte(GetIsolate(), data(),
v8::NewStringType::kNormal, size())
.ToLocalChecked();
#elif defined(USING_JSC)
std::unique_ptr<uint16_t[]> temp_data(new uint16_t[size()]);
// Copy the data by writing each source byte to its own 16-bit element.
std::copy(data(), data() + size(), temp_data.get());
LocalVar<JsString> str(JSStringCreateWithCharacters(temp_data.get(), size()));
CHECK(str);
return JSValueMakeString(GetContext(), str);
#endif
}
} // namespace shaka
<file_sep>/shaka/src/js/mse/text_track.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_MSE_TEXT_TRACK_H_
#define SHAKA_EMBEDDED_JS_MSE_TEXT_TRACK_H_
#include <string>
#include <vector>
#include "include/shaka/text_track.h"
#include "src/core/member.h"
#include "src/core/ref_ptr.h"
#include "src/debug/mutex.h"
#include "src/js/events/event_target.h"
#include "src/js/vtt_cue.h"
#include "src/mapping/backing_object_factory.h"
namespace shaka {
namespace js {
namespace mse {
class TextTrack : public events::EventTarget {
DECLARE_TYPE_INFO(TextTrack);
public:
TextTrack(TextTrackKind kind, const std::string& label,
const std::string& language);
TextTrackKind kind;
std::string label;
std::string language;
std::string id;
std::vector<Member<VTTCue>> cues;
Listener on_cue_change;
void CheckForCueChange(double newTime, double oldTime);
TextTrackMode mode() const;
void SetMode(TextTrackMode mode);
// Technically this should accept a TextTrackCue, but we don't distinguish
// between the types.
void AddCue(RefPtr<VTTCue> cue);
void RemoveCue(RefPtr<VTTCue> cue);
private:
TextTrackMode mode_;
mutable Mutex mutex_;
};
class TextTrackFactory
: public BackingObjectFactory<TextTrack, events::EventTarget> {
public:
TextTrackFactory();
};
} // namespace mse
} // namespace js
} // namespace shaka
DEFINE_ENUM_MAPPING(shaka, TextTrackKind) {
AddMapping(Enum::Subtitles, "subtitles");
AddMapping(Enum::Captions, "captions");
AddMapping(Enum::Descriptions, "descriptions");
AddMapping(Enum::Chapters, "chapters");
AddMapping(Enum::Metadata, "metadata");
}
DEFINE_ENUM_MAPPING(shaka, TextTrackMode) {
AddMapping(Enum::Disabled, "disabled");
AddMapping(Enum::Hidden, "hidden");
AddMapping(Enum::Showing, "showing");
}
#endif // SHAKA_EMBEDDED_JS_MSE_TEXT_TRACK_H_
<file_sep>/shaka/src/js/mse/video_element.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_MSE_VIDEO_ELEMENT_H_
#define SHAKA_EMBEDDED_JS_MSE_VIDEO_ELEMENT_H_
#include <string>
#include <vector>
#include "shaka/optional.h"
#include "shaka/video.h"
#include "src/core/ref_ptr.h"
#include "src/debug/thread.h"
#include "src/js/dom/element.h"
#include "src/js/eme/media_keys.h"
#include "src/js/mse/media_error.h"
#include "src/js/mse/text_track.h"
#include "src/mapping/backing_object_factory.h"
#include "src/mapping/enum.h"
#include "src/mapping/exception_or.h"
#include "src/mapping/promise.h"
#include "src/media/types.h"
#include "src/util/clock.h"
namespace shaka {
namespace js {
namespace mse {
class MediaSource;
class TimeRanges;
enum class CanPlayTypeEnum {
EMPTY,
MAYBE,
PROBABLY,
};
class HTMLVideoElement : public dom::Element {
DECLARE_TYPE_INFO(HTMLVideoElement);
public:
explicit HTMLVideoElement(RefPtr<dom::Document> document);
void Trace(memory::HeapTracer* tracer) const override;
void OnReadyStateChanged(media::MediaReadyState new_ready_state);
void OnPipelineStatusChanged(media::PipelineStatus status);
void OnMediaError(media::SourceType source, media::Status status);
void CheckForCueChange(double newTime, double oldTime);
RefPtr<MediaSource> GetMediaSource() const;
// Encrypted media extensions
Promise SetMediaKeys(RefPtr<eme::MediaKeys> media_keys);
Member<eme::MediaKeys> media_keys;
Listener on_encrypted;
Listener on_waiting_for_key;
// HTMLMediaElement members.
void Load();
static CanPlayTypeEnum CanPlayType(const std::string& type);
media::MediaReadyState ready_state;
bool autoplay;
bool loop;
std::vector<Member<TextTrack>> text_tracks;
RefPtr<MediaError> error;
media::VideoPlaybackQuality GetVideoPlaybackQuality() const;
RefPtr<TimeRanges> Buffered() const;
std::string Source() const;
ExceptionOr<void> SetSource(const std::string& src);
double CurrentTime() const;
void SetCurrentTime(double time);
double Duration() const;
double PlaybackRate() const;
void SetPlaybackRate(double rate);
bool Muted() const;
void SetMuted(bool muted);
double Volume() const;
void SetVolume(double volume);
bool Paused() const;
bool Seeking() const;
bool Ended() const;
void Play();
void Pause();
RefPtr<TextTrack> AddTextTrack(TextTrackKind kind,
optional<std::string> label,
optional<std::string> language);
private:
void ThreadMain();
Member<MediaSource> media_source_;
media::PipelineStatus pipeline_status_;
double volume_;
bool will_play_;
bool is_muted_;
const util::Clock* const clock_;
std::atomic<bool> shutdown_;
Thread thread_;
};
class HTMLVideoElementFactory
: public BackingObjectFactory<HTMLVideoElement, dom::Element> {
public:
HTMLVideoElementFactory();
};
} // namespace mse
} // namespace js
} // namespace shaka
CONVERT_ENUM_AS_NUMBER(shaka::media, MediaReadyState);
DEFINE_ENUM_MAPPING(shaka::js::mse, CanPlayTypeEnum) {
AddMapping(Enum::EMPTY, "");
AddMapping(Enum::MAYBE, "maybe");
AddMapping(Enum::PROBABLY, "probably");
}
#endif // SHAKA_EMBEDDED_JS_MSE_VIDEO_ELEMENT_H_
<file_sep>/shaka/src/public/shaka_utils.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "shaka/utils.h"
namespace shaka {
ShakaRect FitVideoToWindow(int video_width, int video_height, int window_width,
int window_height, int window_x, int window_y) {
const double width_scale = static_cast<double>(window_width) / video_width;
const double height_scale = static_cast<double>(window_height) / video_height;
int scaled_width, scaled_height;
if (width_scale < height_scale) {
scaled_width = window_width;
scaled_height = static_cast<int>(video_height * width_scale);
} else {
scaled_width = static_cast<int>(video_width * height_scale);
scaled_height = window_height;
}
return {.x = (window_width - scaled_width) / 2 + window_x,
.w = scaled_width,
.y = (window_height - scaled_height) / 2 + window_y,
.h = scaled_height};
}
} // namespace shaka
<file_sep>/shaka/test/tests/test_type.js
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
testGroup('TestType', function() {
// These tests are used to test the behavior of the type converters and the
// registering framework. See TestType.
// The expected values for the tests. These must match the constants in
// test_type.h. These must exist in both C++ and JavaScript because that is
// what we are testing; namely that the value of the variables are converted
// correctly.
const expectedInt = 123;
const expectedNumberEnum = 2;
const expectedStringEnum = 'other';
// Used to verify that Unicode characters and embedded nulls are converted
// correctly.
const expectedString = 'ab\u2345_\0_\ud801\udc37!';
const expectedStruct = {
'string': expectedString,
'boolean': true,
any: undefined
};
const expectedArray = ['abc', '123', expectedString];
const TestStringEnum = {
EMPTY: '',
AUTO: 'auto',
OTHER: 'other'
};
if (!window.TestType) {
console.log('Skipping TestType tests in release mode');
return;
}
testGroup('BoxedPrimitives', function() {
test('AcceptsNumbers', function() {
let test = new TestType();
test.acceptNumber(1234);
test.acceptNumber(new Number(1234));
expectToThrow(() => { test.acceptNumber(null); });
expectToThrow(() => { test.acceptNumber(undefined); });
expectToThrow(() => { test.acceptNumber('abc'); });
expectToThrow(() => { test.acceptNumber({}); });
expectToThrow(() => { test.acceptNumber(); });
});
test('AcceptsBooleans', function() {
let test = new TestType();
test.acceptBoolean(false);
test.acceptBoolean(new Boolean(true));
expectToThrow(() => { test.acceptBoolean(null); });
expectToThrow(() => { test.acceptBoolean(undefined); });
expectToThrow(() => { test.acceptBoolean('abc'); });
expectToThrow(() => { test.acceptBoolean({}); });
expectToThrow(() => { test.acceptBoolean(); });
});
});
testGroup('strings', function() {
test('ThrowsForInvalidTypes', function() {
let test = new TestType();
test.acceptString('abc');
test.acceptString(new String('abc'));
test.acceptString(expectedString);
expectToThrow(() => { test.acceptString(null); });
expectToThrow(() => { test.acceptString(undefined); });
expectToThrow(() => { test.acceptString(123); });
expectToThrow(() => { test.acceptString({}); });
expectToThrow(() => { test.acceptString(); });
});
test('Arguments', function() {
let test = new TestType();
expectFalse(test.isExpectedString('abc'));
expectTrue(test.isExpectedString(expectedString));
expectFalse(test.isExpectedString(new String('abc')));
expectTrue(test.isExpectedString(new String(expectedString)));
});
test('ReturnValue', function() {
let test = new TestType();
expectEq(test.getString(), expectedString);
});
});
testGroup('optional', function() {
test('ThrowsForInvalidTypes', function() {
let test = new TestType();
test.acceptOptionalString('abc');
test.acceptOptionalString('');
test.acceptOptionalString(null);
test.acceptOptionalString(undefined);
test.acceptOptionalString();
expectToThrow(() => { test.acceptOptionalString(123); });
expectToThrow(() => { test.acceptOptionalString({}); });
test.acceptOptionalStruct({});
test.acceptOptionalStruct(null);
test.acceptOptionalStruct(undefined);
test.acceptOptionalStruct();
expectToThrow(() => { test.acceptOptionalStruct(123); });
expectToThrow(() => { test.acceptOptionalStruct('abc'); });
});
test('Arguments', function() {
let test = new TestType();
expectTrue(test.isOptionalPresent('abc'));
expectTrue(test.isOptionalPresent(''));
expectFalse(test.isOptionalPresent(null));
expectFalse(test.isOptionalPresent(undefined));
expectFalse(test.isOptionalPresent());
});
test('ReturnValue', function() {
let test = new TestType();
expectEq(test.getOptionalString(false), null);
expectEq(test.getOptionalString(true), expectedString);
});
test('TracesChildren', function() {
let test = new TestType();
test.optionalObject = {abc: 1};
gc();
expectEq(test.optionalObject.abc, 1);
});
});
testGroup('or', function() {
test('ThrowsForInvalidTypes', function() {
let test = new TestType();
test.acceptIntOrStruct(123);
test.acceptIntOrStruct({});
expectToThrow(() => { test.acceptIntOrStruct(false); });
expectToThrow(() => { test.acceptIntOrStruct('abc'); });
expectToThrow(() => { test.acceptIntOrStruct(null); });
expectToThrow(() => { test.acceptIntOrStruct(undefined); });
expectToThrow(() => { test.acceptIntOrStruct(); });
test.acceptStringEnumOrAnyNumber(TestStringEnum.AUTO);
test.acceptStringEnumOrAnyNumber(123);
expectToThrow(() => { test.acceptStringEnumOrAnyNumber('foobar'); });
expectToThrow(() => { test.acceptStringEnumOrAnyNumber({}); });
expectToThrow(() => { test.acceptStringEnumOrAnyNumber(); });
});
test('Arguments', function() {
let test = new TestType();
expectTrue(test.isExpectedIntWithOr(expectedInt));
expectFalse(test.isExpectedIntWithOr(0));
expectFalse(test.isExpectedIntWithOr({}));
expectTrue(test.isExpectedStructWithOr(expectedStruct));
expectFalse(test.isExpectedStructWithOr(0));
expectFalse(test.isExpectedStructWithOr({}));
});
test('ReturnValue', function() {
let test = new TestType();
expectEq(test.getIntOrString(true), expectedInt);
expectEq(test.getIntOrString(false), expectedString);
});
test('TracesChildren', function() {
let test = new TestType();
test.intOrObject = {abc: 1};
gc();
expectEq(test.intOrObject.abc, 1);
});
});
testGroup('structs', function() {
/**
* The type of the C++ struct:
*
* @type {{
* string: string,
* boolean: boolean,
* any: *
* }}
*/
test('ThrowsForInvalidTypes', function() {
let test = new TestType();
test.acceptStruct({});
test.acceptStruct({abc: 123});
test.acceptStruct({string: 'abc'});
test.acceptStruct({string: 123});
expectToThrow(() => { test.acceptStruct(null); });
expectToThrow(() => { test.acceptStruct('abc'); });
expectToThrow(() => { test.acceptStruct(); });
});
test('Arguments', function() {
let test = new TestType();
expectFalse(test.isExpectedConvertedStruct({}));
expectTrue(test.isExpectedConvertedStruct(expectedStruct));
expectTrue(test.isConvertedStructEmpty({}));
expectFalse(test.isConvertedStructEmpty({string: 'abc'}));
// Key 'abc' is not in the C++ type, so it is ignored.
expectTrue(test.isConvertedStructEmpty({abc: '123'}));
// 999 is not the correct type, so it is ignored.
expectTrue(test.isConvertedStructEmpty({string: 999}));
});
test('ReturnValue', function() {
let test = new TestType();
var o = test.getStruct();
expectEq(o, expectedStruct);
expectNotSame(o, expectedStruct);
});
test('TracesChildren', function() {
// Caution, setting a member on a struct directly won't work.
// test.struct.any = {abc: 1};
let test = new TestType();
test.struct = {any: {abc: 1}};
gc();
expectEq(test.struct.any.abc, 1);
});
});
testGroup('enums', function() {
test('ThrowsForInvalidTypes', function() {
let test = new TestType();
test.acceptNumberEnum(expectedNumberEnum);
test.acceptNumberEnum(999);
expectToThrow(() => { test.acceptNumberEnum(null); });
expectToThrow(() => { test.acceptNumberEnum({}); });
expectToThrow(() => { test.acceptNumberEnum(''); });
expectToThrow(() => { test.acceptNumberEnum(); });
test.acceptStringEnum(TestStringEnum.EMPTY);
test.acceptStringEnum(expectedStringEnum);
expectToThrow(() => { test.acceptStringEnum(12); });
// Not a valid enum.
expectToThrow(() => { test.acceptStringEnum('foobar'); });
expectToThrow(() => { test.acceptStringEnum({}); });
expectToThrow(() => { test.acceptStringEnum(); });
});
test('Arguments', function() {
let test = new TestType();
expectTrue(test.isExpectedNumberEnum(expectedNumberEnum));
expectFalse(test.isExpectedNumberEnum(123));
expectTrue(test.isExpectedStringEnum(expectedStringEnum));
expectFalse(test.isExpectedStringEnum(''));
});
test('ReturnValue', function() {
let test = new TestType();
expectEq(test.getNumberEnum(), expectedNumberEnum);
expectEq(test.getStringEnum(), expectedStringEnum);
});
});
testGroup('arrays', function() {
test('ThrowsForInvalidTypes', function() {
let test = new TestType();
test.acceptArrayOfStrings([]);
test.acceptArrayOfStrings(['x']);
test.acceptArrayOfStrings(['a', 'b', 'c']);
expectToThrow(() => { test.acceptArrayOfStrings(null); });
expectToThrow(() => { test.acceptArrayOfStrings('abc'); });
expectToThrow(() => { test.acceptArrayOfStrings([2]); });
expectToThrow(() => {
test.acceptArrayOfStrings(['a', 'b', undefined, 'd']);
});
expectToThrow(() => { test.acceptArrayOfStrings(); });
expectToThrow(() => { test.acceptArrayOfStrings(new Array(2)); });
});
test('Arguments', function() {
let test = new TestType();
expectTrue(test.isExpectedArrayOfStrings(expectedArray));
expectFalse(test.isExpectedArrayOfStrings([]));
expectFalse(test.isExpectedArrayOfStrings(['a', 'b', 'c']));
});
test('ReturnValue', function() {
let test = new TestType();
let result = test.getArrayOfStrings();
expectEq(result, expectedArray);
expectNotSame(result, expectedArray);
});
test('TracesChildren', function() {
let test = new TestType();
test.array = [123, {abc: 1}];
gc();
expectEq(test.array, [123, {abc: 1}]);
});
});
testGroup('maps', function() {
test('ReturnValue', function() {
let test = new TestType();
let result = test.getMapOfStrings();
expectTrue(result);
expectInstanceOf(result, Map);
expectEq(result.get('a'), '1');
expectEq(result.get('b'), '2');
let spy = jasmine.createSpy('callback');
result.forEach(spy);
expectToHaveBeenCalledTimes(spy, 2);
expectToHaveBeenCalledWith(spy, '1', 'a', result);
expectToHaveBeenCalledWith(spy, '2', 'b', result);
});
});
testGroup('callbacks', function() {
test('ThrowsForInvalidTypes', function() {
let test = new TestType();
test.acceptCallback(function() {});
test.acceptCallback(function(a) {});
test.acceptCallback(fail);
expectToThrow(() => { test.acceptCallback(null); });
expectToThrow(() => { test.acceptCallback(12); });
expectToThrow(() => { test.acceptCallback('abc'); });
expectToThrow(() => { test.acceptCallback(); });
});
test('CanInvokeArgument', function() {
let test = new TestType();
let spy = jasmine.createSpy('callback');
spy.and.callFake(function(a) { expectEq(a, expectedString); });
test.invokeCallbackWithString(spy);
expectToHaveBeenCalled(spy);
});
test('TracesChildren', function() {
return new Promise(function(resolve) {
let test = new TestType();
test.callback = resolve;
gc();
expectEq(typeof test.callback, 'function');
test.callback();
});
});
});
testGroup('anything', function() {
test('ThrowsForInvalidTypes', function() {
let test = new TestType();
test.acceptAnything({});
test.acceptAnything([]);
test.acceptAnything('str');
test.acceptAnything(123);
test.acceptAnything(true);
test.acceptAnything(null);
test.acceptAnything(undefined);
// Note Anything is not optional.
expectToThrow(() => { test.acceptAnything(); });
});
test('Arguments', function() {
let test = new TestType();
expectTrue(test.isExpectedStringWithAny(expectedString));
expectFalse(test.isExpectedStringWithAny(''));
expectFalse(test.isExpectedStringWithAny(1));
});
test('DeterminesTruthiness', function() {
let test = new TestType();
expectTrue(test.isTruthy(true));
expectTrue(test.isTruthy(123));
expectTrue(test.isTruthy(-10));
expectTrue(test.isTruthy('foo'));
expectTrue(test.isTruthy({}));
expectTrue(test.isTruthy({a: 1}));
expectTrue(test.isTruthy([]));
expectTrue(test.isTruthy([1, 2]));
expectFalse(test.isTruthy(false));
expectFalse(test.isTruthy(0));
expectFalse(test.isTruthy(NaN));
expectFalse(test.isTruthy(''));
expectFalse(test.isTruthy(null));
expectFalse(test.isTruthy(undefined));
});
test('TracesChildren', function() {
let test = new TestType();
test.any = {abc: 1};
gc();
expectEq(test.any.abc, 1);
// There was a bug where tracing a number caused V8 to crash.
test.any = 123;
gc();
expectEq(test.any, 123);
});
});
testGroup('ByteBuffer', function() {
test('ThrowsForInvalidTypes', function() {
let test = new TestType();
test.acceptByteBuffer(new ArrayBuffer(10));
test.acceptByteBuffer(new ArrayBuffer(0));
test.acceptByteBuffer(new Uint8Array([]));
expectToThrow(() => { test.acceptByteBuffer(12); });
expectToThrow(() => { test.acceptByteBuffer({}); });
expectToThrow(() => { test.acceptByteBuffer([]); });
expectToThrow(() => { test.acceptByteBuffer(null); });
expectToThrow(() => { test.acceptByteBuffer(); });
});
test('WorksWithFields', function() {
let test = new TestType();
var buf = new ArrayBuffer(10);
test.buffer = buf;
expectSame(test.buffer, buf);
});
test('KeepsDataAccrossGcRuns', function() {
let test = new TestType();
let arr = [1, 2, 3, 4, 5];
test.storeByteBuffer(new Uint8Array(arr).buffer);
gc();
let buf = new Uint8Array(test.getByteBuffer());
expectEq(buf.length, arr.length);
for (let i = 0; i < buf.length; i++) {
expectEq(buf[i], arr[i]);
}
});
test('represents a common buffer', function() {
let test = new TestType();
let arr = [1, 2, 3, 4, 5];
let buffer = new Uint8Array(arr);
test.storeByteBuffer(buffer.buffer);
// Mutate the common buffer.
arr = [5, 4, 3, 2, 1];
for (let i = 0; i < arr.length; i++) {
buffer[i] = arr[i];
}
// The return value should contain the same buffer.
let after = new Uint8Array(test.getByteBuffer());
expectEq(after.length, buffer.length);
for (let i = 0; i < buffer.length; i++) {
expectEq(after[i], buffer[i]);
}
});
});
testGroup('Promises', function() {
test('ReturnValue', async function() {
let test = new TestType();
let p = test.promiseResolveWith(1);
expectTrue(p);
expectInstanceOf(p, Promise);
expectInstanceOf(p.then, Function);
await p.then(function(value) {
expectEq(value, 1);
});
});
test('ReturnsRejectedPromiseForTypeErrors', async function() {
try {
let test = new TestType();
await test.promiseAcceptString(123);
fail('Should reject Promise');
} catch(error) {
expectInstanceOf(error, TypeError);
expectEq(error.name, 'TypeError');
expectTrue(error.message);
}
});
test('WillResolveAsynchronously', async function() {
let test = new TestType();
var checked = false;
setTimeout(function() {
checked = true;
}, 15);
await test.promiseResolveAfter(250)
expectTrue(checked);
});
});
testGroup('toPrettyString', function() {
test('ConvertsNulls', function() {
let test = new TestType();
expectEq(test.toPrettyString(undefined), 'undefined');
expectEq(test.toPrettyString(null), 'null');
});
test('ConvertsNumbers', function() {
let test = new TestType();
expectEq(test.toPrettyString(0), '0');
expectEq(test.toPrettyString(1.2), '1.2');
expectEq(test.toPrettyString(2.0), '2');
});
test('ConvertsBooleans', function() {
let test = new TestType();
expectEq(test.toPrettyString(true), 'true');
expectEq(test.toPrettyString(false), 'false');
});
test('ConvertsStrings', function() {
let test = new TestType();
expectEq(test.toPrettyString(''), '""');
expectEq(test.toPrettyString('abc'), '"abc"');
expectEq(test.toPrettyString('a\nb\nc'), '"a\\nb\\nc"');
expectEq(test.toPrettyString('a\tb\tc'), '"a\\tb\\tc"');
});
test('ConvertsPrimitiveObjects', function() {
let test = new TestType();
expectEq(test.toPrettyString(new String('abc')), 'String("abc")');
expectEq(test.toPrettyString(new Boolean(false)), 'Boolean(false)');
expectEq(test.toPrettyString(new Number(123)), 'Number(123)');
});
test('ConvertsBuiltInObjects', function() {
let test = new TestType();
let promise = new Promise(()=>{});
expectEq(test.toPrettyString(promise), '[object Promise]');
let buffer = new ArrayBuffer();
expectEq(test.toPrettyString(buffer), '[object ArrayBuffer]');
let xhr = new XMLHttpRequest();
expectEq(test.toPrettyString(xhr), '[object XMLHttpRequest]');
});
test('ConvertsArrays', function() {
let test = new TestType();
expectEq(test.toPrettyString([]), '[]');
expectEq(test.toPrettyString([0, 1, 2]), '[0, 1, 2]');
expectEq(test.toPrettyString([[], [], []]), '[[...], [...], [...]]');
// Make sure that long arrays get "chopped-off".
let longArray = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25
];
let longArrayString =
'[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, '+
'11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ' +
'...]';
expectEq(test.toPrettyString(longArray), longArrayString);
});
test('ConvertsObjects', function() {
let test = new TestType();
expectEq(test.toPrettyString({}), '{}');
expectEq(test.toPrettyString({a:0}), '{a:0}');
expectEq(test.toPrettyString({a:0, b:1}), '{a:0, b:1}');
expectEq(test.toPrettyString({b:1, a:0}), '{a:0, b:1}');
expectEq(test.toPrettyString({a: 'a'}), '{a:"a"}');
expectEq(test.toPrettyString({a: []}), '{a:[...]}');
expectEq(test.toPrettyString({a: {}}), '{a:{...}}');
// Make sure that long objects get "chopped-off".
let longObject = {
a:1, b:2, c:3, d:4, e:5, f:6, g:7, h:8, i:9, j:10,
k:11, l:12, m:13, n:14, o:15, p:16, q:17, r:18, s:19, t:20,
u:21, v:22, w:23, x:24, y:25
};
let longObjectString =
'{a:1, b:2, c:3, d:4, e:5, f:6, g:7, h:8, i:9, j:10, ' +
'k:11, l:12, m:13, n:14, o:15, p:16, q:17, r:18, s:19, t:20, ' +
'...}';
expectEq(test.toPrettyString(longObject), longObjectString);
function Ctor() {}
let inst = new Ctor();
inst.foo = 1;
expectEq(test.toPrettyString(inst), '{foo:1}');
});
test('StillConvertsWithCustomToString', function() {
let test = new TestType();
let obj = {};
obj.toString = function() { return '[object Promise]'; }
expectEq(test.toPrettyString(obj), '{toString:function() {...}}');
});
});
test('ThrowsExceptions', function() {
try {
let test = new TestType();
test.throwException('Foo');
fail('Should throw exception');
} catch (e) {
expectInstanceOf(e, Error);
expectEq(e.message, 'Foo');
}
});
});
<file_sep>/shaka/src/media/video_controller.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_VIDEO_CONTROLLER_H_
#define SHAKA_EMBEDDED_MEDIA_VIDEO_CONTROLLER_H_
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>
#include "shaka/eme/configuration.h"
#include "shaka/eme/implementation.h"
#include "shaka/frame.h"
#include "src/debug/mutex.h"
#include "src/mapping/byte_buffer.h"
#include "src/mapping/struct.h"
#include "src/media/decoder_thread.h"
#include "src/media/demuxer_thread.h"
#include "src/media/media_processor.h"
#include "src/media/media_utils.h"
#include "src/media/pipeline_manager.h"
#include "src/media/pipeline_monitor.h"
#include "src/media/renderer.h"
#include "src/media/stream.h"
#include "src/media/types.h"
#include "src/util/macros.h"
namespace shaka {
namespace media {
/**
* This is the backing logic for a video element. This handles buffering,
* seeking, playback, etc.. This gets "attached" to a video element when the
* src attribute is set from JavaScript. This can be detached by changing the
* src or by calling load().
*
* The video element represents a renderable surface (e.g. a Gtk window),
* while this object holds the logic for MSE and handling of data.
*
* Unlike a full implementation of video, this object will handle logic for
* seeking and playback rates. A more general video element might only use
* MSE as a source of data and have the logic of playback position handled by
* a more general video handler. However, we bundle all the logic for playback
* in this type.
*
* This object is owned by the MediaSource. When the MediaSource gets attached
* to a video element, the video will save a reference to the MediSource and
* will also use this type. This ensures that the MediaSource will remain
* alive so long as there is either a reference to it or the video is playing.
*/
class VideoController {
public:
VideoController(std::function<void(SourceType, Status)> on_error,
std::function<void()> on_waiting_for_key,
std::function<void(eme::MediaKeyInitDataType, ByteBuffer)>
on_encrypted_init_data,
std::function<void(MediaReadyState)> on_ready_state_changed,
std::function<void(PipelineStatus)> on_pipeline_changed);
~VideoController();
//@{
/** @return The pipeline manager for this video. */
const PipelineManager* GetPipelineManager() const {
return &pipeline_;
}
PipelineManager* GetPipelineManager() {
return &pipeline_;
}
//@}
/** Sets the volume of the audio. */
void SetVolume(double volume);
/** Draws the current video frame onto a texture and returns it. */
Frame DrawFrame(double* delay);
/** Sets the CDM implementation used to decrypt media. */
void SetCdm(eme::Implementation* cdm);
Status AddSource(const std::string& mime_type, SourceType* source_type);
/**
* Appends the given data to the media source. This assumes the data will
* exist until on_complete is called.
* TODO: Investigate using ref-counting to keep this alive.
* @return False if the type wasn't found (or was detached), otherwise true.
*/
bool AppendData(SourceType type, double timestamp_offset, double window_start,
double window_end, const uint8_t* data, size_t data_size,
std::function<void(Status)> on_complete);
bool Remove(SourceType type, double start, double end);
void EndOfStream();
/** @return The current video quality info. */
const VideoPlaybackQuality* GetVideoPlaybackQuality() const {
return &quality_info_;
}
/**
* Gets the buffered ranges for the given type. If the type is Unknown, this
* returns the intersection of the ranges.
*/
BufferedRanges GetBufferedRanges(SourceType type) const;
/**
* Resets all data and clears all internal state. This will reset the object
* to when it was constructed. This is NOT related to abort(), this is
* called when the MediaSource gets closed (detached).
*/
void Reset();
/**
* INTERNAL DEBUG USE ONLY.
*
* Dumps debug state to the console. This includes current time, playback
* rate, and buffered ranges.
*/
void DebugDumpStats() const;
private:
struct Source {
Source(
SourceType source_type,
PipelineManager* pipeline,
const std::string& container,
const std::string& codecs, std::function<void()> on_waiting_for_key,
std::function<void(eme::MediaKeyInitDataType, const uint8_t*, size_t)>
on_encrypted_init_data,
std::function<double()> get_time,
std::function<double()> get_playback_rate,
std::function<void(Status)> on_error,
std::function<void()> on_load_meta);
~Source();
NON_COPYABLE_OR_MOVABLE_TYPE(Source);
void OnSeekDone();
MediaProcessor processor;
Stream stream;
DecoderThread decoder;
DemuxerThread demuxer;
std::unique_ptr<Renderer> renderer;
bool ready;
};
Source* GetSource(SourceType type) const {
return sources_.count(type) != 0 ? sources_.at(type).get() : nullptr;
}
void OnSeek();
void OnLoadMeta(SourceType type);
void OnError(SourceType type, Status error);
void OnEncryptedInitData(eme::MediaKeyInitDataType init_data_type,
const uint8_t* data, size_t data_size);
BufferedRanges GetDecodedRanges() const;
double GetPlaybackRate() const;
mutable SharedMutex mutex_;
std::unordered_map<SourceType, std::unique_ptr<Source>> sources_;
std::function<void(SourceType, Status)> on_error_;
std::function<void()> on_waiting_for_key_;
std::function<void(eme::MediaKeyInitDataType, ByteBuffer)>
on_encrypted_init_data_;
PipelineManager pipeline_;
PipelineMonitor monitor_;
VideoPlaybackQuality quality_info_;
eme::Implementation* cdm_;
double volume_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_VIDEO_CONTROLLER_H_
<file_sep>/shaka/include/shaka/eme/implementation_factory.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_EME_IMPLEMENTATION_FACTORY_H_
#define SHAKA_EMBEDDED_EME_IMPLEMENTATION_FACTORY_H_
#include <string>
#include <vector>
#include "../macros.h"
#include "configuration.h"
namespace shaka {
namespace eme {
class Implementation;
class ImplementationHelper;
/**
* A factory used to create EME implementation instances and to query what this
* implementation supports. This is implemented by an app and registered with
* the ImplementationRegistry.
*
* @ingroup eme
*/
class SHAKA_EXPORT ImplementationFactory {
public:
// Since this is intended to be subclassed by the app, this type cannot be
// changed without breaking ABI compatibility. This includes adding
// new virtual methods.
virtual ~ImplementationFactory();
/** @return Whether this implementation supports the given session type. */
virtual bool SupportsSessionType(MediaKeySessionType type) const = 0;
/** @return Whether this implementation supports the given init data type. */
virtual bool SupportsInitDataType(MediaKeyInitDataType type) const = 0;
/** @return Whether this implementation supports the given robustness. */
virtual bool SupportsAudioRobustness(const std::string& robustness) const = 0;
/** @return Whether this implementation supports the given robustness. */
virtual bool SupportsVideoRobustness(const std::string& robustness) const = 0;
/** @return The distinctive identifier requirements of the implementation. */
virtual MediaKeysRequirement DistinctiveIdentifier() const = 0;
/** @return The persistent state requirements of the implementation. */
virtual MediaKeysRequirement PersistentState() const = 0;
/**
* Creates a new instance of the implementation. The arguments have already
* been filtered according to the support methods. This should verify that
* the arguments are compatible with the implementation. If the
* implementation doesn't support the given arguments, it MUST return nullptr.
*
* @param helper The helper instance used to callback to JavaScript.
* @param distinctive_identifier The distinctive identifier requirement.
* @param persistent_state The persistent state requirement.
* @param audio_robustness The audio robustness requirements.
* @param video_robustness The video robustness requirements.
* @return A new implementation instance, or nullptr if not supported.
*/
virtual Implementation* CreateImplementation(
ImplementationHelper* helper,
MediaKeysRequirement distinctive_identifier,
MediaKeysRequirement persistent_state,
const std::vector<std::string>& audio_robustness,
const std::vector<std::string>& video_robustness) = 0;
};
} // namespace eme
} // namespace shaka
#endif // SHAKA_EMBEDDED_EME_IMPLEMENTATION_FACTORY_H_
<file_sep>/shaka/src/js/events/event_names.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_EVENTS_EVENT_NAMES_H_
#define SHAKA_EMBEDDED_JS_EVENTS_EVENT_NAMES_H_
#include "src/util/macros.h"
namespace shaka {
namespace js {
#define DEFINE_EVENTS_(DEFINE_EVENT) \
DEFINE_EVENT(Abort, "abort") \
DEFINE_EVENT(Error, "error") \
DEFINE_EVENT(ReadyStateChange, "readystatechange") \
/** Media events */ \
DEFINE_EVENT(CanPlay, "canplay") \
DEFINE_EVENT(LoadedMetaData, "loadedmetadata") \
DEFINE_EVENT(LoadedData, "loadeddata") \
DEFINE_EVENT(Waiting, "waiting") \
DEFINE_EVENT(Emptied, "emptied") \
DEFINE_EVENT(Play, "play") \
DEFINE_EVENT(Playing, "playing") \
DEFINE_EVENT(Pause, "pause") \
DEFINE_EVENT(Seeked, "seeked") \
DEFINE_EVENT(Seeking, "seeking") \
DEFINE_EVENT(Ended, "ended") \
DEFINE_EVENT(CueChange, "cuechange") \
/* EME events. */ \
DEFINE_EVENT(KeyStatusesChange, "keystatuseschange") \
DEFINE_EVENT(Message, "message") \
DEFINE_EVENT(WaitingForKey, "waitingforkey") \
DEFINE_EVENT(Encrypted, "encrypted") \
/* Progress tracking */ \
DEFINE_EVENT(Load, "load") \
DEFINE_EVENT(LoadStart, "loadstart") \
DEFINE_EVENT(LoadEnd, "loadend") \
DEFINE_EVENT(Progress, "progress") \
DEFINE_EVENT(Update, "update") \
DEFINE_EVENT(UpdateStart, "updatestart") \
DEFINE_EVENT(UpdateEnd, "updateend") \
/* XMLHttpRequest */ \
DEFINE_EVENT(Timeout, "timeout") \
/* MSE */ \
DEFINE_EVENT(SourceOpen, "sourceopen") \
DEFINE_EVENT(SourceEnded, "sourceended") \
DEFINE_EVENT(SourceClose, "sourceclose") \
DEFINE_EVENT(AddSourceBuffer, "addsourcebuffer") \
DEFINE_EVENT(RemoveSourceBuffer, "removesourcebuffer")
DEFINE_ENUM_AND_TO_STRING_2(EventType, DEFINE_EVENTS_);
#undef DEFINE_EVENTS_
} // namespace js
} // namespace shaka
#endif // SHAKA_EMBEDDED_JS_EVENTS_EVENT_NAMES_H_
<file_sep>/shaka/src/js/test_type.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_TEST_TYPE_H_
#define SHAKA_EMBEDDED_JS_TEST_TYPE_H_
#include <string>
#include <unordered_map>
#include <vector>
#include "shaka/optional.h"
#include "shaka/variant.h"
#include "src/core/member.h"
#include "src/mapping/any.h"
#include "src/mapping/backing_object.h"
#include "src/mapping/backing_object_factory.h"
#include "src/mapping/byte_buffer.h"
#include "src/mapping/callback.h"
#include "src/mapping/enum.h"
#include "src/mapping/promise.h"
#include "src/mapping/struct.h"
namespace shaka {
namespace js {
// A Struct type that is used by TestType.
struct TestTypeOptions : public Struct {
static std::string name() {
return "TestTypeOptions";
}
ADD_DICT_FIELD(std::string, string);
ADD_DICT_FIELD(bool, boolean);
ADD_DICT_FIELD(Any, any);
};
enum class TestNumberEnum {
FIRST = 1,
SECOND,
};
enum class TestStringEnum {
EMPTY,
AUTO,
OTHER,
};
constexpr const int EXPECTED_INT = 123;
constexpr const TestNumberEnum EXPECTED_NUMBER_ENUM = TestNumberEnum::SECOND;
constexpr const TestStringEnum EXPECTED_STRING_ENUM = TestStringEnum::OTHER;
// Used to verify that Unicode characters and embedded nulls are converted
// correctly.
constexpr const char EXPECTED_STRING[] = "ab\xe2\x8d\x85_\0_\xf0\x90\x90\xb7!";
/**
* Defines a backing type that is used to test the registering framework.
* Methods are called in JavaScript tests to test the conversion functions.
*/
class TestType : public BackingObject {
DECLARE_TYPE_INFO(TestType);
public:
TestType();
static TestType* Create() {
return new TestType();
}
void Trace(memory::HeapTracer* tracer) const override;
void AcceptNumber(double) const {}
void AcceptBoolean(bool) const {}
void AcceptString(const std::string&) const {}
void AcceptOptionalString(optional<std::string>) const {}
void AcceptOptionalStruct(optional<TestTypeOptions>) const {}
void AcceptIntOrStruct(variant<int, TestTypeOptions>) const {}
void AcceptStringEnumOrAnyNumber(variant<TestStringEnum, double>) const {}
void AcceptStruct(TestTypeOptions) const {}
void AcceptNumberEnum(TestNumberEnum) const {}
void AcceptStringEnum(TestStringEnum) const {}
void AcceptArrayOfStrings(std::vector<std::string>) const {}
void AcceptCallback(Callback) const {}
void AcceptAnything(Any) const {}
void AcceptByteBuffer(ByteBuffer) const {}
// These return true if the given value is an expected value (the constants
// above).
bool IsExpectedString(const std::string& arg) const;
bool IsOptionalPresent(optional<std::string> arg) const;
bool IsExpectedIntWithOr(variant<int, Any> arg) const;
bool IsExpectedStructWithOr(variant<int, TestTypeOptions> arg) const;
bool IsExpectedConvertedStruct(TestTypeOptions opts) const;
bool IsConvertedStructEmpty(TestTypeOptions opts) const;
bool IsExpectedNumberEnum(TestNumberEnum e) const;
bool IsExpectedStringEnum(TestStringEnum e) const;
bool IsExpectedArrayOfStrings(const std::vector<std::string>& data) const;
bool IsExpectedStringWithAny(Any anything) const;
bool IsTruthy(Any anything) const;
void InvokeCallbackWithString(Callback callback) const;
void StoreByteBuffer(ByteBuffer buffer);
ExceptionOr<void> ThrowException(const std::string& message) const;
Promise PromiseAcceptString(const std::string& value) const;
Promise PromiseResolveWith(Any value) const;
Promise PromiseResolveAfter(uint64_t delay) const;
std::string GetString() const;
optional<std::string> GetOptionalString(bool has_value) const;
variant<int, std::string> GetIntOrString(bool get_int) const;
TestTypeOptions GetStruct() const;
TestNumberEnum GetNumberEnum() const;
TestStringEnum GetStringEnum() const;
std::vector<std::string> GetArrayOfStrings() const;
std::unordered_map<std::string, std::string> GetMapOfStrings() const;
const ByteBuffer& GetByteBuffer() const;
std::string ToPrettyString(Any anything) const;
optional<Any> optional_object;
variant<int, Any> int_or_object;
TestTypeOptions struct_;
std::vector<Any> array;
Callback callback;
Any any;
ByteBuffer buffer;
};
class TestTypeFactory : public BackingObjectFactory<TestType> {
public:
TestTypeFactory();
};
} // namespace js
} // namespace shaka
CONVERT_ENUM_AS_NUMBER(shaka::js, TestNumberEnum);
DEFINE_ENUM_MAPPING(shaka::js, TestStringEnum) {
AddMapping(Enum::EMPTY, "");
AddMapping(Enum::AUTO, "auto");
AddMapping(Enum::OTHER, "other");
}
#endif // SHAKA_EMBEDDED_JS_TEST_TYPE_H_
<file_sep>/shaka/include/shaka/vtt_cue.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_VTT_CUE_H_
#define SHAKA_EMBEDDED_VTT_CUE_H_
#include <mutex>
#include <string>
#include "macros.h"
namespace shaka {
/**
* Represents the direction to write the text.
* @see https://w3c.github.io/webvtt/#webvtt-cue-writing-direction
* @ingroup player
*/
enum class DirectionSetting {
/**
* A line extends horizontally and is offset vertically from the video
* viewport’s top edge, with consecutive lines displayed below each other.
*/
Horizontal,
/**
* A line extends vertically and is offset horizontally from the video
* viewport’s left edge, with consecutive lines displayed to the right of each
* other.
*/
LeftToRight,
/**
* A line extends vertically and is offset horizontally from the video
* viewport’s right edge, with consecutive lines displayed to the left of each
* other.
*/
RightToLeft,
};
/**
* Represents the alignment of the cue box.
* @see https://w3c.github.io/webvtt/#webvtt-cue-line-alignment
* @ingroup player
*/
enum class LineAlignSetting {
/**
* The cue box’s top side (for horizontal cues), left side (for vertical
* growing right), or right side (for vertical growing left) is aligned at the
* line.
*/
Start,
/**
* The cue box is centered at the line.
*/
Center,
/**
* The cue box’s bottom side (for horizontal cues), right side (for vertical
* growing right), or left side (for vertical growing left) is aligned at the
* line.
*/
End,
};
/**
* Represents where the position anchors the cue box.
* @see https://w3c.github.io/webvtt/#webvtt-cue-position-alignment
* @ingroup player
*/
enum class PositionAlignSetting {
/**
* The cue box’s left side (for horizontal cues) or top side (otherwise) is
* aligned at the position.
*/
LineLeft,
/**
* The cue box is centered at the position.
*/
Center,
/**
* The cue box’s right side (for horizontal cues) or bottom side (otherwise)
* is aligned at the position.
*/
LineRight,
/**
* The cue box’s alignment depends on the value of the text alignment of the
* cue.
*/
Auto,
};
/**
* Represents the alignment of text within the cue box.
* @see https://w3c.github.io/webvtt/#webvtt-cue-text-alignment
* @ingroup player
*/
enum class AlignSetting {
/**
* The text of each line is individually aligned towards the start side of the
* box.
*/
Start,
/**
* The text is aligned centered between the box’s start and end sides.
*/
Center,
/**
* The text of each line is individually aligned towards the end side of the
* box.
*/
End,
/**
* The text is aligned to the box’s left side (for horizontal cues) or top
* side (otherwise).
*/
Left,
/**
* The text is aligned to the box’s right side (for horizontal cues) or bottom
* side (otherwise).
*/
Right,
};
/**
* This defines a text cue that is used for subtitles or closed-captioning.
* This type is internally thread-safe.
*
* @see https://w3c.github.io/webvtt/#the-vttcue-interface
* @ingroup player
*/
class SHAKA_EXPORT VTTCue {
public:
VTTCue(double start_time, double end_time, const std::string& text);
VTTCue(const VTTCue& cue);
VTTCue(VTTCue&& cue);
~VTTCue();
VTTCue& operator=(const VTTCue& cue);
VTTCue& operator=(VTTCue&& cue);
/** @name TextTrackCue */
///@{
/** @return The ID of the cue. */
std::string id() const;
/** Sets the ID of the cue to the given value. */
void SetId(const std::string& id);
/** @return The start time the Cue should be rendered at. */
double startTime() const;
/** Sets the start time the Cue should be rendered at. */
void SetStartTime(double time);
/** @return The end time the Cue should be rendered at. */
double endTime() const;
/** Sets the end time the Cue should be rendered at. */
void SetEndTime(double time);
/** @return Whether the media should pause when the cue stops rendering. */
bool pauseOnExit() const;
/** Sets whether the media should pause when the cue stops rendering. */
void SetPauseOnExit(bool pause);
///@}
/** @name VTTCue */
///@{
/** @return The Cue's vertical direction setting. */
DirectionSetting vertical() const;
/** Sets the Cue's vertical direction setting. */
void SetVertical(DirectionSetting setting);
/** @return Whether the Cue snaps to lines. */
bool snapToLines() const;
/** Sets whether the Cue snaps to lines. */
void SetSnapToLines(bool snap);
/** @return The Cue's line align setting. */
LineAlignSetting lineAlign() const;
/** Sets the Cue's line align setting. */
void SetLineAlign(LineAlignSetting align);
/** @return The Cue's line value, or NAN if using 'auto'. */
double line() const;
/** Sets the Cue's line value, use NAN to signal 'auto'. */
void SetLine(double line);
/** @return The Cue's position value, or NAN if using 'auto'. */
double position() const;
/** Sets the Cue's position value, use NAN to signal 'auto'. */
void SetPosition(double position);
/** @return The Cue's position align setting. */
PositionAlignSetting positionAlign() const;
/** Sets the Cue's position align setting. */
void SetPositionAlign(PositionAlignSetting align);
/** @return The Cue's size. */
double size() const;
/** Sets the Cue's size. */
void SetSize(double size);
/** @return The align setting of the Cue. */
AlignSetting align() const;
/** Sets the align setting of the Cue. */
void SetAlign(AlignSetting align);
/** @return The text body of the Cue. */
std::string text() const;
/** Sets the text body of the cue. */
void SetText(const std::string& text);
///@}
private:
mutable std::mutex mutex_;
std::string id_;
double start_time_;
double end_time_;
bool pause_on_exit_;
DirectionSetting vertical_;
bool snap_to_lines_;
double line_;
LineAlignSetting line_align_;
double position_;
PositionAlignSetting position_align_;
double size_;
AlignSetting align_;
std::string text_;
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_VTT_CUE_H_
<file_sep>/shaka/src/memory/object_tracker.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEMORY_OBJECT_TRACKER_H_
#define SHAKA_EMBEDDED_MEMORY_OBJECT_TRACKER_H_
#include <glog/logging.h>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "src/debug/mutex.h"
#include "src/util/pseudo_singleton.h"
#include "src/util/templates.h"
namespace shaka {
class JsManagerImpl;
class RefPtrTest;
namespace eme {
class ClearKeyImplementationTest;
} // namespace eme
namespace memory {
class HeapTracer;
class Traceable;
/**
* Defines a dynamic object tracker. This is a singleton class. This is used
* to track the dynamic backing objects that we create so we can free them when
* they are no longer used. Deriving from BackingObjectBase will automatically
* use this as the backing store for 'new' usages. Objects allocated using this
* should not use 'delete'.
*/
class ObjectTracker final : public PseudoSingleton<ObjectTracker> {
public:
HeapTracer* heap_tracer() {
return tracer_.get();
}
/** Registers the given object to be tracked. */
void RegisterObject(Traceable* object);
/** @see HeapTracer::ForceAlive */
void ForceAlive(const Traceable* ptr);
/** Increment the reference count of the given object. */
void AddRef(const Traceable* object);
/** Decrement the reference count of the given object. */
void RemoveRef(const Traceable* object);
/** Get all the objects that have a non-zero ref count. */
std::unordered_set<const Traceable*> GetAliveObjects() const;
/**
* Called from the HeapTracer to free objects during a GC run.
* @param alive A set of all the currently alive objects.
*/
void FreeDeadObjects(const std::unordered_set<const Traceable*>& alive);
/** Releases all object this owns. This is called as part of shutdown. */
void Dispose();
private:
ObjectTracker();
~ObjectTracker();
friend JsManagerImpl;
friend RefPtrTest;
friend class eme::ClearKeyImplementationTest;
friend class HeapTracerTest;
friend class ObjectTrackerIntegration;
friend class ObjectTrackerTest;
/**
* Used for testing when the objects being tracked exist on the stack. This
* removes all tracked objects.
*/
void UnregisterAllObjects();
/** @return Whether the given object is alive in JavaScript. */
bool IsJsAlive(Traceable* object) const;
/** @return The number of references to the given object. */
uint32_t GetRefCount(Traceable* object) const;
ObjectTracker(const ObjectTracker&) = delete;
ObjectTracker& operator=(const ObjectTracker&) = delete;
/** Used in tests to get all managed objects. */
std::vector<const Traceable*> GetAllObjects() const;
void DestroyObjects(const std::unordered_set<Traceable*>& to_delete,
std::unique_lock<Mutex>* lock);
std::unique_ptr<HeapTracer> tracer_;
mutable Mutex mutex_;
// A map of object pointer to ref count.
std::unordered_map<Traceable*, uint32_t> objects_;
std::unordered_map<Traceable*, uint64_t> last_alive_time_;
std::unordered_set<Traceable*> to_delete_;
};
} // namespace memory
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEMORY_OBJECT_TRACKER_H_
<file_sep>/shaka/src/util/js_wrapper.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_WRAPPER_H_
#define SHAKA_EMBEDDED_JS_WRAPPER_H_
#include "src/core/ref_ptr.h"
namespace shaka {
namespace util {
template <typename T>
class JSWrapper {
public:
RefPtr<T> inner;
JSWrapper() {}
NON_COPYABLE_OR_MOVABLE_TYPE(JSWrapper);
template <typename Func, typename... Args>
auto CallInnerMethod(Func member, Args... args)
-> decltype((inner->*member)(args...)) {
DCHECK(inner) << "Must call Initialize.";
return JsManagerImpl::Instance()
->MainThread()
->AddInternalTask(TaskPriority::Internal, "",
PlainCallbackTask(std::bind(member, inner, args...)))
->GetValue();
}
template <typename Var, typename Val>
void SetMemberVariable(Var member, Val val) {
DCHECK(inner) << "Must call Initialize.";
auto callback = [this, member, val]() { inner->*member = val; };
JsManagerImpl::Instance()
->MainThread()
->AddInternalTask(TaskPriority::Internal, "",
PlainCallbackTask(callback))
->GetValue();
}
template <typename Var>
auto GetMemberVariable(Var member) -> decltype(inner->*member) {
DCHECK(inner) << "Must call Initialize.";
return JsManagerImpl::Instance()
->MainThread()
->AddInternalTask(TaskPriority::Internal, "",
PlainCallbackTask(std::bind(member, inner)))
->GetValue();
}
};
} // namespace util
} // namespace shaka
#endif // SHAKA_EMBEDDED_JS_WRAPPER_H_
<file_sep>/shaka/src/media/types.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_TYPES_H_
#define SHAKA_EMBEDDED_MEDIA_TYPES_H_
#include <functional> // For std::hash
#include <iostream>
#include <string>
#include <type_traits>
#include "src/mapping/struct.h"
#include "src/util/macros.h"
namespace shaka {
namespace media {
// enum class Status
#define DEFINE_ENUM_(DEFINE) \
/** The operation succeeded. */ \
DEFINE(Success) \
\
/** \
* The specified media stack (i.e. MediaSource) has been detached and \
* destroyed. \
*/ \
DEFINE(Detached) \
\
/** \
* FFmpeg hit the end of its internal stream. This is expected to happen \
* during shutdown, but is an internal error otherwise. \
*/ \
DEFINE(EndOfStream) \
\
/** There is no source of the specified type. */ \
DEFINE(QuotaExceeded) \
\
/** The system wasn't able to allocate the required memory. */ \
DEFINE(OutOfMemory) \
\
/** The specified action is not supported (e.g. unknown MIME type). */ \
DEFINE(NotSupported) \
\
/** \
* The specified action is not allowed (e.g. adding a second video source). \
*/ \
DEFINE(NotAllowed) \
\
/** An unknown error occurred; see log for system codes. */ \
DEFINE(UnknownError) \
\
/* ---- Demuxer Errors ---- */ \
/** \
* We were unable to open the demuxer. This usually happens because of \
* invalid input or a missing initialization segment. \
*/ \
DEFINE(CannotOpenDemuxer) \
\
/** The input stream didn't have any elementary streams. */ \
DEFINE(NoStreamsFound) \
\
/** \
* The input stream contained multiplexed content, which isn't supported. \
*/ \
DEFINE(MultiplexedContentFound) \
\
/** The container data was in an invalid format. */ \
DEFINE(InvalidContainerData) \
\
/** ---- Decoder Errors ---- */ \
/** The codec in the content didn't match the value initialized with. */ \
DEFINE(DecoderMismatch) \
\
/** Unable to initialize the decoder. */ \
DEFINE(DecoderFailedInit) \
\
/** There was an error in the codec data. */ \
DEFINE(InvalidCodecData) \
\
/** \
* The decryption key for the frame wasn't found. This error isn't fatal; \
* once the CDM gets the required key the decoder can continue. \
*/ \
DEFINE(KeyNotFound)
DEFINE_ENUM_AND_TO_STRING(Status, DEFINE_ENUM_);
#undef DEFINE_ENUM_
// enum class SourceType
#define DEFINE_ENUM_(DEFINE) \
DEFINE(Unknown) \
DEFINE(Audio) \
DEFINE(Video)
DEFINE_ENUM_AND_TO_STRING(SourceType, DEFINE_ENUM_);
#undef DEFINE_ENUM_
// enum class PipelineStatus
#define DEFINE_ENUM_(DEFINE) \
/** The pipeline is starting up. */ \
DEFINE(Initializing) \
/** The pipeline is playing media. */ \
DEFINE(Playing) \
/** The pipeline is paused (by user action). */ \
DEFINE(Paused) \
/** \
* The pipeline is performing a seek and will play once done. Note \
* that a seek is completed quickly, but we remain in this state until \
* we transition to Playing. So this is similar to Stalled. \
*/ \
DEFINE(SeekingPlay) \
/** Similar to SeekingPlay, but will remain paused. */ \
DEFINE(SeekingPause) \
/** \
* The pipeline is stalled waiting for new content. This only happens \
* when playing. If the video is paused, it will be in Paused, even if \
* there is no content. \
*/ \
DEFINE(Stalled) \
/** The video has ended and the pipeline is waiting for user action. */ \
DEFINE(Ended) \
/** There was an error that has stopped the pipeline. */ \
DEFINE(Errored)
DEFINE_ENUM_AND_TO_STRING(PipelineStatus, DEFINE_ENUM_);
#undef DEFINE_ENUM_
enum MediaReadyState {
HAVE_NOTHING = 0,
HAVE_METADATA = 1,
HAVE_CURRENT_DATA = 2,
HAVE_FUTURE_DATA = 3,
HAVE_ENOUGH_DATA = 4,
};
struct VideoPlaybackQuality : Struct {
static std::string name() {
return "VideoPlaybackQuality";
}
ADD_DICT_FIELD(double, creationTime);
ADD_DICT_FIELD(uint64_t, totalVideoFrames);
ADD_DICT_FIELD(uint64_t, droppedVideoFrames);
ADD_DICT_FIELD(uint64_t, corruptedVideoFrames);
};
struct BufferedRange {
BufferedRange() : start(0), end(0) {}
BufferedRange(double start, double end) : start(start), end(end) {}
bool operator==(const BufferedRange& other) const {
return start == other.start && end == other.end;
}
bool operator!=(const BufferedRange& other) const {
return !(*this == other);
}
double start;
double end;
};
using BufferedRanges = std::vector<BufferedRange>;
std::ostream& operator<<(std::ostream& os, const BufferedRange& range);
/** @returns A string error message for the given status. */
std::string GetErrorString(Status status);
} // namespace media
} // namespace shaka
namespace std {
// To be used as keys in an unordered_{set,map} requires a definition of
// std::hash<T>. C++14 adds a general definition for enums, but since we
// target C++11, we need to add our own.
template <>
struct hash<shaka::media::SourceType> {
size_t operator()(shaka::media::SourceType type) const {
return static_cast<size_t>(type);
}
};
} // namespace std
#endif // SHAKA_EMBEDDED_MEDIA_TYPES_H_
<file_sep>/shaka/src/media/demuxer_thread.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/demuxer_thread.h"
#include <cmath>
#include <memory>
#include <string>
#include <utility>
#include "src/core/js_manager_impl.h"
#include "src/media/media_processor.h"
#include "src/media/stream.h"
namespace shaka {
namespace media {
namespace {
std::string ShortContainerName(const std::string& container) {
if (container == "matroska") {
return "mkv";
}
DCHECK_LT(container.size(), 10u) << "Container needs a short name";
return container.substr(0, 10);
}
} // namespace
DemuxerThread::DemuxerThread(std::function<void()> on_load_meta,
MediaProcessor* processor, Stream* stream)
: mutex_("DemuxerThread"),
new_data_("New demuxed data"),
on_load_meta_(std::move(on_load_meta)),
shutdown_(false),
cur_data_(nullptr),
cur_size_(0),
window_start_(0),
window_end_(HUGE_VAL),
need_key_frame_(true),
processor_(processor),
stream_(stream),
thread_(ShortContainerName(processor->container()) + " demux",
std::bind(&DemuxerThread::ThreadMain, this)) {}
DemuxerThread::~DemuxerThread() {
CHECK(!thread_.joinable()) << "Need to call Stop() before destroying";
}
void DemuxerThread::Stop() {
shutdown_ = true;
new_data_.SignalAllIfNotSet();
thread_.join();
}
void DemuxerThread::AppendData(double timestamp_offset, double window_start,
double window_end, const uint8_t* data,
size_t data_size,
std::function<void(Status)> on_complete) {
DCHECK(data);
DCHECK_GT(data_size, 0u);
std::unique_lock<Mutex> lock(mutex_);
DCHECK(input_.empty()); // Should not be performing an update.
input_.SetBuffer(data, data_size);
processor_->SetTimestampOffset(timestamp_offset);
window_start_ = window_start;
window_end_ = window_end;
cur_data_ = data;
cur_size_ = data_size;
on_complete_ = std::move(on_complete);
new_data_.SignalAll();
}
void DemuxerThread::ThreadMain() {
using namespace std::placeholders; // NOLINT
auto on_read = std::bind(&DemuxerThread::OnRead, this, _1, _2);
auto on_reset_read = std::bind(&DemuxerThread::OnResetRead, this);
const Status init_status =
processor_->InitializeDemuxer(on_read, on_reset_read);
if (init_status != Status::Success) {
// If we get an error before we append the first segment, then we won't have
// a callback yet, so we have nowhere to send the error to. Wait until we
// get the first segment.
std::unique_lock<Mutex> lock(mutex_);
if (!on_complete_ && !shutdown_) {
new_data_.ResetAndWaitWhileUnlocked(lock);
}
CallOnComplete(init_status);
return;
}
// The demuxer initialization will read the init segment and load any metadata
// it needs.
on_load_meta_();
while (!shutdown_) {
std::unique_ptr<BaseFrame> frame;
const Status status = processor_->ReadDemuxedFrame(&frame);
if (status != Status::Success) {
std::unique_lock<Mutex> lock(mutex_);
CallOnComplete(status);
break;
}
{
std::unique_lock<Mutex> lock(mutex_);
if (frame->pts < window_start_ ||
frame->pts + frame->duration > window_end_) {
need_key_frame_ = true;
VLOG(2) << "Dropping frame outside append window, pts=" << frame->pts;
continue;
}
if (need_key_frame_) {
if (frame->is_key_frame) {
need_key_frame_ = false;
} else {
VLOG(2) << "Dropping frame while looking for key frame, pts="
<< frame->pts;
continue;
}
}
}
stream_->GetDemuxedFrames()->AppendFrame(std::move(frame));
}
}
size_t DemuxerThread::OnRead(uint8_t* data, size_t data_size) {
std::unique_lock<Mutex> lock(mutex_);
// If we get called with no input, then we are done processing the previous
// data, so call on_complete. This is a no-op if there is no callback.
if (input_.empty()) {
CallOnComplete(Status::Success);
if (!shutdown_) {
new_data_.ResetAndWaitWhileUnlocked(lock);
}
}
if (shutdown_)
return 0;
const size_t bytes_read = input_.Read(data, data_size);
VLOG(3) << "ReadCallback: Read " << bytes_read << " bytes from stream.";
return bytes_read;
}
void DemuxerThread::OnResetRead() {
std::unique_lock<Mutex> lock(mutex_);
input_.SetBuffer(cur_data_, cur_size_);
}
void DemuxerThread::CallOnComplete(Status status) {
if (on_complete_) {
// on_complete must be invoked on the event thread.
JsManagerImpl::Instance()->MainThread()->AddInternalTask(
TaskPriority::Internal, "Append done",
PlainCallbackTask(std::bind(on_complete_, status)));
on_complete_ = std::function<void(Status)>();
}
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/js/mse/video_element.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/mse/video_element.h"
#include "src/core/js_manager_impl.h"
#include "src/js/dom/document.h"
#include "src/js/mse/media_source.h"
#include "src/js/mse/time_ranges.h"
#include "src/util/macros.h"
namespace shaka {
namespace js {
namespace mse {
HTMLVideoElement::HTMLVideoElement(RefPtr<dom::Document> document)
: dom::Element(document, "video", nullopt, nullopt),
ready_state(media::HAVE_NOTHING),
autoplay(false),
loop(false),
pipeline_status_(media::PipelineStatus::Initializing),
volume_(1),
will_play_(false),
is_muted_(false),
clock_(&util::Clock::Instance),
shutdown_(false),
thread_("VideoElement", std::bind(&HTMLVideoElement::ThreadMain, this)) {
AddListenerField(EventType::Encrypted, &on_encrypted);
AddListenerField(EventType::WaitingForKey, &on_waiting_for_key);
}
// \cond Doxygen_Skip
HTMLVideoElement::~HTMLVideoElement() {
shutdown_.store(true, std::memory_order_release);
thread_.join();
}
// \endcond Doxygen_Skip
void HTMLVideoElement::Trace(memory::HeapTracer* tracer) const {
dom::Element::Trace(tracer);
tracer->Trace(&text_tracks);
tracer->Trace(&media_source_);
}
void HTMLVideoElement::ThreadMain() {
double lastTime = CurrentTime();
while (!shutdown_.load(std::memory_order_acquire)) {
const double time = CurrentTime();
if (pipeline_status_ == media::PipelineStatus::Playing) {
CheckForCueChange(time, lastTime);
lastTime = time;
}
clock_->SleepSeconds(0.25);
}
}
void HTMLVideoElement::OnReadyStateChanged(
media::MediaReadyState new_ready_state) {
DCHECK(media_source_ ? new_ready_state != media::HAVE_NOTHING
: new_ready_state == media::HAVE_NOTHING);
if (ready_state == new_ready_state)
return;
if (ready_state < media::HAVE_METADATA &&
new_ready_state >= media::HAVE_METADATA) {
ScheduleEvent<events::Event>(EventType::LoadedMetaData);
}
if (ready_state < media::HAVE_CURRENT_DATA &&
new_ready_state >= media::HAVE_CURRENT_DATA) {
ScheduleEvent<events::Event>(EventType::LoadedData);
}
if (ready_state < media::HAVE_ENOUGH_DATA &&
new_ready_state >= media::HAVE_ENOUGH_DATA) {
ScheduleEvent<events::Event>(EventType::CanPlay);
}
if (ready_state >= media::HAVE_FUTURE_DATA &&
new_ready_state < media::HAVE_FUTURE_DATA &&
new_ready_state != media::HAVE_NOTHING) {
ScheduleEvent<events::Event>(EventType::Waiting);
}
ScheduleEvent<events::Event>(EventType::ReadyStateChange);
ready_state = new_ready_state;
}
void HTMLVideoElement::OnPipelineStatusChanged(media::PipelineStatus status) {
if (status == pipeline_status_) {
// If we get another seeking status change, we still fire the 'seeking'
// event since the current time changed.
if (status == media::PipelineStatus::SeekingPlay ||
status == media::PipelineStatus::SeekingPause) {
ScheduleEvent<events::Event>(EventType::Seeking);
}
return;
}
switch (status) {
case media::PipelineStatus::Initializing:
ScheduleEvent<events::Event>(EventType::Emptied);
break;
case media::PipelineStatus::Playing:
if (pipeline_status_ == media::PipelineStatus::Paused) {
ScheduleEvent<events::Event>(EventType::Play);
} else if (pipeline_status_ == media::PipelineStatus::SeekingPlay) {
ScheduleEvent<events::Event>(EventType::Seeked);
} else {
DCHECK(pipeline_status_ == media::PipelineStatus::Stalled ||
pipeline_status_ == media::PipelineStatus::Initializing);
}
ScheduleEvent<events::Event>(EventType::Playing);
break;
case media::PipelineStatus::Paused:
if (pipeline_status_ == media::PipelineStatus::Playing ||
pipeline_status_ == media::PipelineStatus::Stalled) {
ScheduleEvent<events::Event>(EventType::Pause);
} else if (pipeline_status_ == media::PipelineStatus::SeekingPause) {
ScheduleEvent<events::Event>(EventType::Seeked);
} else {
DCHECK_EQ(pipeline_status_, media::PipelineStatus::Initializing);
}
break;
case media::PipelineStatus::Stalled:
if (pipeline_status_ == media::PipelineStatus::Playing)
ScheduleEvent<events::Event>(EventType::Pause);
break;
case media::PipelineStatus::SeekingPlay:
if (pipeline_status_ == media::PipelineStatus::Playing)
ScheduleEvent<events::Event>(EventType::Pause);
FALL_THROUGH_INTENDED;
case media::PipelineStatus::SeekingPause:
ScheduleEvent<events::Event>(EventType::Seeking);
break;
case media::PipelineStatus::Ended:
if (pipeline_status_ == media::PipelineStatus::Playing) {
ScheduleEvent<events::Event>(EventType::Pause);
} else if (pipeline_status_ == media::PipelineStatus::SeekingPlay ||
pipeline_status_ == media::PipelineStatus::SeekingPause) {
ScheduleEvent<events::Event>(EventType::Seeked);
}
ScheduleEvent<events::Event>(EventType::Ended);
break;
case media::PipelineStatus::Errored:
ScheduleEvent<events::Event>(EventType::Error);
if (!error)
error = new MediaError(MEDIA_ERR_DECODE, "Unknown media error");
break;
}
pipeline_status_ = status;
}
void HTMLVideoElement::CheckForCueChange(double newTime, double oldTime) {
for (const auto& text_track : text_tracks) {
text_track->CheckForCueChange(newTime, oldTime);
}
}
void HTMLVideoElement::OnMediaError(media::SourceType /* source */,
media::Status status) {
ScheduleEvent<events::Event>(EventType::Error);
if (!error)
error = new MediaError(MEDIA_ERR_DECODE, GetErrorString(status));
}
RefPtr<MediaSource> HTMLVideoElement::GetMediaSource() const {
return media_source_;
}
Promise HTMLVideoElement::SetMediaKeys(RefPtr<eme::MediaKeys> media_keys) {
if (!media_keys && !media_source_)
return Promise::Resolved();
if (!media_source_) {
return Promise::Rejected(JsError::DOMException(
InvalidStateError, "Cannot set MediaKeys until after setting source"));
}
eme::Implementation* cdm = media_keys ? media_keys->GetCdm() : nullptr;
media_source_->GetController()->SetCdm(cdm);
this->media_keys = media_keys;
return Promise::Resolved();
}
void HTMLVideoElement::Load() {
error = nullptr;
if (media_source_) {
media_source_->CloseMediaSource();
media_source_.reset();
OnReadyStateChanged(media::HAVE_NOTHING);
OnPipelineStatusChanged(media::PipelineStatus::Initializing);
will_play_ = false;
}
}
CanPlayTypeEnum HTMLVideoElement::CanPlayType(const std::string& type) {
if (!MediaSource::IsTypeSupported(type))
return CanPlayTypeEnum::EMPTY;
return CanPlayTypeEnum::MAYBE;
}
media::VideoPlaybackQuality HTMLVideoElement::GetVideoPlaybackQuality() const {
return media_source_
? *media_source_->GetController()->GetVideoPlaybackQuality()
: media::VideoPlaybackQuality();
}
RefPtr<TimeRanges> HTMLVideoElement::Buffered() const {
if (!media_source_)
return new TimeRanges(media::BufferedRanges());
return new TimeRanges(media_source_->GetController()->GetBufferedRanges(
media::SourceType::Unknown));
}
std::string HTMLVideoElement::Source() const {
return media_source_ ? media_source_->url : "";
}
ExceptionOr<void> HTMLVideoElement::SetSource(const std::string& src) {
// Unload any previous MediaSource objects.
Load();
DCHECK(!media_source_);
if (src.empty())
return {};
media_source_ = MediaSource::FindMediaSource(src);
if (media_source_) {
media_source_->OpenMediaSource(this);
media_source_->GetController()->SetVolume(is_muted_ ? 0 : volume_);
if (autoplay || will_play_)
media_source_->GetController()->GetPipelineManager()->Play();
} else {
// We don't support direct URL playback, only MediaSource playback.
return JsError::DOMException(NotSupportedError,
"Unknown MediaSource URL given.");
}
return {};
}
double HTMLVideoElement::CurrentTime() const {
if (!media_source_)
return 0;
return media_source_->GetController()->GetPipelineManager()->GetCurrentTime();
}
void HTMLVideoElement::SetCurrentTime(double time) {
if (media_source_) {
media_source_->GetController()->GetPipelineManager()->SetCurrentTime(time);
}
}
double HTMLVideoElement::Duration() const {
if (!media_source_)
return 0;
return media_source_->GetController()->GetPipelineManager()->GetDuration();
}
double HTMLVideoElement::PlaybackRate() const {
if (!media_source_)
return 1;
return media_source_->GetController()
->GetPipelineManager()
->GetPlaybackRate();
}
void HTMLVideoElement::SetPlaybackRate(double rate) {
if (media_source_) {
return media_source_->GetController()
->GetPipelineManager()
->SetPlaybackRate(rate);
}
}
bool HTMLVideoElement::Muted() const {
return is_muted_;
}
void HTMLVideoElement::SetMuted(bool muted) {
is_muted_ = muted;
if (media_source_)
media_source_->GetController()->SetVolume(muted ? 0 : volume_);
}
double HTMLVideoElement::Volume() const {
return volume_;
}
void HTMLVideoElement::SetVolume(double volume) {
volume_ = volume;
if (media_source_)
media_source_->GetController()->SetVolume(is_muted_ ? 0 : volume_);
}
bool HTMLVideoElement::Paused() const {
return pipeline_status_ == media::PipelineStatus::Paused ||
pipeline_status_ == media::PipelineStatus::SeekingPause ||
pipeline_status_ == media::PipelineStatus::Ended;
}
bool HTMLVideoElement::Seeking() const {
return pipeline_status_ == media::PipelineStatus::SeekingPlay ||
pipeline_status_ == media::PipelineStatus::SeekingPause;
}
bool HTMLVideoElement::Ended() const {
return pipeline_status_ == media::PipelineStatus::Ended;
}
void HTMLVideoElement::Play() {
if (media_source_)
return media_source_->GetController()->GetPipelineManager()->Play();
will_play_ = true;
}
void HTMLVideoElement::Pause() {
if (media_source_)
return media_source_->GetController()->GetPipelineManager()->Pause();
will_play_ = false;
}
RefPtr<TextTrack> HTMLVideoElement::AddTextTrack(
TextTrackKind kind, optional<std::string> label,
optional<std::string> language) {
RefPtr<TextTrack> ret =
new TextTrack(kind, label.value_or(""), language.value_or(""));
text_tracks.emplace_back(ret);
return ret;
}
HTMLVideoElementFactory::HTMLVideoElementFactory() {
AddConstant("HAVE_NOTHING", media::HAVE_NOTHING);
AddConstant("HAVE_METADATA", media::HAVE_METADATA);
AddConstant("HAVE_CURRENT_DATA", media::HAVE_CURRENT_DATA);
AddConstant("HAVE_FUTURE_DATA", media::HAVE_FUTURE_DATA);
AddConstant("HAVE_ENOUGH_DATA", media::HAVE_ENOUGH_DATA);
AddListenerField(EventType::Encrypted, &HTMLVideoElement::on_encrypted);
AddListenerField(EventType::WaitingForKey,
&HTMLVideoElement::on_waiting_for_key);
AddReadWriteProperty("autoplay", &HTMLVideoElement::autoplay);
AddReadWriteProperty("loop", &HTMLVideoElement::loop);
AddReadOnlyProperty("mediaKeys", &HTMLVideoElement::media_keys);
AddReadOnlyProperty("readyState", &HTMLVideoElement::ready_state);
AddReadOnlyProperty("textTracks", &HTMLVideoElement::text_tracks);
AddReadOnlyProperty("error", &HTMLVideoElement::error);
AddGenericProperty("paused", &HTMLVideoElement::Paused);
AddGenericProperty("seeking", &HTMLVideoElement::Seeking);
AddGenericProperty("ended", &HTMLVideoElement::Ended);
AddGenericProperty("buffered", &HTMLVideoElement::Buffered);
AddGenericProperty("src", &HTMLVideoElement::Source,
&HTMLVideoElement::SetSource);
AddGenericProperty("currentSrc", &HTMLVideoElement::Source);
AddGenericProperty("currentTime", &HTMLVideoElement::CurrentTime,
&HTMLVideoElement::SetCurrentTime);
AddGenericProperty("duration", &HTMLVideoElement::Duration);
AddGenericProperty("playbackRate", &HTMLVideoElement::PlaybackRate,
&HTMLVideoElement::SetPlaybackRate);
AddMemberFunction("load", &HTMLVideoElement::Load);
AddMemberFunction("play", &HTMLVideoElement::Play);
AddMemberFunction("pause", &HTMLVideoElement::Pause);
AddMemberFunction("setMediaKeys", &HTMLVideoElement::SetMediaKeys);
AddMemberFunction("addTextTrack", &HTMLVideoElement::AddTextTrack);
AddMemberFunction("getVideoPlaybackQuality",
&HTMLVideoElement::GetVideoPlaybackQuality);
AddStaticFunction("canPlayType", &HTMLVideoElement::CanPlayType);
NotImplemented("crossOrigin");
NotImplemented("networkState");
NotImplemented("preload");
NotImplemented("getStartDate");
NotImplemented("defaultPlaybackRate");
NotImplemented("playable");
NotImplemented("seekable");
NotImplemented("mediaGroup");
NotImplemented("controller");
NotImplemented("controls");
NotImplemented("volume");
NotImplemented("muted");
NotImplemented("defaultMuted");
NotImplemented("audioTracks");
NotImplemented("videoTracks");
}
} // namespace mse
} // namespace js
} // namespace shaka
<file_sep>/shaka/src/js/xml_http_request.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/xml_http_request.h"
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cstring>
#include <stdexcept>
#include <utility>
#include "src/core/environment.h"
#include "src/core/js_manager_impl.h"
#include "src/js/events/event.h"
#include "src/js/events/event_names.h"
#include "src/js/events/progress_event.h"
#include "src/js/js_error.h"
#include "src/js/navigator.h"
#include "src/js/timeouts.h"
#include "src/memory/heap_tracer.h"
#include "src/util/clock.h"
#include "src/util/utils.h"
namespace shaka {
namespace js {
namespace {
/** The minimum delay, in milliseconds, between "progress" events. */
constexpr size_t kProgressInterval = 15;
constexpr const char* kCookieFileName = "net_cookies.dat";
size_t UploadCallback(void* buffer, size_t member_size, size_t member_count,
void* user_data) {
auto* request = reinterpret_cast<XMLHttpRequest*>(user_data);
auto* buffer_bytes = reinterpret_cast<uint8_t*>(buffer);
size_t total_size = member_size * member_count;
return request->OnUpload(buffer_bytes, total_size);
}
size_t DownloadCallback(void* buffer, size_t member_size, size_t member_count,
void* user_data) {
auto* request = reinterpret_cast<XMLHttpRequest*>(user_data);
auto* buffer_bytes = reinterpret_cast<uint8_t*>(buffer);
size_t total_size = member_size * member_count;
request->OnDataReceived(buffer_bytes, total_size);
return total_size;
}
size_t HeaderCallback(char* buffer, size_t member_size, size_t member_count,
void* user_data) {
auto* request = reinterpret_cast<XMLHttpRequest*>(user_data);
auto* buffer_bytes = reinterpret_cast<uint8_t*>(buffer);
size_t total_size = member_size * member_count;
request->OnHeaderReceived(buffer_bytes, total_size);
return total_size;
}
double CurrentDownloadSize(CURL* curl) {
double ret;
CHECK_EQ(CURLE_OK, curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &ret));
return ret;
}
/**
* Parses the status line of the request. This will extract the status code
* and message.
* @param buffer The input buffer containing the status line.
* @param length The length of the buffer.
* @param code [OUT] Where to put the status code.
* @param message [OUT] Where to put the pointer to the start of the message.
* It will be a pointer within |buffer|. Namely
* |buffer| <= |*message| < |buffer + length|.
* @param message_length [OUT] Where to put the length of the message.
* @return True on success, false on error.
*/
bool ParseStatusLine(const char* buffer, size_t length, int* code,
const char** message, size_t* message_length) {
// NOTE: curl will convert the status line of http2 to match http1.1.
// e.g.: "HTTP/1.1 200 OK\r\n"
constexpr const char kMinStatusLine[] = "HTTP/1.1 200 \r\n";
constexpr const char kHttp10[] = "HTTP/1.0 ";
constexpr const char kHttp11[] = "HTTP/1.1 ";
constexpr const size_t kMinStatusSize = sizeof(kMinStatusLine) - 1;
constexpr const size_t kHttp10Size = sizeof(kHttp10) - 1;
constexpr const size_t kHttp11Size = sizeof(kHttp11) - 1;
constexpr const size_t kStatusSize = 3;
if (length < kMinStatusSize)
return false;
if (strncmp(buffer, kHttp10, kHttp10Size) != 0 &&
strncmp(buffer, kHttp11, kHttp11Size) != 0)
return false;
// Convert the status code, must be three numbers [0-9].
const char* status_code = buffer + kHttp10Size;
const char* status_code_end = status_code + kStatusSize;
if (!std::isdigit(status_code[0]) || !std::isdigit(status_code[1]) ||
!std::isdigit(status_code[2])) {
return false;
}
if (status_code_end[0] != ' ')
return false;
if (buffer[length - 2] != '\r' || buffer[length - 1] != '\n')
return false;
*code = std::stoi(std::string(status_code, status_code_end));
*message = status_code_end + 1;
*message_length = length - kMinStatusSize;
return true;
}
} // namespace
XMLHttpRequest::XMLHttpRequest()
: ready_state(UNSENT),
mutex_("XMLHttpRequest"),
curl_(curl_easy_init()),
request_headers_(nullptr) {
AddListenerField(EventType::Abort, &on_abort);
AddListenerField(EventType::Error, &on_error);
AddListenerField(EventType::Load, &on_load);
AddListenerField(EventType::LoadStart, &on_load_start);
AddListenerField(EventType::Progress, &on_progress);
AddListenerField(EventType::ReadyStateChange, &on_ready_state_change);
AddListenerField(EventType::Timeout, &on_timeout);
AddListenerField(EventType::LoadEnd, &on_load_end);
Reset();
}
// \cond Doxygen_Skip
XMLHttpRequest::~XMLHttpRequest() {
// Don't call Abort() since we can't raise events.
abort_pending_ = true;
JsManagerImpl::Instance()->NetworkThread()->AbortRequest(this);
curl_easy_cleanup(curl_);
if (request_headers_)
curl_slist_free_all(request_headers_);
request_headers_ = nullptr;
}
// \endcond Doxygen_Skip
void XMLHttpRequest::Trace(memory::HeapTracer* tracer) const {
// No need to trace on_* members as EventTarget handles it.
EventTarget::Trace(tracer);
std::unique_lock<Mutex> lock(mutex_);
tracer->Trace(&response);
tracer->Trace(&upload_data_);
}
bool XMLHttpRequest::IsShortLived() const {
return true;
}
void XMLHttpRequest::Abort() {
if (!JsManagerImpl::Instance()->NetworkThread()->ContainsRequest(this))
return;
abort_pending_ = true;
JsManagerImpl::Instance()->NetworkThread()->AbortRequest(this);
std::unique_lock<Mutex> lock(mutex_);
if (ready_state != DONE) {
// Fire events synchronously.
ready_state = DONE;
RaiseEvent<events::Event>(EventType::ReadyStateChange);
double total_size = CurrentDownloadSize(curl_);
RaiseEvent<events::ProgressEvent>(EventType::Progress, true, total_size,
total_size);
RaiseEvent<events::Event>(EventType::Abort);
RaiseEvent<events::ProgressEvent>(EventType::LoadEnd, true, total_size,
total_size);
}
// The spec says at the end to change the ready state without firing an event.
// https://xhr.spec.whatwg.org/#the-abort()-method
ready_state = UNSENT;
}
std::string XMLHttpRequest::GetAllResponseHeaders() const {
std::unique_lock<Mutex> lock(mutex_);
std::string ret;
for (auto it : response_headers_) {
ret.append(it.first + ": " + it.second + "\r\n");
}
return ret;
}
shaka::optional<std::string> XMLHttpRequest::GetResponseHeader(
const std::string& name) const {
std::unique_lock<Mutex> lock(mutex_);
auto it = response_headers_.find(name);
if (it == response_headers_.end())
return nullopt;
return it->second;
}
ExceptionOr<void> XMLHttpRequest::Open(const std::string& method,
const std::string& url,
optional<bool> async,
optional<std::string> user,
optional<std::string> password) {
if (async.has_value() && !async.value()) {
return JsError::DOMException(NotSupportedError,
"Synchronous requests are not supported.");
}
// This will call Abort() which may call back into JavaScript by firing
// events synchronously.
Reset();
std::unique_lock<Mutex> lock(mutex_);
this->ready_state = OPENED;
ScheduleEvent<events::Event>(EventType::ReadyStateChange);
curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_, CURLOPT_CUSTOMREQUEST, method.c_str());
if (method == "HEAD")
curl_easy_setopt(curl_, CURLOPT_NOBODY, 1L);
if (user.has_value())
curl_easy_setopt(curl_, CURLOPT_USERNAME, user->c_str());
if (password.has_value())
curl_easy_setopt(curl_, CURLOPT_PASSWORD, password->c_str());
return {};
}
ExceptionOr<void> XMLHttpRequest::Send(
optional<variant<ByteBuffer, ByteString>> maybe_data) {
// Don't query while locked to avoid a deadlock.
const bool contains_request =
JsManagerImpl::Instance()->NetworkThread()->ContainsRequest(this);
{
std::unique_lock<Mutex> lock(mutex_);
// If we are not open, or if the request has already been sent.
if (ready_state != OPENED || contains_request) {
return JsError::DOMException(InvalidStateError,
"The object's state must be OPENED.");
}
if (response_type != "arraybuffer") {
return JsError::DOMException(
NotSupportedError,
"Response type " + response_type + " is not supported");
}
if (maybe_data.has_value()) {
if (holds_alternative<ByteBuffer>(*maybe_data)) {
upload_data_ = std::move(get<ByteBuffer>(*maybe_data));
} else {
ByteString* str = &get<ByteString>(*maybe_data);
upload_data_.SetFromBuffer(str->data(), str->size());
}
upload_pos_ = 0;
curl_easy_setopt(curl_, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl_, CURLOPT_INFILESIZE_LARGE,
static_cast<curl_off_t>(upload_data_.size()));
curl_easy_setopt(curl_, CURLOPT_READDATA, this);
curl_easy_setopt(curl_, CURLOPT_READFUNCTION, UploadCallback);
} else {
curl_easy_setopt(curl_, CURLOPT_UPLOAD, 0L);
}
curl_easy_setopt(curl_, CURLOPT_TIMEOUT_MS,
static_cast<long>(timeout_ms)); // NOLINT
curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, request_headers_);
}
// Don't add while locked to avoid a deadlock.
JsManagerImpl::Instance()->NetworkThread()->AddRequest(this);
return {};
}
ExceptionOr<void> XMLHttpRequest::SetRequestHeader(const std::string& key,
const std::string& value) {
std::unique_lock<Mutex> lock(mutex_);
if (ready_state != OPENED) {
return JsError::DOMException(InvalidStateError,
"The object's state must be OPENED.");
}
const std::string header = key + ": " + value;
request_headers_ = curl_slist_append(request_headers_, header.c_str());
return {};
}
void XMLHttpRequest::RaiseProgressEvents() {
std::unique_lock<Mutex> lock(mutex_);
if (abort_pending_)
return;
if (ready_state == OPENED) {
this->ready_state = HEADERS_RECEIVED;
RaiseEvent<events::Event>(EventType::ReadyStateChange);
}
if (ready_state != LOADING) {
this->ready_state = LOADING;
RaiseEvent<events::Event>(EventType::ReadyStateChange);
}
const double cur_size = CurrentDownloadSize(curl_);
RaiseEvent<events::ProgressEvent>(EventType::Progress, estimated_size_ != 0,
cur_size, estimated_size_);
}
void XMLHttpRequest::OnDataReceived(uint8_t* buffer, size_t length) {
std::unique_lock<Mutex> lock(mutex_);
// We need to schedule these events from this callback since we don't know
// when the last header will be received.
const uint64_t now = util::Clock::Instance.GetMonotonicTime();
if (!abort_pending_ && now - last_progress_time_ >= kProgressInterval) {
last_progress_time_ = now;
JsManagerImpl::Instance()->MainThread()->AddInternalTask(
TaskPriority::Internal, "Schedule XHR events",
MemberCallbackTask(this, &XMLHttpRequest::RaiseProgressEvents));
}
temp_data_.AppendCopy(buffer, length);
}
void XMLHttpRequest::OnHeaderReceived(const uint8_t* buffer, size_t length) {
std::unique_lock<Mutex> lock(mutex_);
// This method is called for each header (including status line) for the
// duration of the request, this includes redirects.
// https://curl.haxx.se/libcurl/c/CURLOPT_HEADERFUNCTION.html
//
// Be careful about using string methods. This data may not be null-
// terminated. Be sure to use the |length| parameter and always pass the
// explicit end to std::string.
auto* str = reinterpret_cast<const char*>(buffer);
if (!parsing_headers_) {
const char* message;
size_t message_size;
if (!ParseStatusLine(str, length, &status, &message, &message_size))
return;
status_text.assign(message, message + message_size);
parsing_headers_ = true;
// Clear headers from the previous request. This is important for
// redirects so we don't keep headers from the redirect.
response_headers_.clear();
} else {
// 'Content-Length: 123\r\n'
const char* sep = std::find(str, str + length, ':');
// |sep == str + length| if not found.
const size_t key_len = sep - str;
const size_t rest_len = length - key_len; // == 0 if not found.
if (rest_len >= 2 && sep[rest_len - 2] == '\r' &&
sep[rest_len - 1] == '\n') {
std::string key = util::ToAsciiLower(std::string(str, sep));
std::string value =
util::TrimAsciiWhitespace(std::string(sep + 1, sep + rest_len - 1));
if (response_headers_.count(key) == 0)
response_headers_[key] = value;
else
response_headers_[key] += ", " + value;
// Parse content-length so we can get the size of the download.
if (key == "content-length") {
errno = 0; // |errno| is thread_local.
char* end;
const auto size = strtol(value.c_str(), &end, 10);
if (errno != ERANGE && end == value.c_str() + value.size()) {
estimated_size_ = size;
}
}
}
// Ignore invalid headers.
}
if (length == 2 && str[0] == '\r' && str[1] == '\n') {
// An empty header signals the end of the headers for the current request.
// If there is a redirect or the XMLHttpRequest object is used to make
// another request then we should parse the status line.
parsing_headers_ = false;
}
}
size_t XMLHttpRequest::OnUpload(uint8_t* buffer, size_t length) {
std::unique_lock<Mutex> lock(mutex_);
const size_t remaining = upload_data_.size() - upload_pos_;
if (length > remaining)
length = remaining;
std::memcpy(buffer, upload_data_.data() + upload_pos_, length);
upload_pos_ += length;
return length;
}
void XMLHttpRequest::Reset() {
Abort();
response.Clear();
response_text = "";
response_type = "arraybuffer";
response_url = "";
status = 0;
status_text = "";
timeout_ms = 0;
with_credentials = false;
last_progress_time_ = 0;
estimated_size_ = 0;
parsing_headers_ = false;
abort_pending_ = false;
response_headers_.clear();
temp_data_.Clear();
upload_data_.Clear();
curl_easy_reset(curl_);
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, DownloadCallback);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curl_, CURLOPT_HEADERFUNCTION, HeaderCallback);
curl_easy_setopt(curl_, CURLOPT_HEADERDATA, this);
curl_easy_setopt(curl_, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl_, CURLOPT_USERAGENT, USER_AGENT);
const std::string cookie_file =
JsManagerImpl::Instance()->GetPathForDynamicFile(kCookieFileName);
curl_easy_setopt(curl_, CURLOPT_COOKIEFILE, cookie_file.c_str());
curl_easy_setopt(curl_, CURLOPT_COOKIEJAR, cookie_file.c_str());
// Don't batch up TCP packets.
curl_easy_setopt(curl_, CURLOPT_TCP_NODELAY, 1L);
// Don't wait for a 100 Continue for uploads.
curl_easy_setopt(curl_, CURLOPT_EXPECT_100_TIMEOUT_MS, 1L);
if (request_headers_)
curl_slist_free_all(request_headers_);
request_headers_ = nullptr;
}
void XMLHttpRequest::OnRequestComplete(CURLcode code) {
// Careful, this is called from the worker thread, so we cannot call into V8.
std::unique_lock<Mutex> lock(mutex_);
if (code == CURLE_OK) {
response_text = temp_data_.CreateString();
response.SetFromDynamicBuffer(temp_data_);
temp_data_.Clear();
char* url;
curl_easy_getinfo(curl_, CURLINFO_EFFECTIVE_URL, &url);
response_url = url;
// Flush cookie list to disk so other instances can access them.
curl_easy_setopt(curl_, CURLOPT_COOKIELIST, "FLUSH");
} else {
// Don't need to reset everything on error because it was reset in Send().
// But we do need to set these as they are set in OnHeaderReceived.
status = 0;
status_text = "";
}
// Don't schedule events if we are aborted, they will be called within
// Abort().
if (!abort_pending_) {
this->ready_state = DONE;
ScheduleEvent<events::Event>(EventType::ReadyStateChange);
double total_size = CurrentDownloadSize(curl_);
ScheduleEvent<events::ProgressEvent>(EventType::Progress, true, total_size,
total_size);
switch (code) {
case CURLE_OK:
ScheduleEvent<events::Event>(EventType::Load);
break;
case CURLE_OPERATION_TIMEDOUT:
ScheduleEvent<events::Event>(EventType::Timeout);
break;
default:
LOG(ERROR) << "Error returned by curl: " << code;
ScheduleEvent<events::Event>(EventType::Error);
break;
}
ScheduleEvent<events::ProgressEvent>(EventType::LoadEnd, true, total_size,
total_size);
}
}
XMLHttpRequestFactory::XMLHttpRequestFactory() {
AddReadOnlyProperty("readyState", &XMLHttpRequest::ready_state);
AddReadOnlyProperty("response", &XMLHttpRequest::response);
AddReadOnlyProperty("responseText", &XMLHttpRequest::response_text);
AddReadWriteProperty("responseType", &XMLHttpRequest::response_type);
AddReadOnlyProperty("responseURL", &XMLHttpRequest::response_url);
AddReadOnlyProperty("status", &XMLHttpRequest::status);
AddReadOnlyProperty("statusText", &XMLHttpRequest::status_text);
AddReadWriteProperty("timeout", &XMLHttpRequest::timeout_ms);
AddReadOnlyProperty("withCredentials", &XMLHttpRequest::with_credentials);
AddListenerField(EventType::Abort, &XMLHttpRequest::on_abort);
AddListenerField(EventType::Error, &XMLHttpRequest::on_error);
AddListenerField(EventType::Load, &XMLHttpRequest::on_load);
AddListenerField(EventType::LoadStart, &XMLHttpRequest::on_load_start);
AddListenerField(EventType::Progress, &XMLHttpRequest::on_progress);
AddListenerField(EventType::ReadyStateChange,
&XMLHttpRequest::on_ready_state_change);
AddListenerField(EventType::Timeout, &XMLHttpRequest::on_timeout);
AddListenerField(EventType::LoadEnd, &XMLHttpRequest::on_load_end);
AddMemberFunction("abort", &XMLHttpRequest::Abort);
AddMemberFunction("getAllResponseHeaders",
&XMLHttpRequest::GetAllResponseHeaders);
AddMemberFunction("getResponseHeader", &XMLHttpRequest::GetResponseHeader);
AddMemberFunction("open", &XMLHttpRequest::Open);
AddMemberFunction("send", &XMLHttpRequest::Send);
AddMemberFunction("setRequestHeader", &XMLHttpRequest::SetRequestHeader);
}
} // namespace js
} // namespace shaka
<file_sep>/shaka/src/js/mse/media_source.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_MSE_MEDIA_SOURCE_H_
#define SHAKA_EMBEDDED_JS_MSE_MEDIA_SOURCE_H_
#include <string>
#include <unordered_map>
#include "shaka/optional.h"
#include "src/core/member.h"
#include "src/core/ref_ptr.h"
#include "src/js/events/event_target.h"
#include "src/mapping/byte_buffer.h"
#include "src/mapping/enum.h"
#include "src/mapping/exception_or.h"
#include "src/media/types.h"
#include "src/media/video_controller.h"
namespace shaka {
namespace js {
namespace mse {
class HTMLVideoElement;
class SourceBuffer;
enum class MediaSourceReadyState {
CLOSED,
OPEN,
ENDED,
};
class MediaSource : public events::EventTarget {
DECLARE_TYPE_INFO(MediaSource);
public:
MediaSource();
static MediaSource* Create() {
return new MediaSource();
}
static bool IsTypeSupported(const std::string& mime_type);
static RefPtr<MediaSource> FindMediaSource(const std::string& url);
media::VideoController* GetController() {
return &controller_;
}
void Trace(memory::HeapTracer* tracer) const override;
ExceptionOr<RefPtr<SourceBuffer>> AddSourceBuffer(const std::string& type);
ExceptionOr<void> EndOfStream(optional<std::string> error);
double GetDuration() const;
ExceptionOr<void> SetDuration(double duration);
/** Called when this MediaSource gets attached to a video element. */
void OpenMediaSource(RefPtr<HTMLVideoElement> video);
/** Called when the media source gets detached. */
void CloseMediaSource();
Listener on_source_open;
Listener on_source_ended;
Listener on_source_close;
MediaSourceReadyState ready_state;
const std::string url;
private:
/** Called when the media's ready-state changes. */
void OnReadyStateChanged(media::MediaReadyState ready_state);
/** Called when the media pipeline status changes. */
void OnPipelineStatusChanged(media::PipelineStatus status);
/** Called when a media error occurs. */
void OnMediaError(media::SourceType source, media::Status error);
/** Called when the media pipeline is waiting for an EME key. */
void OnWaitingForKey();
/** Called when we get new encrypted initialization data. */
void OnEncrypted(shaka::eme::MediaKeyInitDataType init_data_type,
ByteBuffer init_data);
std::unordered_map<media::SourceType, Member<SourceBuffer>> source_buffers_;
media::VideoController controller_;
Member<HTMLVideoElement> video_element_;
// A map of every MediaSource object created. These are not traced so they
// are weak pointers. Once a MediaSource gets destroyed, it will be removed
// from this map by its destructor.
static std::unordered_map<std::string, Member<MediaSource>> media_sources_;
};
class MediaSourceFactory
: public BackingObjectFactory<MediaSource, events::EventTarget> {
public:
MediaSourceFactory();
};
} // namespace mse
} // namespace js
} // namespace shaka
DEFINE_ENUM_MAPPING(shaka::js::mse, MediaSourceReadyState) {
AddMapping(Enum::CLOSED, "closed");
AddMapping(Enum::OPEN, "open");
AddMapping(Enum::ENDED, "ended");
}
#endif // SHAKA_EMBEDDED_JS_MSE_MEDIA_SOURCE_H_
<file_sep>/shaka/src/js/eme/search_registry.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/eme/search_registry.h"
#include <utility>
#include "shaka/eme/implementation.h"
#include "shaka/eme/implementation_factory.h"
#include "shaka/eme/implementation_registry.h"
#include "src/core/ref_ptr.h"
#include "src/js/eme/media_key_system_access.h"
#include "src/js/js_error.h"
#include "src/js/mse/media_source.h"
namespace shaka {
namespace js {
namespace eme {
namespace {
bool IsPersistentSessionType(MediaKeySessionType type) {
return type == MediaKeySessionType::PersistentLicense;
}
bool SupportsContentType(const std::string& content_type) {
media::SourceType unused_type;
std::string container;
std::string unused_codec;
if (!ParseMimeAndCheckSupported(content_type, &unused_type, &container,
&unused_codec)) {
return false;
}
// FFmpeg demuxer only exposes encryption info for MP4 and WebM.
if (container != "mp4" && container != "webm")
return false;
return true;
}
bool GetSupportedConfiguration(
const ImplementationFactory* implementation,
const MediaKeySystemConfiguration& candidate_config,
MediaKeySystemConfiguration* supported_config) {
// 1. Let accumulated configuration be a new MediaKeySystemConfiguration
// dictionary.
// Note: accumulated configuration == supported_config
// 2. Set the label member of accumulated configuration to equal the label
// member of candidate configuration.
supported_config->label = candidate_config.label;
// 3. If the initDataTypes member of candidate configuration is non-empty, run
// the following steps:
if (!candidate_config.initDataTypes.empty()) {
// 1. Let supported types be an empty sequence of DOMStrings.
supported_config->initDataTypes.clear();
// 2. For each value in candidate configuration's initDataTypes member:
for (auto& init_data_type : candidate_config.initDataTypes) {
// 1. Let initDataType be the value.
// 2. If the implementation supports generating requests based on
// initDataType, add initDataType to supported types. String comparison is
// case-sensitive. The empty string is never supported.
if (implementation->SupportsInitDataType(init_data_type))
supported_config->initDataTypes.push_back(init_data_type);
}
// 3. If supported types is empty, return NotSupported.
if (supported_config->initDataTypes.empty()) {
VLOG(1) << "None of the init data types are supported";
return false;
}
}
// 4. Let distinctive identifier requirement be the value of candidate
// configuration's distinctiveIdentifier member.
MediaKeysRequirement distinctive_identifier =
candidate_config.distinctiveIdentifier;
// NA: 5. If distinctive identifier requirement is "optional" and Distinctive
// Identifiers are not allowed according to restrictions, set distinctive
// identifier requirement to "not-allowed".
// 6. Follow the steps for distinctive identifier requirement from the
// following list:
switch (distinctive_identifier) {
case MediaKeysRequirement::Required:
if (implementation->DistinctiveIdentifier() ==
MediaKeysRequirement::NotAllowed) {
VLOG(1) << "Distinctive identifier is required by app, but unsupported "
"by implementation";
return false;
}
break;
case MediaKeysRequirement::Optional:
break;
case MediaKeysRequirement::NotAllowed:
if (implementation->DistinctiveIdentifier() ==
MediaKeysRequirement::Required) {
VLOG(1) << "Distinctive identifier is required by implementation, but "
"app doesn't allow it";
return false;
}
break;
}
// 7. Set the distinctiveIdentifier member of accumulated configuration to
// equal distinctive identifier requirement.
supported_config->distinctiveIdentifier = distinctive_identifier;
// 8. Let persistent state requirement be equal to the value of candidate
// configuration's persistentState member.
MediaKeysRequirement persistent_state = candidate_config.persistentState;
// NA: 9. If persistent state requirement is "optional" and persisting state
// is not allowed according to restrictions, set persistent state requirement
// to "not-allowed".
// 10. Follow the steps for persistent state requirement from the following
// list:
switch (persistent_state) {
case MediaKeysRequirement::Required:
if (implementation->PersistentState() ==
MediaKeysRequirement::NotAllowed) {
VLOG(1) << "Persistent state is required by app, but unsupported by "
"implementation";
return false;
}
break;
case MediaKeysRequirement::Optional:
break;
case MediaKeysRequirement::NotAllowed:
if (implementation->PersistentState() == MediaKeysRequirement::Required) {
VLOG(1) << "Persistent state is required by implementation, but app "
"doesn't allow it";
return false;
}
break;
}
// 11. Set the persistentState member of accumulated configuration to equal
// the value of persistent state requirement.
supported_config->persistentState = persistent_state;
// 12. Follow the steps for the first matching condition from the following
// list:
std::vector<MediaKeySessionType> session_types =
candidate_config.sessionTypes;
if (session_types.empty())
session_types.push_back(MediaKeySessionType::Temporary);
// 13. For each value in session types.
for (auto& session_type : session_types) {
// 1. Let session type be the value.
// 2. If accumulated configuration's persistentState value is "not-allowed"
// and the Is persistent session type? algorithm returns true for session
// type return NotSupported.
if (supported_config->persistentState == MediaKeysRequirement::NotAllowed &&
IsPersistentSessionType(session_type)) {
VLOG(1) << "Request for persistent session but persistentState is "
"'not-allowed'";
return false;
}
// 3. If the implementation does not support session type in combination
// with accumulated configuration and restrictions for other reasons, return
// NotSupported.
if (!implementation->SupportsSessionType(session_type)) {
VLOG(1) << "Implementation doesn't support session type";
return false;
}
// 4. If accumulated configuration's persistentState value is "optional" and
// the result of running the Is persistent session type? algorithm on
// session type is true, change accumulated configuration's persistentState
// value to "required".
if (IsPersistentSessionType(session_type)) {
// The value NotAllowed was handled above, so the value is either
// Optional or already Required.
supported_config->persistentState = MediaKeysRequirement::Required;
}
}
// 14. Set the sessionTypes member of accumulated configuration to session
// types.
supported_config->sessionTypes = session_types;
// 15. If the videoCapabilities and audioCapabilities members in candidate
// configuration are both empty, return NotSupported.
if (candidate_config.audioCapabilities.empty() &&
candidate_config.videoCapabilities.empty()) {
VLOG(1) << "No audio/video capabilities given";
return false;
}
// 16. If the videoCapabilities member in candidate configuration is non-empty
if (!candidate_config.videoCapabilities.empty()) {
for (auto& video_cap : candidate_config.videoCapabilities) {
if (SupportsContentType(video_cap.contentType) &&
implementation->SupportsVideoRobustness(video_cap.robustness)) {
supported_config->videoCapabilities.push_back(video_cap);
}
}
if (supported_config->videoCapabilities.empty()) {
VLOG(1) << "None of the video capabilities are supported";
return false;
}
}
// 17. If the audioCapabilities member in candidate configuration is non-empty
if (!candidate_config.audioCapabilities.empty()) {
for (auto& audio_cap : candidate_config.audioCapabilities) {
if (SupportsContentType(audio_cap.contentType) &&
implementation->SupportsAudioRobustness(audio_cap.robustness)) {
supported_config->audioCapabilities.push_back(audio_cap);
}
}
if (supported_config->audioCapabilities.empty()) {
VLOG(1) << "None of the audio capabilities are supported";
return false;
}
}
// 18. If accumulated configuration's distinctiveIdentifier value is
// "optional", follow the steps for the first matching condition from the
// following list:
if (supported_config->distinctiveIdentifier ==
MediaKeysRequirement::Optional) {
if (implementation->DistinctiveIdentifier() ==
MediaKeysRequirement::Required) {
supported_config->distinctiveIdentifier = MediaKeysRequirement::Required;
} else {
supported_config->distinctiveIdentifier =
MediaKeysRequirement::NotAllowed;
}
}
// 19. If accumulated configuration's persistentState value is "optional",
// follow the steps for the first matching condition from the following list:
if (supported_config->persistentState == MediaKeysRequirement::Optional) {
if (implementation->PersistentState() == MediaKeysRequirement::Required) {
supported_config->persistentState = MediaKeysRequirement::Required;
} else {
supported_config->persistentState = MediaKeysRequirement::NotAllowed;
}
}
// Ignore remaining steps since they pertain to consent.
return true;
}
} // namespace
SearchRegistry::SearchRegistry(Promise promise, std::string key_system,
std::vector<MediaKeySystemConfiguration> configs)
: promise_(std::move(promise)),
key_system_(std::move(key_system)),
configs_(std::move(configs)) {}
SearchRegistry::~SearchRegistry() {}
SearchRegistry::SearchRegistry(SearchRegistry&&) = default;
SearchRegistry& SearchRegistry::operator=(SearchRegistry&&) = default;
void SearchRegistry::Trace(memory::HeapTracer* tracer) const {
tracer->Trace(&promise_);
tracer->Trace(&configs_);
}
void SearchRegistry::operator()() {
// 1. If keySystem is not one of the Key Systems supported by the user agent,
// reject promise with a NotSupportedError. String comparison is
// case-sensitive.
// 2. Let implementation be the implementation of keySystem.
auto* implementation = ImplementationRegistry::GetImplementation(key_system_);
if (!implementation) {
VLOG(1) << "No implementation found for: " << key_system_;
promise_.RejectWith(JsError::DOMException(
NotSupportedError, "Key system " + key_system_ + " is not supported."));
return;
}
// 3. For each value in supportedConfigurations:
for (auto& candidate_config : configs_) {
// 1. Let candidate configuration be the value.
// 2. Let supported configuration be the result of executing the Get
// Supported Configuration algorithm on implementation, candidate
// configuration, and origin.
// 3. If supported configuration is not NotSupported, run the following
// steps:
MediaKeySystemConfiguration supported_config;
if (GetSupportedConfiguration(implementation, candidate_config,
&supported_config)) {
// 1. Let access be a new MediaKeySystemAccess object, and initialize it
// as follows:
RefPtr<MediaKeySystemAccess> access(new MediaKeySystemAccess(
key_system_, supported_config, implementation));
// 2. Resolve promise with access and abort the parallel steps of this
// algorithm.
LocalVar<JsValue> value(ToJsValue(access));
promise_.ResolveWith(value);
return;
}
}
// 4. Reject promise with NotSupportedError.
promise_.RejectWith(JsError::DOMException(
NotSupportedError, "None of the given configurations are supported."));
}
} // namespace eme
} // namespace js
} // namespace shaka
<file_sep>/shaka/tools/version.py
#!/usr/bin/python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Generates the version.h file that contains the library version."""
from __future__ import print_function
import argparse
import os
import re
import subprocess
import sys
import embed_utils
_MAX_VERSION = 2**16 - 1
# The commits, beta version, and is-dirty (1 bit) are stored in a 16-bit block.
_MAX_COMMITS = 2**12 - 1
_MAX_BETA_VERSION = 2**3 - 1
def _GetVersion():
"""Returns the version string of the library."""
try:
cur_dir = os.path.dirname(__file__)
cmd = ['git', '-C', cur_dir, 'describe', '--tags', '--dirty']
with open(os.devnull, 'w') as null:
return subprocess.check_output(cmd, stderr=null).strip()
except subprocess.CalledProcessError:
# TODO: Remove once the first version is tagged.
return 'v0.1.0-beta'
def ParseVersion(version_str):
"""Parses the given version string.
The version numbering is such that each commit gets a unique version number
and can be compared using integer comparisons. The major, minor, and revision
components are just 16-bit portions of the number; the tag forms the low
16-bits.
The tag contains the beta version number, the commit count since the last
version, and whether the working directory is dirty. If this is a beta
version, (e.g. v1.2.3-beta), then the returned number will actually be the
previous version (1, 2, 2) and the tag will contain the beta version number.
Because the beta version is the highest in the bit ordering, it will make it
larger than a version string from the previous version (v1.2.2).
64 48 32 16 13 0
|-------------------------------------------------------------------|
| Major | Minor | Revision | Tag |
| | | | B | Commits |D|
|-------------------------------------------------------------------|
Args:
version: The version string to parse.
Returns:
The parsed version, as a 4-tuple of numbers.
"""
match = re.match(
r'^v(\d+)\.(\d+)\.(\d+)(-beta(\d*))?(-(\d+)-g[0-9a-f]+)?(-dirty)?$',
version_str)
if not match:
raise ValueError('Invalid version format: ' + version_str)
major = int(match.group(1))
minor = int(match.group(2))
revision = int(match.group(3))
tag = 0
if any(v > _MAX_VERSION for v in (major, minor, revision)):
raise ValueError('Version number too large: ' + version_str)
if major == 0 and minor == 0 and revision == 0:
raise ValueError('Version cannot be v0.0.0')
if match.group(4):
# If this is a pre-release version, reduce the numbers so the release
# version will be larger than this number.
beta_version = int(match.group(5) or 1)
if beta_version == 0 or beta_version > _MAX_BETA_VERSION:
raise ValueError('Invalid beta version number: ' + version_str)
tag = beta_version << 13
if revision != 0:
revision -= 1
elif minor != 0:
revision = _MAX_VERSION
minor -= 1
else:
assert major > 0
minor = revision = _MAX_VERSION
major -= 1
if match.group(6):
commits = int(match.group(7))
if commits == 0:
raise ValueError('Invalid version format: ' + version_str)
if commits > _MAX_COMMITS:
raise ValueError('Too many commits since last release: ' + version_str)
tag |= commits << 1
if match.group(8):
tag |= 1
return major, minor, revision, tag
def _GenVersion(output):
"""Writes the version.h file to the given file object."""
version = _GetVersion()
major, minor, revision, tag = ParseVersion(version)
assert major >= 0 and major <= _MAX_VERSION
assert minor >= 0 and minor <= _MAX_VERSION
assert revision >= 0 and revision <= _MAX_VERSION
assert tag >= 0 and tag <= _MAX_VERSION
writer = embed_utils.CodeWriter(output)
writer.Write('#define SHAKA_VERSION_MAJOR %dULL' % major)
writer.Write('#define SHAKA_VERSION_MINOR %dULL' % minor)
writer.Write('#define SHAKA_VERSION_REVISION %dULL' % revision)
writer.Write('#define SHAKA_VERSION_TAG %dULL' % tag)
writer.Write('#define SHAKA_VERSION_INT ('
'(SHAKA_VERSION_MAJOR << 48ULL) | '
'(SHAKA_VERSION_MINOR << 32ULL) | '
'(SHAKA_VERSION_REVISION << 16ULL) | (SHAKA_VERSION_TAG))')
writer.Write('#define SHAKA_VERSION_STR "%s"' % version)
writer.Write()
writer.Write('#ifdef __cplusplus')
writer.Write('extern "C" {')
writer.Write('#endif // __cplusplus')
writer.Write('/** @return The runtime version of the library. */')
writer.Write('const char* GetShakaEmbeddedVersion();')
writer.Write('#ifdef __cplusplus')
writer.Write('}')
writer.Write('#endif // __cplusplus')
def main(argv):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', required=True,
help='The path to the file to generate.')
parsed_args = parser.parse_args(argv)
output_dir = os.path.dirname(parsed_args.output)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(parsed_args.output, 'w') as f:
_GenVersion(f)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
<file_sep>/shaka/src/media/media_utils.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/media_utils.h"
#include <glog/logging.h>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
}
#include <algorithm>
#include <type_traits>
#include "src/media/hardware_support.h"
#include "src/util/macros.h"
namespace shaka {
namespace media {
namespace {
struct StringMapping {
const char* source;
const char* dest;
};
const StringMapping kContainerMap[] = {
{"mp4", "mov"},
{"webm", "matroska"},
};
const StringMapping kCodecMap[] = {
{"avc1", "h264"}, {"avc3", "h264"}, {"hev1", "hevc"},
{"hvc1", "hevc"}, {"mp4a", "aac"},
};
constexpr const char* kWhitespaceCharacters = " \f\n\r\t\v";
/** @returns Whether the given string is a MIME token. */
bool IsToken(const std::string& token) {
return !token.empty() &&
token.find_first_of(R"(()<>@,;:\"/[]?=)") == std::string::npos &&
token.find_first_of(kWhitespaceCharacters) == std::string::npos;
}
std::string substr_end(const std::string& source, std::string::size_type start,
std::string::size_type end) {
if (end == std::string::npos)
return source.substr(start);
return source.substr(start, end - start);
}
} // namespace
bool ParseMimeType(const std::string& source, std::string* type,
std::string* subtype,
std::unordered_map<std::string, std::string>* params) {
// Extract type.
const auto type_end = source.find('/');
if (type_end == std::string::npos)
return false;
*type = util::TrimAsciiWhitespace(substr_end(source, 0, type_end));
if (!IsToken(*type))
return false;
// Extract subtype.
const auto subtype_end = source.find(';', type_end);
*subtype =
util::TrimAsciiWhitespace(substr_end(source, type_end + 1, subtype_end));
if (!IsToken(*subtype))
return false;
// Extract parameters.
params->clear();
auto param_end = subtype_end;
while (param_end != std::string::npos) {
const auto name_end = source.find('=', param_end);
if (name_end == std::string::npos)
return false;
const std::string param_name =
util::TrimAsciiWhitespace(substr_end(source, param_end + 1, name_end));
if (!IsToken(param_name))
return false;
const auto value_start =
source.find_first_not_of(kWhitespaceCharacters, name_end + 1);
std::string value;
if (value_start == std::string::npos) {
param_end = std::string::npos;
value = "";
} else if (source[value_start] == '"') {
const auto str_end = source.find('"', value_start + 1);
if (str_end == std::string::npos)
return false;
value = substr_end(source, value_start + 1, str_end);
param_end = source.find(';', str_end);
const std::string extra =
util::TrimAsciiWhitespace(substr_end(source, str_end + 1, param_end));
if (!extra.empty())
return false;
} else {
param_end = source.find(';', name_end);
value = util::TrimAsciiWhitespace(
substr_end(source, name_end + 1, param_end));
if (!IsToken(value))
return false;
}
params->emplace(util::ToAsciiLower(param_name), value);
}
return true;
}
bool IsTypeSupported(const std::string& container, const std::string& codecs,
int width, int height) { // NOLINT(misc-unused-parameters)
if (codecs.find(',') != std::string::npos) {
VLOG(1) << "Multiplexed streams not supported.";
return false;
}
const std::string norm_container = NormalizeContainer(container);
if (!av_find_input_format(norm_container.c_str())) {
VLOG(1) << "Container '" << norm_container << "' (normalized from '"
<< container << "') is not supported";
return false;
}
const std::string norm_codec = NormalizeCodec(codecs);
if (!codecs.empty() && !avcodec_find_decoder_by_name(norm_codec.c_str())) {
VLOG(1) << "Codec '" << norm_codec << "' (normalized from '" << codecs
<< "') is not supported";
return false;
}
#ifdef FORCE_HARDWARE_DECODE
if (!DoesHardwareSupportCodec(codecs, width, height)) {
VLOG(1) << "Codec '" << codecs << "' isn't supported by the hardware.";
return false;
}
#endif
return true;
}
bool ParseMimeAndCheckSupported(const std::string& mime_type,
SourceType* source_type, std::string* container,
std::string* codec) {
std::string type;
std::unordered_map<std::string, std::string> params;
if (!ParseMimeType(mime_type, &type, container, ¶ms))
return false;
const long width = atol(params["width"].c_str()); // NOLINT
const long height = atol(params["height"].c_str()); // NOLINT
if (!IsTypeSupported(*container, params["codecs"], width, height))
return false;
if (type == "video") {
*source_type = SourceType::Video;
} else if (type == "audio") {
*source_type = SourceType::Audio;
} else {
VLOG(1) << "Non-audio/video MIME given '" << mime_type << "'";
return false;
}
*codec = params["codecs"];
return true;
}
std::string NormalizeContainer(const std::string& container) {
for (const auto& entry : kContainerMap)
if (container == entry.source)
return entry.dest;
return container;
}
std::string NormalizeCodec(const std::string& codec) {
const std::string simple_codec = codec.substr(0, codec.find('.'));
for (const auto& entry : kCodecMap)
if (simple_codec == entry.source)
return entry.dest;
return simple_codec;
}
BufferedRanges IntersectionOfBufferedRanges(
const std::vector<BufferedRanges>& sources) {
if (sources.empty())
return BufferedRanges();
BufferedRanges accumulated = sources[0];
for (auto& source : sources) {
BufferedRanges temp;
size_t acc_i = 0, source_i = 0;
while (acc_i < accumulated.size() && source_i < source.size()) {
const double start =
std::max(accumulated[acc_i].start, source[source_i].start);
const double end = std::min(accumulated[acc_i].end, source[source_i].end);
if (end > start)
temp.emplace_back(start, end);
if (accumulated[acc_i].end < source[source_i].end)
acc_i++;
else
source_i++;
}
accumulated.swap(temp);
}
return accumulated;
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/media/ffmpeg_encoded_frame.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/ffmpeg_encoded_frame.h"
extern "C" {
#include <libavutil/encryption_info.h>
}
#include <netinet/in.h>
#include <limits>
#include <vector>
#include "shaka/eme/configuration.h"
#include "shaka/eme/implementation.h"
namespace shaka {
namespace media {
namespace {
constexpr const size_t kAesBlockSize = 16;
constexpr const uint32_t kCencScheme = 0x63656e63;
constexpr const uint32_t kCensScheme = 0x63656e73;
constexpr const uint32_t kCbc1Scheme = 0x63626331;
constexpr const uint32_t kCbcsScheme = 0x63626373;
void IncrementIv(uint32_t count, std::vector<uint8_t>* iv) {
DCHECK_EQ(iv->size(), 16u);
auto* counter = reinterpret_cast<uint32_t*>(&iv->at(8));
// The IV is a big-endian integer. ntohl will convert a big-endian number to
// a host byte order; htonl does the opposite. Since these are unsigned,
// overflow is well-defined.
constexpr const uint32_t max = std::numeric_limits<uint32_t>::max();
if (max - count < ntohl(counter[1])) {
counter[0] = htonl(ntohl(counter[0]) + 1);
}
counter[1] = htonl(ntohl(counter[1]) + count);
}
} // namespace
// static
FFmpegEncodedFrame* FFmpegEncodedFrame::MakeFrame(AVPacket* pkt,
AVStream* stream,
size_t stream_id,
double timestamp_offset) {
const double factor = av_q2d(stream->time_base);
const double pts = pkt->pts * factor + timestamp_offset;
const double dts = pkt->dts * factor + timestamp_offset;
const double duration = pkt->duration * factor;
const bool is_key_frame = pkt->flags & AV_PKT_FLAG_KEY;
return new (std::nothrow) FFmpegEncodedFrame(
pkt, stream_id, timestamp_offset, pts, dts, duration, is_key_frame);
}
FFmpegEncodedFrame::~FFmpegEncodedFrame() {
av_packet_unref(&packet_);
}
FrameType FFmpegEncodedFrame::frame_type() const {
return FrameType::FFmpegEncodedFrame;
}
size_t FFmpegEncodedFrame::EstimateSize() const {
size_t size = sizeof(*this) + packet_.size;
for (int i = packet_.side_data_elems; i; i--)
size += packet_.side_data[i - 1].size;
return size;
}
bool FFmpegEncodedFrame::is_encrypted() const {
return av_packet_get_side_data(&packet_, AV_PKT_DATA_ENCRYPTION_INFO,
nullptr);
}
Status FFmpegEncodedFrame::Decrypt(eme::Implementation* cdm,
AVPacket* dest_packet) const {
DCHECK(cdm) << "Must pass a CDM";
DCHECK(dest_packet) << "Must pass a valid packet";
DCHECK_LE(packet_.size, dest_packet->size);
DCHECK(is_encrypted()) << "This frame isn't encrypted";
int side_data_size;
uint8_t* side_data = av_packet_get_side_data(
&packet_, AV_PKT_DATA_ENCRYPTION_INFO, &side_data_size);
if (!side_data) {
LOG(ERROR) << "Unable to get side data from packet.";
return Status::UnknownError;
}
std::unique_ptr<AVEncryptionInfo, void (*)(AVEncryptionInfo*)> enc_info(
av_encryption_info_get_side_data(side_data, side_data_size),
&av_encryption_info_free);
if (!enc_info) {
LOG(ERROR) << "Could not allocate new encryption info structure.";
return Status::OutOfMemory;
}
eme::EncryptionScheme scheme;
switch (enc_info->scheme) {
case kCencScheme:
if (enc_info->crypt_byte_block != 0 || enc_info->skip_byte_block != 0) {
LOG(ERROR) << "Cannot specify encryption pattern with 'cenc' scheme.";
return Status::InvalidContainerData;
}
scheme = eme::EncryptionScheme::AesCtr;
break;
case kCensScheme:
scheme = eme::EncryptionScheme::AesCtr;
break;
case kCbc1Scheme:
if (enc_info->crypt_byte_block != 0 || enc_info->skip_byte_block != 0) {
LOG(ERROR) << "Cannot specify encryption pattern with 'cbc1' scheme.";
return Status::InvalidContainerData;
}
scheme = eme::EncryptionScheme::AesCbc;
break;
case kCbcsScheme:
scheme = eme::EncryptionScheme::AesCbc;
break;
default:
LOG(ERROR) << "Scheme 0x" << std::hex << enc_info->scheme
<< " is unsupported";
return Status::NotSupported;
}
if (enc_info->subsample_count == 0) {
const eme::DecryptStatus decrypt_status = cdm->Decrypt(
scheme,
eme::EncryptionPattern{enc_info->crypt_byte_block,
enc_info->skip_byte_block},
0, enc_info->key_id, enc_info->key_id_size, enc_info->iv,
enc_info->iv_size, packet_.data, packet_.size, dest_packet->data);
switch (decrypt_status) {
case eme::DecryptStatus::Success:
break;
case eme::DecryptStatus::NotSupported:
return Status::NotSupported;
case eme::DecryptStatus::KeyNotFound:
return Status::KeyNotFound;
default:
return Status::UnknownError;
}
} else {
const uint8_t* src = packet_.data;
uint8_t* dest = dest_packet->data;
size_t total_size = packet_.size;
size_t block_offset = 0;
std::vector<uint8_t> cur_iv(enc_info->iv, enc_info->iv + enc_info->iv_size);
for (uint32_t i = 0; i < enc_info->subsample_count; i++) {
const unsigned int clear_bytes =
enc_info->subsamples[i].bytes_of_clear_data;
const unsigned int protected_bytes =
enc_info->subsamples[i].bytes_of_protected_data;
if (total_size < clear_bytes ||
total_size - clear_bytes < protected_bytes) {
LOG(ERROR) << "Invalid subsample size";
return Status::InvalidContainerData;
}
// Copy clear content first.
memcpy(dest, src, clear_bytes);
src += clear_bytes;
dest += clear_bytes;
total_size -= clear_bytes;
// If there is nothing to decrypt, skip to the next subsample.
if (protected_bytes == 0)
continue;
// Decrypt encrypted content.
const eme::DecryptStatus decrypt_status = cdm->Decrypt(
scheme,
eme::EncryptionPattern{enc_info->crypt_byte_block,
enc_info->skip_byte_block},
block_offset, enc_info->key_id, enc_info->key_id_size, cur_iv.data(),
cur_iv.size(), src, protected_bytes, dest);
switch (decrypt_status) {
case eme::DecryptStatus::Success:
break;
case eme::DecryptStatus::NotSupported:
return Status::NotSupported;
case eme::DecryptStatus::KeyNotFound:
return Status::KeyNotFound;
default:
return Status::UnknownError;
}
if (enc_info->scheme == kCencScheme || enc_info->scheme == kCensScheme) {
uint32_t increment = 0;
if (enc_info->scheme == kCencScheme) {
// Increment the IV for each AES block we decrypted; add the
// block_offset to account for any partial block at the beginning.
increment = (block_offset + protected_bytes) / kAesBlockSize;
} else {
// Increment the IV for each encrypted block within the pattern.
const size_t num_blocks = protected_bytes / kAesBlockSize;
const size_t pattern_size =
enc_info->crypt_byte_block + enc_info->skip_byte_block;
// Count the number of "pattern blocks" in the protected part of the
// subsample. If there is a partial pattern, include it only if it
// has a whole crypt_byte_block.
increment = (num_blocks / pattern_size) * enc_info->crypt_byte_block;
if (num_blocks % pattern_size >= enc_info->crypt_byte_block)
increment += enc_info->crypt_byte_block;
}
IncrementIv(increment, &cur_iv);
block_offset = (block_offset + protected_bytes) % kAesBlockSize;
} else if (enc_info->scheme == kCbc1Scheme) {
// 'cbc1' uses cipher-block-chaining, so the IV should be the last
// encrypted block of this subsample.
if (protected_bytes < kAesBlockSize ||
protected_bytes % kAesBlockSize != 0) {
LOG(ERROR) << "'cbc1' requires subsamples to be a multiple of the "
"AES block size.";
return Status::InvalidContainerData;
}
const uint8_t* block_end = src + protected_bytes;
cur_iv.assign(block_end - kAesBlockSize, block_end);
}
// 'cbcs' uses constant-IV.
src += protected_bytes;
dest += protected_bytes;
total_size -= protected_bytes;
}
if (total_size != 0) {
LOG(ERROR) << "Extra remaining data after subsample handling";
return Status::InvalidContainerData;
}
}
return Status::Success;
}
FFmpegEncodedFrame::FFmpegEncodedFrame(AVPacket* pkt, size_t stream_id,
double offset, double pts, double dts,
double duration, bool is_key_frame)
: BaseFrame(pts, dts, duration, is_key_frame),
stream_id_(stream_id),
timestamp_offset_(offset) {
av_packet_move_ref(&packet_, pkt);
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/media/stream.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_STREAM_H_
#define SHAKA_EMBEDDED_MEDIA_STREAM_H_
#include "src/media/base_frame.h"
#include "src/media/frame_buffer.h"
#include "src/util/macros.h"
namespace shaka {
namespace media {
/**
* This maintains two buffers of media frames. One buffer (the demuxed buffer)
* contains demuxed, encoded media frames. The other (the decoded buffer)
* contains decoded, full media frames.
*
* The demuxed buffer defines the buffered ranges in MSE. This buffer is the
* larger of the two and the data will likely live longer. The data will only
* be freed when we run out of memory or if JavaScript tells us to through a
* call to remove().
*
* The decoded buffered is smaller and only contains frames slightly ahead of
* the playhead. When the playhead passes a frame, it is dropped.
*
* This class handles reordering frames as needed and controls the lifetime of
* the frames. Other classes will insert data into this object.
*
* This class is fully thread-safe. It is fine to append frames from background
* threads and remove them from others.
*/
class Stream {
public:
Stream();
~Stream();
NON_COPYABLE_OR_MOVABLE_TYPE(Stream);
/** @return The amount of time decoded ahead of the given time. */
double DecodedAheadOf(double time) const;
/** @returns The buffered ranges for the Stream. */
BufferedRanges GetBufferedRanges() const {
return demuxed_frames_.GetBufferedRanges();
}
FrameBuffer* GetDemuxedFrames() {
return &demuxed_frames_;
}
const FrameBuffer* GetDemuxedFrames() const {
return &demuxed_frames_;
}
FrameBuffer* GetDecodedFrames() {
return &decoded_frames_;
}
const FrameBuffer* GetDecodedFrames() const {
return &decoded_frames_;
}
private:
FrameBuffer demuxed_frames_;
FrameBuffer decoded_frames_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_STREAM_H_
<file_sep>/shaka/test/src/util/dynamic_buffer_unittest.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/util/dynamic_buffer.h"
#include <gtest/gtest.h>
namespace shaka {
namespace util {
namespace {
const char kData1[] = "First Data";
const char kData2[] = "Second\0Data";
// Number of characters in string (not counting trailing '\0').
const size_t kData1Size = sizeof(kData1) - 1;
const size_t kData2Size = sizeof(kData2) - 1;
} // namespace
TEST(DynamicBufferTest, Size) {
DynamicBuffer buf;
buf.AppendCopy(kData1, kData1Size);
buf.AppendCopy(kData2, kData2Size);
EXPECT_EQ(kData1Size + kData2Size, buf.Size());
buf.AppendCopy(kData1, kData1Size);
EXPECT_EQ(kData1Size * 2 + kData2Size, buf.Size());
}
TEST(DynamicBufferTest, Clear) {
DynamicBuffer buf;
buf.AppendCopy(kData1, kData1Size);
buf.AppendCopy(kData2, kData2Size);
EXPECT_EQ(kData1Size + kData2Size, buf.Size());
buf.Clear();
EXPECT_EQ(0u, buf.Size());
EXPECT_EQ("", buf.CreateString());
}
TEST(DynamicBufferTest, CreateString) {
DynamicBuffer buf;
buf.AppendCopy(kData1, kData1Size);
buf.AppendCopy(kData2, kData2Size);
std::string expected(kData1, kData1Size);
expected.append(kData2, kData2Size);
EXPECT_EQ(expected, buf.CreateString());
}
TEST(DynamicBufferTest, CopyDataTo) {
DynamicBuffer buf;
buf.AppendCopy(kData1, kData1Size);
buf.AppendCopy(kData2, kData2Size);
std::vector<uint8_t> expected(kData1, kData1 + kData1Size);
expected.insert(expected.end(), kData2, kData2 + kData2Size);
std::vector<uint8_t> actual;
actual.resize(buf.Size());
buf.CopyDataTo(&actual[0], actual.size());
EXPECT_EQ(expected, actual);
}
} // namespace util
} // namespace shaka
<file_sep>/shaka/include/shaka/eme/implementation_registry.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_EME_IMPLEMENTATION_REGISTRY_H_
#define SHAKA_EMBEDDED_EME_IMPLEMENTATION_REGISTRY_H_
#include <string>
#include "../macros.h"
namespace shaka {
namespace eme {
class ImplementationFactory;
/**
* Defines a registry for implementations of EME. During system startup all
* implementations should be registered with this type to make them available.
*
* @ingroup eme
*/
class SHAKA_EXPORT ImplementationRegistry final {
public:
/**
* Adds an EME implementation to the registry. The caller retains ownership
* of the pointer and it must remain valid for the entire lifetime of the
* program.
*/
static void AddImplementation(const std::string& key_system,
ImplementationFactory* factory);
/** @returns The implementation of the given key system, or nullptr. */
static ImplementationFactory* GetImplementation(
const std::string& key_system);
private:
ImplementationRegistry();
};
} // namespace eme
} // namespace shaka
#endif // SHAKA_EMBEDDED_EME_IMPLEMENTATION_REGISTRY_H_
<file_sep>/shaka/src/media/ffmpeg_encoded_frame.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_FFMPEG_ENCODED_FRAME_H_
#define SHAKA_EMBEDDED_MEDIA_FFMPEG_ENCODED_FRAME_H_
extern "C" {
#include <libavformat/avformat.h>
}
#include <memory>
#include "src/media/base_frame.h"
#include "src/media/types.h"
#include "src/util/macros.h"
namespace shaka {
namespace eme {
class Implementation;
} // namespace eme
namespace media {
/** This defines a single encoded media frame. */
class FFmpegEncodedFrame final : public BaseFrame {
public:
~FFmpegEncodedFrame() override;
static FFmpegEncodedFrame* MakeFrame(AVPacket* pkt, AVStream* stream,
size_t stream_id,
double timestamp_offset);
NON_COPYABLE_OR_MOVABLE_TYPE(FFmpegEncodedFrame);
FrameType frame_type() const override;
size_t EstimateSize() const override;
const AVPacket* raw_packet() const {
return &packet_;
}
size_t stream_id() const {
return stream_id_;
}
double timestamp_offset() const {
return timestamp_offset_;
}
/** @return Whether this frame is encrypted. */
bool is_encrypted() const;
/**
* Attempts to decrypt the frame into the given packet by the given CDM. The
* given packet should already been initialized with a buffer large enough to
* hold the current frame.
*/
Status Decrypt(eme::Implementation* cdm, AVPacket* dest_packet) const;
private:
FFmpegEncodedFrame(AVPacket* pkt, size_t stream_id, double offset, double pts,
double dts, double duration, bool is_key_frame);
AVPacket packet_;
const size_t stream_id_;
const double timestamp_offset_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_FFMPEG_ENCODED_FRAME_H_
<file_sep>/shaka/test/src/media/frame_buffer_unittest.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/frame_buffer.h"
#include <math.h>
#include <gtest/gtest.h>
namespace shaka {
namespace media {
namespace {
constexpr const bool kPtsOrder = false;
constexpr const bool kDtsOrder = true;
std::unique_ptr<BaseFrame> MakeFrame(double start, double end,
bool is_key_frame = true) {
BaseFrame* ret = new BaseFrame(start, start, end - start, is_key_frame);
return std::unique_ptr<BaseFrame>(ret);
}
} // namespace
TEST(FrameBufferTest, CreatesFirstRange) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
auto ranges = buffer.GetBufferedRanges();
ASSERT_EQ(1u, ranges.size());
EXPECT_EQ(0, ranges[0].start);
EXPECT_EQ(10, ranges[0].end);
}
TEST(FrameBufferTest, CreatesNewRangeAtStart) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(20, 30));
// Should create a new range before the original.
buffer.AppendFrame(MakeFrame(0, 10));
auto ranges = buffer.GetBufferedRanges();
ASSERT_EQ(2u, ranges.size());
EXPECT_EQ(0, ranges[0].start);
EXPECT_EQ(10, ranges[0].end);
EXPECT_EQ(20, ranges[1].start);
EXPECT_EQ(30, ranges[1].end);
}
TEST(FrameBufferTest, CreatesNewRangeAtEnd) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
// Should create a new range after the original.
buffer.AppendFrame(MakeFrame(20, 30));
auto ranges = buffer.GetBufferedRanges();
ASSERT_EQ(2u, ranges.size());
EXPECT_EQ(0, ranges[0].start);
EXPECT_EQ(10, ranges[0].end);
EXPECT_EQ(20, ranges[1].start);
EXPECT_EQ(30, ranges[1].end);
}
TEST(FrameBufferTest, CreatesNewRangeInMiddle) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
buffer.AppendFrame(MakeFrame(40, 50));
ASSERT_EQ(2u, buffer.GetBufferedRanges().size());
// Should create a new range between the two existing ranges.
buffer.AppendFrame(MakeFrame(20, 30));
auto ranges = buffer.GetBufferedRanges();
ASSERT_EQ(3u, ranges.size());
EXPECT_EQ(0, ranges[0].start);
EXPECT_EQ(10, ranges[0].end);
EXPECT_EQ(20, ranges[1].start);
EXPECT_EQ(30, ranges[1].end);
EXPECT_EQ(40, ranges[2].start);
EXPECT_EQ(50, ranges[2].end);
}
TEST(FrameBufferTest, AddsToEndOfExistingRange) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
// Should add to the exiting range.
buffer.AppendFrame(MakeFrame(10, 20));
auto ranges = buffer.GetBufferedRanges();
ASSERT_EQ(1u, ranges.size());
EXPECT_EQ(0, ranges[0].start);
EXPECT_EQ(20, ranges[0].end);
}
TEST(FrameBufferTest, AddsToMiddleOfExistingRange) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
buffer.AppendFrame(MakeFrame(10, 20));
// Should insert the frame in between the existing two. The frames should be
// in pts order, even though they are overlapping.
buffer.AppendFrame(MakeFrame(5, 10));
auto ranges = buffer.GetBufferedRanges();
ASSERT_EQ(1u, ranges.size());
EXPECT_EQ(0, ranges[0].start);
EXPECT_EQ(20, ranges[0].end);
}
TEST(FrameBufferTest, AddsToBeginningOfExistingRange) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(10, 20));
// Should add to the exiting range.
buffer.AppendFrame(MakeFrame(0, 10));
auto ranges = buffer.GetBufferedRanges();
ASSERT_EQ(1u, ranges.size());
EXPECT_EQ(0, ranges[0].start);
EXPECT_EQ(20, ranges[0].end);
}
TEST(FrameBufferTest, StillAddsToExistingWithGap) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
// Should add to the exiting range.
buffer.AppendFrame(MakeFrame(10.01, 20));
auto ranges = buffer.GetBufferedRanges();
ASSERT_EQ(1u, ranges.size());
EXPECT_EQ(0, ranges[0].start);
EXPECT_EQ(20, ranges[0].end);
}
TEST(FrameBufferTest, CombinesOverlappingRanges) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
buffer.AppendFrame(MakeFrame(20, 30));
ASSERT_EQ(2u, buffer.GetBufferedRanges().size());
// Should result in combining the two ranges.
buffer.AppendFrame(MakeFrame(10, 20));
auto ranges = buffer.GetBufferedRanges();
ASSERT_EQ(1u, ranges.size());
EXPECT_EQ(0, ranges[0].start);
EXPECT_EQ(30, ranges[0].end);
}
TEST(FrameBufferTest, CombinesRangesWithSmallGap) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
buffer.AppendFrame(MakeFrame(20, 30));
ASSERT_EQ(2u, buffer.GetBufferedRanges().size());
// Should result in combining the two ranges.
buffer.AppendFrame(MakeFrame(10, 19.99));
auto ranges = buffer.GetBufferedRanges();
ASSERT_EQ(1u, ranges.size());
EXPECT_EQ(0, ranges[0].start);
EXPECT_EQ(30, ranges[0].end);
}
TEST(FrameBufferTest, UsesPtsForBufferedRanges) {
// This should use the PTS of the frames for buffered ranges, even when we
// are sorted on DTS. This means that the first frame in the range may not
// define the time ranges for it.
FrameBuffer buffer(kDtsOrder);
auto makeFrame = [](double dts, double pts) {
return std::unique_ptr<BaseFrame>(new BaseFrame(pts, dts, 1, true));
};
// Range 1: DTS (0, 1, 2), PTS (1, 0, 2)
buffer.AppendFrame(makeFrame(0, 1));
buffer.AppendFrame(makeFrame(1, 0));
buffer.AppendFrame(makeFrame(2, 2));
// Range 2: DTS (10, 11, 12), PTS (10, 12, 11)
buffer.AppendFrame(makeFrame(10, 10));
buffer.AppendFrame(makeFrame(11, 12));
buffer.AppendFrame(makeFrame(12, 11));
auto buffered = buffer.GetBufferedRanges();
ASSERT_EQ(2u, buffered.size());
EXPECT_EQ(0, buffered[0].start);
EXPECT_EQ(3, buffered[0].end);
EXPECT_EQ(10, buffered[1].start);
EXPECT_EQ(13, buffered[1].end);
}
TEST(FrameBufferTest, FramesBetween) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
buffer.AppendFrame(MakeFrame(10, 20));
buffer.AppendFrame(MakeFrame(20, 30));
buffer.AppendFrame(MakeFrame(30, 40));
//
buffer.AppendFrame(MakeFrame(100, 110));
buffer.AppendFrame(MakeFrame(110, 120));
buffer.AppendFrame(MakeFrame(120, 130));
ASSERT_EQ(2u, buffer.GetBufferedRanges().size());
EXPECT_EQ(0, buffer.FramesBetween(0, 0));
EXPECT_EQ(0, buffer.FramesBetween(0, 10));
EXPECT_EQ(0, buffer.FramesBetween(5, 10));
EXPECT_EQ(2, buffer.FramesBetween(0, 30));
EXPECT_EQ(3, buffer.FramesBetween(0, 100));
EXPECT_EQ(4, buffer.FramesBetween(0, 105));
EXPECT_EQ(4, buffer.FramesBetween(0, 110));
EXPECT_EQ(2, buffer.FramesBetween(5, 30));
EXPECT_EQ(2, buffer.FramesBetween(100, 200));
}
TEST(FrameBufferTest, GetKeyFrameBefore_FindsFrameBefore) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
buffer.AppendFrame(MakeFrame(10, 20, false));
buffer.AppendFrame(MakeFrame(20, 30, false));
ASSERT_EQ(1u, buffer.GetBufferedRanges().size());
const BaseFrame* frame = buffer.GetKeyFrameBefore(15).get();
ASSERT_NE(nullptr, frame);
EXPECT_EQ(0, frame->pts);
}
TEST(FrameBufferTest, GetKeyFrameBefore_FindsExactFrame) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
buffer.AppendFrame(MakeFrame(10, 20));
buffer.AppendFrame(MakeFrame(20, 30));
ASSERT_EQ(1u, buffer.GetBufferedRanges().size());
const BaseFrame* frame = buffer.GetKeyFrameBefore(10).get();
ASSERT_NE(nullptr, frame);
EXPECT_EQ(10, frame->pts);
}
TEST(FrameBufferTest, GetKeyFrameBefore_WontReturnFutureFrames) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(10, 20));
buffer.AppendFrame(MakeFrame(20, 30));
buffer.AppendFrame(MakeFrame(30, 40));
ASSERT_EQ(1u, buffer.GetBufferedRanges().size());
const BaseFrame* frame = buffer.GetKeyFrameBefore(0).get();
EXPECT_EQ(nullptr, frame);
}
TEST(FrameBufferTest, GetFrameAfter_GetsNext) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
buffer.AppendFrame(MakeFrame(10, 20));
const BaseFrame* frame = buffer.GetFrameAfter(0).get();
ASSERT_NE(nullptr, frame);
EXPECT_EQ(10, frame->pts);
}
TEST(FrameBufferTest, GetFrameAfter_GetsNextAcrossRanges) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 2));
buffer.AppendFrame(MakeFrame(2, 3));
buffer.AppendFrame(MakeFrame(10, 12));
buffer.AppendFrame(MakeFrame(12, 14));
ASSERT_EQ(2u, buffer.GetBufferedRanges().size());
const BaseFrame* frame = buffer.GetFrameAfter(2).get();
ASSERT_NE(nullptr, frame);
EXPECT_EQ(10, frame->pts);
}
TEST(FrameBufferTest, GetFrameAfter_ReturnsNull) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
ASSERT_EQ(nullptr, buffer.GetFrameAfter(0).get());
ASSERT_EQ(nullptr, buffer.GetFrameAfter(4).get());
ASSERT_EQ(nullptr, buffer.GetFrameAfter(10).get());
ASSERT_EQ(nullptr, buffer.GetFrameAfter(12).get());
}
TEST(FrameBufferTest, GetFrameNear_NextFrame) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(10, 10));
const BaseFrame* frame = buffer.GetFrameNear(0).get();
ASSERT_NE(nullptr, frame);
EXPECT_EQ(10, frame->pts);
}
TEST(FrameBufferTest, GetFrameNear_NextFrameBetweenRanges) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 0));
buffer.AppendFrame(MakeFrame(10, 10));
ASSERT_EQ(2u, buffer.GetBufferedRanges().size());
const BaseFrame* frame = buffer.GetFrameNear(7).get();
ASSERT_NE(nullptr, frame);
EXPECT_EQ(10, frame->pts);
}
TEST(FrameBufferTest, GetFrameNear_PastTheEnd) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
buffer.AppendFrame(MakeFrame(10, 10));
const BaseFrame* frame = buffer.GetFrameNear(12).get();
ASSERT_NE(nullptr, frame);
EXPECT_EQ(10, frame->pts);
}
TEST(FrameBufferTest, GetFrameNear_InPastBetweenRanges) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 1));
buffer.AppendFrame(MakeFrame(1, 2));
buffer.AppendFrame(MakeFrame(10, 11));
buffer.AppendFrame(MakeFrame(11, 12));
ASSERT_EQ(2u, buffer.GetBufferedRanges().size());
const BaseFrame* frame = buffer.GetFrameNear(3).get();
ASSERT_NE(nullptr, frame);
EXPECT_EQ(1, frame->pts);
}
TEST(FrameBufferTest, GetFrameNear_GetsNearest) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 10));
buffer.AppendFrame(MakeFrame(10.01, 10));
ASSERT_EQ(1u, buffer.GetBufferedRanges().size());
const BaseFrame* frame = buffer.GetFrameNear(10.001).get();
ASSERT_NE(nullptr, frame);
EXPECT_EQ(0, frame->pts);
frame = buffer.GetFrameNear(10.009).get();
ASSERT_NE(nullptr, frame);
EXPECT_EQ(10.01, frame->pts);
}
TEST(FrameBufferTest, GetFrameNear_ReturnsNull) {
// Since it returns the nearest frame always, the only case it returns null is
// when there are no frames.
FrameBuffer buffer(kPtsOrder);
const BaseFrame* frame = buffer.GetFrameNear(0).get();
ASSERT_EQ(nullptr, frame);
}
TEST(FrameBufferTest, Remove_RemovesWholeRange) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 1));
buffer.AppendFrame(MakeFrame(1, 2));
buffer.AppendFrame(MakeFrame(2, 3));
//
buffer.AppendFrame(MakeFrame(6, 7));
buffer.AppendFrame(MakeFrame(7, 8));
ASSERT_EQ(2u, buffer.GetBufferedRanges().size());
buffer.Remove(6, 8);
EXPECT_EQ(1u, buffer.GetBufferedRanges().size());
EXPECT_EQ(nullptr, buffer.GetFrameAfter(3).get());
}
TEST(FrameBufferTest, Remove_SplitsRanges) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 1));
buffer.AppendFrame(MakeFrame(1, 2));
buffer.AppendFrame(MakeFrame(2, 3));
buffer.AppendFrame(MakeFrame(3, 4));
buffer.AppendFrame(MakeFrame(4, 5));
ASSERT_EQ(1u, buffer.GetBufferedRanges().size());
buffer.Remove(2, 4);
auto buffered = buffer.GetBufferedRanges();
ASSERT_EQ(2u, buffered.size());
EXPECT_EQ(0, buffered[0].start);
EXPECT_EQ(2, buffered[0].end);
EXPECT_EQ(4, buffered[1].start);
EXPECT_EQ(5, buffered[1].end);
const BaseFrame* frame = buffer.GetFrameAfter(1).get();
ASSERT_NE(nullptr, frame);
EXPECT_EQ(4, frame->pts);
}
TEST(FrameBufferTest, Remove_RemovesPartOfRange) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 1));
buffer.AppendFrame(MakeFrame(1, 2));
buffer.AppendFrame(MakeFrame(2, 3));
buffer.AppendFrame(MakeFrame(3, 4));
buffer.AppendFrame(MakeFrame(4, 5));
ASSERT_EQ(1u, buffer.GetBufferedRanges().size());
buffer.Remove(3, 5);
auto buffered = buffer.GetBufferedRanges();
ASSERT_EQ(1u, buffered.size());
EXPECT_EQ(0, buffered[0].start);
EXPECT_EQ(3, buffered[0].end);
EXPECT_EQ(nullptr, buffer.GetFrameAfter(2).get());
}
TEST(FrameBufferTest, Remove_RemovesMultipleRanges) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 1));
buffer.AppendFrame(MakeFrame(1, 2));
buffer.AppendFrame(MakeFrame(2, 3));
//
buffer.AppendFrame(MakeFrame(5, 6));
buffer.AppendFrame(MakeFrame(6, 7));
//
buffer.AppendFrame(MakeFrame(10, 11));
buffer.AppendFrame(MakeFrame(11, 12));
//
buffer.AppendFrame(MakeFrame(15, 16));
buffer.AppendFrame(MakeFrame(16, 17));
buffer.AppendFrame(MakeFrame(17, 18));
ASSERT_EQ(4u, buffer.GetBufferedRanges().size());
buffer.Remove(0, 7);
auto buffered = buffer.GetBufferedRanges();
ASSERT_EQ(2u, buffered.size());
EXPECT_EQ(10, buffered[0].start);
EXPECT_EQ(12, buffered[0].end);
EXPECT_EQ(15, buffered[1].start);
EXPECT_EQ(18, buffered[1].end);
}
TEST(FrameBufferTest, Remove_RemovesAllRanges) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 1));
buffer.AppendFrame(MakeFrame(1, 2));
buffer.AppendFrame(MakeFrame(2, 3));
//
buffer.AppendFrame(MakeFrame(5, 6));
buffer.AppendFrame(MakeFrame(6, 7));
ASSERT_EQ(2u, buffer.GetBufferedRanges().size());
buffer.Remove(0, 7);
EXPECT_EQ(0u, buffer.GetBufferedRanges().size());
}
TEST(FrameBufferTest, Remove_RemovesNothing) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 1));
buffer.AppendFrame(MakeFrame(1, 2));
buffer.AppendFrame(MakeFrame(2, 3));
//
buffer.AppendFrame(MakeFrame(5, 6));
buffer.AppendFrame(MakeFrame(6, 7));
ASSERT_EQ(2u, buffer.GetBufferedRanges().size());
buffer.Remove(10, 20);
auto buffered = buffer.GetBufferedRanges();
ASSERT_EQ(2u, buffered.size());
EXPECT_EQ(0, buffered[0].start);
EXPECT_EQ(3, buffered[0].end);
EXPECT_EQ(5, buffered[1].start);
EXPECT_EQ(7, buffered[1].end);
}
TEST(FrameBufferTest, Remove_SupportsInfinity) {
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(2, 3));
buffer.AppendFrame(MakeFrame(3, 4));
//
buffer.AppendFrame(MakeFrame(6, 7));
buffer.AppendFrame(MakeFrame(7, 8));
ASSERT_EQ(2u, buffer.GetBufferedRanges().size());
buffer.Remove(0, HUGE_VAL /* Infinity */);
EXPECT_EQ(0u, buffer.GetBufferedRanges().size());
}
TEST(FrameBufferTest, Remove_RemovesUntilKeyframe) {
// When removing frames, it should remove frames past the given stop until the
// next keyframe; see step 3.4 of the "Coded Frame Removal Algorithm" in MSE:
// https://w3c.github.io/media-source/#sourcebuffer-coded-frame-removal
FrameBuffer buffer(kPtsOrder);
buffer.AppendFrame(MakeFrame(0, 1));
buffer.AppendFrame(MakeFrame(1, 2));
buffer.AppendFrame(MakeFrame(2, 3, false));
buffer.AppendFrame(MakeFrame(3, 4, false));
buffer.AppendFrame(MakeFrame(6, 7));
buffer.AppendFrame(MakeFrame(7, 8));
ASSERT_EQ(2u, buffer.GetBufferedRanges().size());
buffer.Remove(0, 2); // Should actually remove [0, 4].
auto buffered = buffer.GetBufferedRanges();
ASSERT_EQ(1u, buffered.size());
EXPECT_EQ(6, buffered[0].start);
EXPECT_EQ(8, buffered[0].end);
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/js/dom/container_node.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/dom/container_node.h"
#include "src/js/dom/document.h"
#include "src/js/dom/element.h"
#include "src/js/js_error.h"
#include "src/memory/heap_tracer.h"
namespace shaka {
namespace js {
namespace dom {
namespace {
RefPtr<Element> ToElement(RefPtr<Node> node) {
if (!node->is_element())
return nullptr;
return static_cast<Element*>(node.get());
}
} // namespace
ContainerNode::ContainerNode(NodeType type, RefPtr<Document> document)
: Node(type, document) {}
// \cond Doxygen_Skip
ContainerNode::~ContainerNode() {}
// \endcond Doxygen_Skip
std::vector<RefPtr<Element>> ContainerNode::GetElementsByTagName(
const std::string& name) const {
std::vector<RefPtr<Element>> ret;
for (auto& child : child_nodes()) {
RefPtr<Element> elem = ToElement(child);
if (elem) {
if (elem->tag_name() == name) {
ret.push_back(elem);
}
auto temp = elem->GetElementsByTagName(name);
ret.insert(ret.end(), temp.begin(), temp.end());
}
}
return ret;
}
ContainerNodeFactory::ContainerNodeFactory() {
AddMemberFunction("getElementsByTagName", &Element::GetElementsByTagName);
NotImplemented("children");
NotImplemented("firstElementChild");
NotImplemented("lastElementChild");
NotImplemented("childElementCount");
NotImplemented("getElementsByTagNameNS");
NotImplemented("getElementsByClassName");
NotImplemented("prepend");
NotImplemented("append");
NotImplemented("querySelector");
NotImplemented("querySelectorAll");
}
} // namespace dom
} // namespace js
} // namespace shaka
<file_sep>/shaka/src/js/events/media_encrypted_event.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/events/media_encrypted_event.h"
namespace shaka {
namespace js {
namespace events {
MediaEncryptedEvent::MediaEncryptedEvent(
EventType event_type, eme::MediaKeyInitDataType init_data_type,
ByteBuffer init_data)
: MediaEncryptedEvent(to_string(event_type), init_data_type,
std::move(init_data)) {}
// \cond Doxygen_Skip
MediaEncryptedEvent::~MediaEncryptedEvent() {}
// \endcond Doxygen_Skip
void MediaEncryptedEvent::Trace(memory::HeapTracer* tracer) const {
Event::Trace(tracer);
tracer->Trace(&init_data);
}
MediaEncryptedEvent::MediaEncryptedEvent(
const std::string& event_type, eme::MediaKeyInitDataType init_data_type,
ByteBuffer init_data)
: Event(event_type),
init_data_type(init_data_type),
init_data(std::move(init_data)) {}
MediaEncryptedEventFactory::MediaEncryptedEventFactory() {
AddReadOnlyProperty("initDataType", &MediaEncryptedEvent::init_data_type);
AddReadOnlyProperty("initData", &MediaEncryptedEvent::init_data);
}
} // namespace events
} // namespace js
} // namespace shaka
<file_sep>/shaka/src/media/frame_converter.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_FRAME_CONVERTER_H_
#define SHAKA_EMBEDDED_MEDIA_FRAME_CONVERTER_H_
extern "C" {
#ifdef HAS_SWSCALE
# include <libswscale/swscale.h>
#endif
#include <libavutil/frame.h>
#include <libavutil/imgutils.h>
}
#include "src/util/macros.h"
namespace shaka {
namespace media {
/**
* A class that converts a frame from one pixel format to another.
* Acts as a wrapper over swscale.
*/
class FrameConverter {
public:
FrameConverter();
~FrameConverter();
NON_COPYABLE_OR_MOVABLE_TYPE(FrameConverter);
/**
* Converts a frame to the given pixel format, using swscale. The returned
* data is only valid until this method is called again or when this object
* is destroyed.
*
* @param frame The frame to be converted.
* @param data A pointer that will be set to point to the new data of the
* converted frame if conversion is successful.
* @param linesize A pointer that will be set to point to the new linesizes of
* the converted frame if conversion is successful.
* @param desired_pixel_format The pixel format to convert to.
* @return True if the conversion was successful, false otherwise.
*/
bool ConvertFrame(const AVFrame* frame, uint8_t* const** data,
const int** linesize, AVPixelFormat desired_pixel_format);
private:
AVFrame* cpu_frame_;
#ifdef HAS_SWSCALE
SwsContext* sws_ctx_ = nullptr;
uint8_t* convert_frame_data_[4] = {nullptr, nullptr, nullptr, nullptr};
AVPixelFormat convert_pixel_format_ = AV_PIX_FMT_NONE;
int convert_frame_linesize_[4] = {0, 0, 0, 0};
int convert_frame_width_ = 0, convert_frame_height_ = 0;
#endif
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_FRAME_CONVERTER_H_
<file_sep>/shaka/test/src/memory/object_tracker_unittest.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/memory/object_tracker.h"
#include <gtest/gtest.h>
#include <functional>
#include "src/core/ref_ptr.h"
#include "src/mapping/backing_object.h"
#include "src/util/utils.h"
namespace shaka {
namespace memory {
namespace {
class TestObject : public BackingObject {
public:
static std::string name() {
return "TestObject";
}
TestObject(bool* is_free) : is_free_(is_free) {
*is_free = false;
}
~TestObject() override {
*is_free_ = true;
if (on_destroy)
on_destroy();
}
std::function<void()> on_destroy;
private:
BackingObjectFactoryBase* factory() const override {
return nullptr;
}
bool* is_free_;
};
} // namespace
class ObjectTrackerTest : public testing::Test {
protected:
void ExpectNonZeroRefs(const Traceable* obj) {
EXPECT_TRUE(util::contains(tracker.GetAliveObjects(), obj));
}
void ExpectZeroRefs(const Traceable* obj) {
EXPECT_FALSE(util::contains(tracker.GetAliveObjects(), obj));
EXPECT_TRUE(util::contains(tracker.GetAllObjects(), obj));
}
void ExpectMissing(const Traceable* obj) {
EXPECT_FALSE(util::contains(tracker.GetAllObjects(), obj));
}
ObjectTracker::UnsetForTesting unset_;
ObjectTracker tracker;
};
TEST_F(ObjectTrackerTest, BasicFlow) {
bool is_free = false;
TestObject* obj = new TestObject(&is_free);
ASSERT_TRUE(obj);
ExpectZeroRefs(obj);
ASSERT_FALSE(is_free);
{
// Note, this will not free the object even though it is the last reference.
RefPtr<TestObject> ref(obj);
ExpectNonZeroRefs(obj);
}
ASSERT_FALSE(is_free);
ExpectZeroRefs(obj);
// The tracker thinks the object is dead because it has a zero ref count. But
// it will not be freed because it is in |js_alive|.
std::unordered_set<const Traceable*> js_alive = {obj};
tracker.FreeDeadObjects(js_alive);
ExpectZeroRefs(obj);
ASSERT_FALSE(is_free);
// Perform a GC where the object is dead.
ExpectZeroRefs(obj);
js_alive.clear();
tracker.FreeDeadObjects(js_alive);
// The pointer is invalid at this point.
ExpectMissing(obj);
EXPECT_TRUE(is_free);
}
TEST_F(ObjectTrackerTest, Dispose) {
bool is_free1, is_free2;
TestObject* obj1 = new TestObject(&is_free1);
TestObject* obj2 = new TestObject(&is_free2);
tracker.AddRef(obj1);
ExpectNonZeroRefs(obj1);
ExpectZeroRefs(obj2);
tracker.Dispose();
ExpectMissing(obj1);
ExpectMissing(obj2);
EXPECT_TRUE(is_free1);
EXPECT_TRUE(is_free2);
}
TEST_F(ObjectTrackerTest, CanCreateObjectsInDispose) {
bool is_free1, is_free2 = false, is_free3;
TestObject* obj1 = new TestObject(&is_free1);
obj1->on_destroy = [&]() {
TestObject* obj2 = new TestObject(&is_free2);
obj2->on_destroy = [&]() { new TestObject(&is_free3); };
};
tracker.Dispose();
EXPECT_TRUE(is_free1);
EXPECT_TRUE(is_free2);
EXPECT_TRUE(is_free3);
}
TEST_F(ObjectTrackerTest, RefCounts) {
bool is_free1, is_free2;
TestObject* obj1 = new TestObject(&is_free1);
TestObject* obj2 = new TestObject(&is_free2);
// Basic flow.
ExpectZeroRefs(obj1);
tracker.AddRef(obj1);
ExpectNonZeroRefs(obj1);
tracker.RemoveRef(obj1);
ExpectZeroRefs(obj1);
// Two objects are independent.
tracker.AddRef(obj1);
tracker.AddRef(obj2);
ExpectNonZeroRefs(obj1);
ExpectNonZeroRefs(obj2);
tracker.RemoveRef(obj2);
ExpectNonZeroRefs(obj1);
ExpectZeroRefs(obj2);
tracker.RemoveRef(obj1);
ExpectZeroRefs(obj1);
ExpectZeroRefs(obj2);
// Multiple ref counts.
tracker.AddRef(obj1);
tracker.AddRef(obj2);
tracker.AddRef(obj2);
tracker.AddRef(obj1);
tracker.AddRef(obj1);
tracker.AddRef(obj2);
ExpectNonZeroRefs(obj1);
ExpectNonZeroRefs(obj2);
tracker.RemoveRef(obj1);
tracker.RemoveRef(obj1);
ExpectNonZeroRefs(obj1);
ExpectNonZeroRefs(obj2);
tracker.RemoveRef(obj2); // obj1 = 1, obj2 = 2
ExpectNonZeroRefs(obj1);
ExpectNonZeroRefs(obj2);
tracker.AddRef(obj1);
tracker.RemoveRef(obj2);
tracker.RemoveRef(obj2); // obj1 = 2, obj2 = 0
ExpectNonZeroRefs(obj1);
ExpectZeroRefs(obj2);
tracker.RemoveRef(obj1);
tracker.RemoveRef(obj1);
ExpectZeroRefs(obj1);
ExpectZeroRefs(obj2);
EXPECT_FALSE(is_free1);
EXPECT_FALSE(is_free2);
tracker.Dispose();
}
} // namespace memory
} // namespace shaka
<file_sep>/shaka/src/public/player.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "shaka/player.h"
#include "shaka/version.h"
#include "src/core/js_manager_impl.h"
#include "src/debug/thread_event.h"
#include "src/js/manifest.h"
#include "src/js/mse/video_element.h"
#include "src/js/player_externs.h"
#include "src/js/stats.h"
#include "src/js/track.h"
#include "src/mapping/any.h"
#include "src/mapping/convert_js.h"
#include "src/mapping/js_engine.h"
#include "src/mapping/js_utils.h"
#include "src/mapping/js_wrappers.h"
#include "src/mapping/struct.h"
#include "src/util/utils.h"
// Declared in version.h by generated code in //shaka/tools/version.py.
SHAKA_EXPORT extern "C" const char* GetShakaEmbeddedVersion() {
return SHAKA_VERSION_STR;
}
namespace shaka {
namespace {
/**
* A helper class that converts a number to the argument to load(). This
* exists because we need to convert the C++ NaN into a JavaScript undefined.
* This class allows the code below to be more general and avoids having to
* have a special case for converting the argument for load().
*/
class LoadHelper : public GenericConverter {
public:
explicit LoadHelper(double value) : value_(value) {}
bool TryConvert(Handle<JsValue> /* value */) override {
LOG(FATAL) << "Not reached";
}
ReturnVal<JsValue> ToJsValue() const override {
return !isnan(value_) ? ::shaka::ToJsValue(value_) : JsUndefined();
}
private:
const double value_;
};
/**
* A helper that converts a JavaScript value into the given return type as a
* variant. If the return type is |void|, this ignores the value.
*/
template <typename Ret>
struct Converter {
using variant_type = typename AsyncResults<Ret>::variant_type;
using future_type = std::shared_future<variant_type>;
static variant_type Convert(const std::string& name, Handle<JsValue> result) {
Ret ret;
if (!FromJsValue(result, &ret)) {
return Error(ErrorType::NonShakaError,
"Invalid return value from " + name + "().");
}
return ret;
}
};
template <>
struct Converter<void> {
using variant_type = AsyncResults<void>::variant_type;
using future_type = std::shared_future<variant_type>;
static variant_type Convert(const std::string& /* name */,
Handle<JsValue> /* result */) {
return monostate();
}
};
Error ConvertError(Handle<JsValue> except) {
if (!IsObject(except))
return Error(ErrorType::NonShakaError, ConvertToString(except));
LocalVar<JsObject> obj = UnsafeJsCast<JsObject>(except);
LocalVar<JsValue> message_member = GetMemberRaw(obj, "message");
// Rather than checking for the type of the exception, assume that if it has
// a 'name' field, then it is an exception.
LocalVar<JsValue> name_member = GetMemberRaw(obj, "name");
if (!IsNullOrUndefined(name_member)) {
const std::string message =
ConvertToString(name_member) + ": " + ConvertToString(message_member);
return Error(ErrorType::NonShakaError, message);
}
LocalVar<JsValue> code = GetMemberRaw(obj, "code");
LocalVar<JsValue> category = GetMemberRaw(obj, "category");
if (GetValueType(code) != JSValueType::Number ||
GetValueType(category) != JSValueType::Number) {
return Error(ErrorType::NonShakaError, ConvertToString(except));
}
LocalVar<JsValue> severity_val = GetMemberRaw(obj, "severity");
int severity = 0;
if (GetValueType(severity_val) == JSValueType::Number)
severity = static_cast<int>(NumberFromValue(severity_val));
std::string message;
if (IsNullOrUndefined(message_member)) {
message = "Shaka Error, Category: " + ConvertToString(category) +
", Code: " + ConvertToString(code);
} else {
message = ConvertToString(message_member);
}
return Error(static_cast<int>(NumberFromValue(category)),
static_cast<int>(NumberFromValue(code)), severity, message);
}
Converter<void>::variant_type CallMemberFunction(Handle<JsObject> that,
const std::string& name,
int argc,
LocalVar<JsValue>* argv,
LocalVar<JsValue>* result) {
LocalVar<JsValue> member = GetMemberRaw(that, name);
if (GetValueType(member) != JSValueType::Function) {
return Error(ErrorType::BadMember,
"The member '" + name + "' is not a function.");
}
LocalVar<JsValue> result_or_except;
LocalVar<JsFunction> member_func = UnsafeJsCast<JsFunction>(member);
if (!InvokeMethod(member_func, that, argc, argv, &result_or_except)) {
return ConvertError(result_or_except);
}
if (result)
*result = result_or_except;
return monostate();
}
Converter<void>::variant_type AttachEventListener(
Handle<JsObject> player, const std::string& name, Player::Client* client,
std::function<void(Handle<JsObject> event)> handler) {
const std::function<void(optional<Any>)> callback = [=](optional<Any> event) {
// We can't accept or use events::Event since Shaka player raises fake
// events. So manually look for the properties.
LocalVar<JsValue> event_val = ToJsValue(event);
if (!IsObject(event_val)) {
client->OnError(
Error(ErrorType::NonShakaError, ConvertToString(event_val)));
return;
}
LocalVar<JsObject> event_obj = UnsafeJsCast<JsObject>(event_val);
handler(event_obj);
};
LocalVar<JsFunction> callback_js = CreateStaticFunction("", "", callback);
LocalVar<JsValue> arguments[] = {ToJsValue(name), RawToJsValue(callback_js)};
return CallMemberFunction(player, "addEventListener", 2, arguments, nullptr);
}
} // namespace
// Allow using shaka::ToJsValue() (from convert_js.h) for DefaultValue.
template <>
struct impl::ConvertHelper<DefaultValueType> {
static ReturnVal<JsValue> ToJsValue(DefaultValueType /* unused */) {
return JsUndefined();
}
};
class Player::Impl {
public:
explicit Impl(JsManager* engine) {
CHECK(engine) << "Must pass a JsManager instance";
}
~Impl() {
if (player_)
CallPlayerPromiseMethod<void>("destroy").wait();
}
NON_COPYABLE_OR_MOVABLE_TYPE(Impl);
Converter<void>::future_type Initialize(js::mse::HTMLVideoElement* video,
Client* client) {
// This function can be called immediately after the JsManager
// constructor. Since the Environment might not be setup yet, run this in
// an internal task so we know it is ready.
const auto callback = [=]() -> Converter<void>::variant_type {
LocalVar<JsValue> player_ctor = GetDescendant(
JsEngine::Instance()->global_handle(), {"shaka", "Player"});
if (GetValueType(player_ctor) != JSValueType::Function) {
LOG(ERROR) << "Cannot get 'shaka.Player' object; is "
"shaka-player.compiled.js corrupted?";
return Error(ErrorType::BadMember,
"The constructor 'shaka.Player' is not found.");
}
LocalVar<JsFunction> player_ctor_func =
UnsafeJsCast<JsFunction>(player_ctor);
LocalVar<JsValue> result_or_except;
LocalVar<JsValue> args[] = {video->JsThis()};
if (!InvokeConstructor(player_ctor_func, 1, args, &result_or_except)) {
return ConvertError(result_or_except);
}
player_ = UnsafeJsCast<JsObject>(result_or_except);
return AttachListeners(player_, client);
};
return JsManagerImpl::Instance()
->MainThread()
->AddInternalTask(TaskPriority::Internal, "Player ctor",
PlainCallbackTask(callback))
->future();
}
/** Calls the given Player method and returns the result as a Ret type. */
template <typename Ret, typename... Args>
typename Converter<Ret>::future_type CallPlayerMethod(
const std::string& name, const Args&... args) const {
const auto callback = [=]() -> typename Converter<Ret>::variant_type {
LocalVar<JsValue> result;
LocalVar<JsValue> js_args[] = {ToJsValue(args)..., JsUndefined()};
auto error =
CallMemberFunction(player_, name, sizeof...(args), js_args, &result);
if (holds_alternative<Error>(error))
return get<Error>(error);
return Converter<Ret>::Convert(name, result);
};
return JsManagerImpl::Instance()
->MainThread()
->AddInternalTask(TaskPriority::Internal, "Player." + name,
PlainCallbackTask(callback))
->future();
}
/**
* Calls the given Player method that should return a Promise to the given
* type. The resulting async results will complete when the Promise is
* resolved/rejected.
*/
template <typename Ret, typename... Args>
typename Converter<Ret>::future_type CallPlayerPromiseMethod(
const std::string& name, Args&&... args) {
// TODO: Combine with CallPlayerMethod. These are separate since this uses
// a std::promise for the return value rather than the internal task future.
auto promise =
std::make_shared<std::promise<typename Converter<Ret>::variant_type>>();
const auto callback = [this, promise, name, args...]() {
LocalVar<JsValue> result;
LocalVar<JsValue> js_args[] = {ToJsValue(args)..., JsUndefined()};
auto error =
CallMemberFunction(player_, name, sizeof...(args), js_args, &result);
if (holds_alternative<Error>(error)) {
promise->set_value(get<Error>(error));
return;
}
auto js_promise = Converter<Promise>::Convert(name, result);
if (holds_alternative<Error>(js_promise)) {
promise->set_value(get<Error>(js_promise));
return;
}
get<Promise>(js_promise)
.Then(
[promise, name](Any res) {
LocalVar<JsValue> value = res.ToJsValue();
promise->set_value(Converter<Ret>::Convert(name, value));
},
[promise](Any except) {
LocalVar<JsValue> val = except.ToJsValue();
promise->set_value(ConvertError(val));
});
};
JsManagerImpl::Instance()
->MainThread()
->AddInternalTask(TaskPriority::Internal, "Player." + name,
PlainCallbackTask(callback))
->future();
return promise->get_future().share();
}
template <typename T>
typename Converter<T>::future_type GetConfigValue(
const std::string& name_path) {
const auto callback = [=]() -> typename Converter<T>::variant_type {
LocalVar<JsValue> configuration;
auto error = CallMemberFunction(player_, "getConfiguration", 0, nullptr,
&configuration);
if (holds_alternative<Error>(error))
return get<Error>(error);
// Split the name path on periods.
std::vector<std::string> components = util::StringSplit(name_path, '.');
// Navigate through the path.
auto result =
GetDescendant(UnsafeJsCast<JsObject>(configuration), components);
return Converter<T>::Convert(name_path, result);
};
return JsManagerImpl::Instance()
->MainThread()
->AddInternalTask(TaskPriority::Internal, "Player.getConfiguration",
PlainCallbackTask(callback))
->future();
}
private:
Converter<void>::variant_type AttachListeners(Handle<JsObject> player,
Client* client) {
#define ATTACH(name, call) \
do { \
const auto ret = AttachEventListener(player, name, client, call); \
if (holds_alternative<Error>(ret)) \
return get<Error>(ret); \
} while (false)
const auto on_error = [=](Handle<JsObject> event) {
LocalVar<JsValue> detail = GetMemberRaw(event, "detail");
client->OnError(ConvertError(detail));
};
ATTACH("error", on_error);
const auto on_buffering = [=](Handle<JsObject> event) {
LocalVar<JsValue> is_buffering = GetMemberRaw(event, "buffering");
bool is_buffering_bool;
if (FromJsValue(is_buffering, &is_buffering_bool)) {
client->OnBuffering(is_buffering_bool);
} else {
client->OnError(Error(ErrorType::NonShakaError,
"Bad 'buffering' event from JavaScript Player"));
}
};
ATTACH("buffering", on_buffering);
#undef ATTACH
return {};
}
Global<JsObject> player_;
};
Player::Client::Client() {}
Player::Client::Client(const Client&) = default;
Player::Client::Client(Client&&) = default;
Player::Client::~Client() {}
Player::Client& Player::Client::operator=(const Client&) = default;
Player::Client& Player::Client::operator=(Client&&) = default;
void Player::Client::OnError(const Error& /* error */) {}
void Player::Client::OnBuffering(bool /* is_buffering */) {}
Player::Player(JsManager* engine) : impl_(new Impl(engine)) {}
Player::Player(Player&&) = default;
Player::~Player() {}
Player& Player::operator=(Player&&) = default;
AsyncResults<void> Player::SetLogLevel(JsManager* engine, LogLevel level) {
DCHECK(engine);
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
const auto callback = [level]() -> Converter<void>::variant_type {
LocalVar<JsValue> set_level = GetDescendant(
JsEngine::Instance()->global_handle(), {"shaka", "log", "setLevel"});
if (GetValueType(set_level) != JSValueType::Function) {
LOG(ERROR) << "Cannot get 'shaka.log.setLevel' function; is "
"shaka-player.compiled.js a Release build?";
return Error(ErrorType::BadMember,
"The function 'shaka.log.setLevel' is not found.");
}
LocalVar<JsFunction> set_level_func = UnsafeJsCast<JsFunction>(set_level);
LocalVar<JsValue> args[] = {ToJsValue(static_cast<int>(level))};
LocalVar<JsValue> except;
if (!InvokeMethod(set_level_func, JsEngine::Instance()->global_handle(), 1,
args, &except)) {
return ConvertError(except);
}
return monostate();
};
return JsManagerImpl::Instance()
->MainThread()
->AddInternalTask(TaskPriority::Internal, "SetLogLevel",
PlainCallbackTask(callback))
->future();
}
AsyncResults<Player::LogLevel> Player::GetLogLevel(JsManager* engine) {
DCHECK(engine);
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
const auto callback = []() -> Converter<Player::LogLevel>::variant_type {
LocalVar<JsValue> current_level =
GetDescendant(JsEngine::Instance()->global_handle(),
{"shaka", "log", "currentLevel"});
if (GetValueType(current_level) != JSValueType::Number) {
LOG(ERROR) << "Cannot get 'shaka.log.currentLevel'; is "
"shaka-player.compiled.js a Release build?";
return Error(ErrorType::BadMember,
"The variable 'shaka.log.currentLevel' is not found.");
}
return static_cast<LogLevel>(NumberFromValue(current_level));
};
return JsManagerImpl::Instance()
->MainThread()
->AddInternalTask(TaskPriority::Internal, "GetLogLevel",
PlainCallbackTask(callback))
->future();
}
AsyncResults<std::string> Player::GetPlayerVersion(JsManager* engine) {
DCHECK(engine);
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
const auto callback = []() -> Converter<std::string>::variant_type {
LocalVar<JsValue> version = GetDescendant(
JsEngine::Instance()->global_handle(), {"shaka", "Player", "version"});
std::string ret;
if (!FromJsValue(version, &ret)) {
return Error(ErrorType::BadMember,
"The variable 'shaka.Player.version' is not found.");
}
return ret;
};
return JsManagerImpl::Instance()
->MainThread()
->AddInternalTask(TaskPriority::Internal, "GetVersion",
PlainCallbackTask(callback))
->future();
}
AsyncResults<void> Player::Initialize(Video* video, Client* client) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->Initialize(video->GetJavaScriptObject(), client);
}
AsyncResults<void> Player::Destroy() {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerPromiseMethod<void>("destroy");
}
AsyncResults<bool> Player::IsAudioOnly() const {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<bool>("isAudioOnly");
}
AsyncResults<bool> Player::IsBuffering() const {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<bool>("isBuffering");
}
AsyncResults<bool> Player::IsInProgress() const {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<bool>("isInProgress");
}
AsyncResults<bool> Player::IsLive() const {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<bool>("isLive");
}
AsyncResults<bool> Player::IsTextTrackVisible() const {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<bool>("isTextTrackVisible");
}
AsyncResults<bool> Player::UsingEmbeddedTextTrack() const {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<bool>("usingEmbeddedTextTrack");
}
AsyncResults<optional<std::string>> Player::AssetUri() const {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<optional<std::string>>("assetUri");
}
AsyncResults<optional<DrmInfo>> Player::DrmInfo() const {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<optional<shaka::DrmInfo>>("drmInfo");
}
AsyncResults<std::vector<LanguageRole>> Player::GetAudioLanguagesAndRoles()
const {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<std::vector<LanguageRole>>(
"getAudioLanguagesAndRoles");
}
AsyncResults<BufferedInfo> Player::GetBufferedInfo() const {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<BufferedInfo>("getBufferedInfo");
}
AsyncResults<double> Player::GetExpiration() const {
return impl_->CallPlayerMethod<double>("getExpiration");
}
AsyncResults<Stats> Player::GetStats() const {
return impl_->CallPlayerMethod<Stats>("getStats");
}
AsyncResults<std::vector<Track>> Player::GetTextTracks() const {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<std::vector<Track>>("getTextTracks");
}
AsyncResults<std::vector<Track>> Player::GetVariantTracks() const {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<std::vector<Track>>("getVariantTracks");
}
AsyncResults<std::vector<LanguageRole>> Player::GetTextLanguagesAndRoles()
const {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<std::vector<LanguageRole>>(
"getTextLanguagesAndRoles");
}
AsyncResults<std::string> Player::KeySystem() const {
return impl_->CallPlayerMethod<std::string>("keySystem");
}
AsyncResults<BufferedRange> Player::SeekRange() const {
return impl_->CallPlayerMethod<BufferedRange>("seekRange");
}
AsyncResults<void> Player::Load(const std::string& manifest_uri,
double start_time) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerPromiseMethod<void>("load", manifest_uri,
LoadHelper(start_time));
}
AsyncResults<void> Player::Unload() {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerPromiseMethod<void>("unload");
}
AsyncResults<bool> Player::Configure(const std::string& name_path,
DefaultValueType value) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<bool>("configure", name_path, value);
}
AsyncResults<bool> Player::Configure(const std::string& name_path, bool value) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<bool>("configure", name_path, value);
}
AsyncResults<bool> Player::Configure(const std::string& name_path,
double value) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<bool>("configure", name_path, value);
}
AsyncResults<bool> Player::Configure(const std::string& name_path,
const std::string& value) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<bool>("configure", name_path, value);
}
AsyncResults<bool> Player::GetConfigurationBool(const std::string& name_path) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->GetConfigValue<bool>(name_path);
}
AsyncResults<double> Player::GetConfigurationDouble(
const std::string& name_path) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->GetConfigValue<double>(name_path);
}
AsyncResults<std::string> Player::GetConfigurationString(
const std::string& name_path) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->GetConfigValue<std::string>(name_path);
}
AsyncResults<void> Player::ResetConfiguration() {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<void>("resetConfiguration");
}
AsyncResults<void> Player::RetryStreaming() {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<void>("retryStreaming");
}
AsyncResults<void> Player::SelectAudioLanguage(const std::string& language,
optional<std::string> role) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<void>("selectAudioLanguage", language, role);
}
AsyncResults<void> Player::SelectEmbeddedTextTrack() {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<void>("selectEmbeddedTextTrack");
}
AsyncResults<void> Player::SelectTextLanguage(const std::string& language,
optional<std::string> role) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<void>("selectTextLanguage", language, role);
}
AsyncResults<void> Player::SelectTextTrack(const Track& track) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<void>("selectTextTrack", track.GetInternal());
}
AsyncResults<void> Player::SelectVariantTrack(const Track& track,
bool clear_buffer) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<void>("selectVariantTrack",
track.GetInternal(), clear_buffer);
}
AsyncResults<void> Player::SetTextTrackVisibility(bool visibility) {
DCHECK(!JsManagerImpl::Instance()->MainThread()->BelongsToCurrentThread());
return impl_->CallPlayerMethod<void>("setTextTrackVisibility", visibility);
}
} // namespace shaka
<file_sep>/shaka/src/media/media_processor.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/media_processor.h"
#include <netinet/in.h>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/encryption_info.h>
#include <libavutil/hwcontext.h>
#include <libavutil/opt.h>
}
#include <cstring>
#include <utility>
#include "src/core/js_manager_impl.h"
#include "src/debug/mutex.h"
#include "src/debug/thread_event.h"
#include "src/media/ffmpeg_decoded_frame.h"
#include "src/media/ffmpeg_encoded_frame.h"
#include "src/media/media_utils.h"
#include "src/util/utils.h"
// Special error code added by //third_party/ffmpeg/mov.patch
#define AVERROR_SHAKA_RESET_DEMUXER (-123456)
namespace shaka {
namespace media {
namespace {
constexpr const size_t kInitialBufferSize = 2048;
std::string ErrStr(int code) {
if (code == 0)
return "Success";
const char* prefix = code < 0 ? "-" : "";
return util::StringPrintf("%s0x%08x: %s", prefix, abs(code),
av_err2str(code));
}
/**
* Prints logs about the given FFmpeg error code. Many of the codes don't apply
* to us, so this method asserts that we don't see those codes. For those that
* apply, this prints logs about it.
*/
void HandleGenericFFmpegError(int code) {
// See //third_party/ffmpeg/src/libavutil/error.h
switch (code) {
case AVERROR_BSF_NOT_FOUND:
case AVERROR_DECODER_NOT_FOUND:
case AVERROR_DEMUXER_NOT_FOUND:
case AVERROR_ENCODER_NOT_FOUND:
case AVERROR_FILTER_NOT_FOUND:
case AVERROR_MUXER_NOT_FOUND:
case AVERROR_OPTION_NOT_FOUND:
case AVERROR_STREAM_NOT_FOUND:
// This should be handled by VideoController::AddSource.
LOG(DFATAL) << "Unable to find media handler: " << ErrStr(code);
break;
case AVERROR_BUFFER_TOO_SMALL:
case AVERROR_EOF:
case AVERROR_INVALIDDATA:
case AVERROR_INPUT_CHANGED:
case AVERROR_OUTPUT_CHANGED:
case AVERROR(EAGAIN):
case AVERROR(EINVAL):
case AVERROR(ENOMEM):
// Calling code should handle these codes.
LOG(DFATAL) << "Special error not handled: " << ErrStr(code);
break;
case AVERROR_HTTP_BAD_REQUEST:
case AVERROR_HTTP_UNAUTHORIZED:
case AVERROR_HTTP_FORBIDDEN:
case AVERROR_HTTP_NOT_FOUND:
case AVERROR_HTTP_OTHER_4XX:
case AVERROR_HTTP_SERVER_ERROR:
case AVERROR_PROTOCOL_NOT_FOUND:
// We don't use FFmpeg's networking, so this shouldn't happen.
LOG(DFATAL) << "Unexpected networking error: " << ErrStr(code);
break;
case AVERROR_BUG:
case AVERROR_BUG2:
case AVERROR_PATCHWELCOME:
LOG(DFATAL) << "Bug inside FFmpeg: " << ErrStr(code);
break;
case AVERROR_EXIT:
case AVERROR_EXTERNAL:
case AVERROR_UNKNOWN:
LOG(ERROR) << "Unknown error inside FFmpeg: " << ErrStr(code);
break;
default:
LOG(DFATAL) << "Unknown error: " << ErrStr(code);
break;
}
}
const AVCodec* FindCodec(AVCodecID codec_id) {
#ifdef ENABLE_HARDWARE_DECODE
const AVCodec* hybrid = nullptr;
const AVCodec* external = nullptr;
void* opaque = nullptr;
while (const AVCodec* codec = av_codec_iterate(&opaque)) {
if (codec->id == codec_id && av_codec_is_decoder(codec)) {
if (codec->capabilities & AV_CODEC_CAP_HARDWARE)
return codec;
if (codec->capabilities & AV_CODEC_CAP_HYBRID) {
// Keep the hybrid as a fallback, but try to find a hardware-only one.
hybrid = codec;
} else if (codec->wrapper_name) {
// This is an external codec, which may be provided by the OS. Fallback
// to this if nothing else.
external = codec;
}
}
}
if (hybrid)
return hybrid;
if (external)
return external;
#endif
return avcodec_find_decoder(codec_id);
}
/**
* Creates a 'pssh' box from the given encryption info. FFmpeg outputs the
* encryption info in a generic structure, but EME expects it in one of several
* binary formats. We use the 'cenc' format, which is one or more 'pssh' boxes.
*/
std::vector<uint8_t> CreatePssh(AVEncryptionInitInfo* info) {
// 4 box size
// 4 box type
// 1 version
// 3 flags
// 16 system_id
// if (version > 0)
// 4 key_id_count
// for (key_id_count)
// 16 key_id
// 4 data_size
// [data_size] data
DCHECK_EQ(info->system_id_size, 16u);
size_t pssh_size = info->data_size + 32;
if (info->num_key_ids) {
DCHECK_EQ(info->key_id_size, 16u);
pssh_size += 4 + info->num_key_ids * 16;
}
#define WRITE_INT(ptr, num) *reinterpret_cast<uint32_t*>(ptr) = htonl(num)
std::vector<uint8_t> pssh(pssh_size, 0);
uint8_t* ptr = pssh.data();
WRITE_INT(ptr, pssh_size);
WRITE_INT(ptr + 4, 0x70737368); // 'pssh'
WRITE_INT(ptr + 8, info->num_key_ids ? 0x01000000 : 0);
std::memcpy(ptr + 12, info->system_id, 16);
ptr += 28;
if (info->num_key_ids) {
WRITE_INT(ptr, info->num_key_ids);
ptr += 4;
for (uint32_t i = 0; i < info->num_key_ids; i++) {
std::memcpy(ptr, info->key_ids[i], 16);
ptr += 16;
}
}
WRITE_INT(ptr, info->data_size);
std::memcpy(ptr + 4, info->data, info->data_size);
DCHECK_EQ(ptr + info->data_size + 4, pssh.data() + pssh_size);
#undef WRITE_INT
return pssh;
}
} // namespace
class MediaProcessor::Impl {
public:
Impl(const std::string& container, const std::string& codec,
std::function<void(eme::MediaKeyInitDataType, const uint8_t*, size_t)>
on_encrypted_init_data)
: mutex_("MediaProcessor"),
signal_("MediaProcessor demuxer ready"),
on_encrypted_init_data_(std::move(on_encrypted_init_data)),
container_(NormalizeContainer(container)),
codec_(NormalizeCodec(codec)),
io_(nullptr),
demuxer_ctx_(nullptr),
decoder_ctx_(nullptr),
received_frame_(nullptr),
#ifdef ENABLE_HARDWARE_DECODE
hw_device_ctx_(nullptr),
hw_pix_fmt_(AV_PIX_FMT_NONE),
#endif
timestamp_offset_(0),
prev_timestamp_offset_(0),
decoder_stream_id_(0) {
}
~Impl() {
if (io_) {
// If an IO buffer was allocated by libavformat, it must be freed by us.
if (io_->buffer) {
av_free(io_->buffer);
}
// The IO context itself must be freed by us as well. Closing ctx_ does
// not free the IO context attached to it.
av_free(io_);
}
// It is safe if these fields are nullptr.
for (AVCodecParameters*& params : codec_params_)
avcodec_parameters_free(¶ms);
avcodec_free_context(&decoder_ctx_);
avformat_close_input(&demuxer_ctx_);
av_frame_free(&received_frame_);
#ifdef ENABLE_HARDWARE_DECODE
av_buffer_unref(&hw_device_ctx_);
#endif
}
NON_COPYABLE_OR_MOVABLE_TYPE(Impl);
std::string container() const {
return container_;
}
std::string codec() const {
return codec_;
}
double duration() const {
std::unique_lock<Mutex> lock(mutex_);
if (!demuxer_ctx_ || demuxer_ctx_->duration == AV_NOPTS_VALUE)
return 0;
return static_cast<double>(demuxer_ctx_->duration) / AV_TIME_BASE;
}
Status ReinitDemuxer(std::unique_lock<Mutex>* lock) {
avformat_close_input(&demuxer_ctx_);
avio_flush(io_);
AVFormatContext* new_ctx;
// Create the new demuxer without the lock held because the method will
// block while waiting for the init segment.
lock->unlock();
const Status status = CreateDemuxer(&new_ctx);
if (status != Status::Success)
return status;
lock->lock();
demuxer_ctx_ = new_ctx;
AVStream* stream = demuxer_ctx_->streams[0];
auto* params = avcodec_parameters_alloc();
if (!params) {
return Status::OutOfMemory;
}
const int copy_code = avcodec_parameters_copy(params, stream->codecpar);
if (copy_code < 0) {
avcodec_parameters_free(¶ms);
HandleGenericFFmpegError(copy_code);
return Status::CannotOpenDemuxer;
}
codec_params_.push_back(params);
time_scales_.push_back(stream->time_base);
return Status::Success;
}
Status CreateDemuxer(AVFormatContext** context) {
// Allocate a demuxer context and set it to use the IO context.
AVFormatContext* demuxer = avformat_alloc_context();
if (!demuxer) {
return Status::OutOfMemory;
}
demuxer->pb = io_;
// If we enable the probes, in encrypted content we'll get logs about being
// unable to parse the content; however, if we disable the probes, we won't
// get accurate frame durations, which can cause problems.
// TODO: Find a way to conditionally disable parsing or to suppress the
// logs for encrypted content (since the errors there aren't fatal).
// demuxer->probesize = 0;
// demuxer->max_analyze_duration = 0;
// To enable extremely verbose logging:
// demuxer->debug = 1;
// Parse encryption info for WebM; ignored for other demuxers.
AVDictionary* dict = nullptr;
CHECK_EQ(av_dict_set_int(&dict, "parse_encryption", 1, 0), 0);
AVInputFormat* format = av_find_input_format(container_.c_str());
CHECK(format) << "Should have checked for support before creating.";
const int open_code = avformat_open_input(&demuxer, nullptr, format, &dict);
av_dict_free(&dict);
if (open_code < 0) {
// If avformat_open_input fails, it will free and reset |demuxer|.
DCHECK(!demuxer);
if (open_code == AVERROR(ENOMEM))
return Status::OutOfMemory;
if (open_code == AVERROR_INVALIDDATA)
return Status::InvalidContainerData;
HandleGenericFFmpegError(open_code);
return Status::CannotOpenDemuxer;
}
const int find_code = avformat_find_stream_info(demuxer, nullptr);
if (find_code < 0) {
avformat_close_input(&demuxer);
if (find_code == AVERROR(ENOMEM))
return Status::OutOfMemory;
if (find_code == AVERROR_INVALIDDATA)
return Status::InvalidContainerData;
HandleGenericFFmpegError(find_code);
return Status::CannotOpenDemuxer;
}
if (demuxer->nb_streams == 0) {
avformat_close_input(&demuxer);
return Status::NoStreamsFound;
}
if (demuxer->nb_streams > 1) {
avformat_close_input(&demuxer);
return Status::MultiplexedContentFound;
}
*context = demuxer;
return Status::Success;
}
Status InitializeDemuxer(std::function<size_t(uint8_t*, size_t)> on_read,
std::function<void()> on_reset_read) {
std::unique_lock<Mutex> lock(mutex_);
on_read_ = std::move(on_read);
on_reset_read_ = std::move(on_reset_read);
// Allocate a context for custom IO.
// NOTE: The buffer may be reallocated/resized by libavformat later.
// It is always our responsibility to free it later with av_free.
io_ = avio_alloc_context(
reinterpret_cast<unsigned char*>(av_malloc(kInitialBufferSize)),
kInitialBufferSize,
0, // write_flag (read-only)
this, // opaque user data
&Impl::ReadCallback,
nullptr, // write callback (read-only)
nullptr); // seek callback (linear reads only)
if (!io_) {
return Status::OutOfMemory;
}
received_frame_ = av_frame_alloc();
if (!received_frame_) {
return Status::OutOfMemory;
}
const Status reinit_status = ReinitDemuxer(&lock);
if (reinit_status == Status::Success)
signal_.SignalAll();
return reinit_status;
}
Status ReadDemuxedFrame(std::unique_ptr<BaseFrame>* frame) {
AVPacket pkt;
int ret = av_read_frame(demuxer_ctx_, &pkt);
if (ret == AVERROR_SHAKA_RESET_DEMUXER) {
// Special case for Shaka where we need to reinit the demuxer.
VLOG(1) << "Reinitializing demuxer";
on_reset_read_();
std::unique_lock<Mutex> lock(mutex_);
const Status reinit_status = ReinitDemuxer(&lock);
if (reinit_status != Status::Success)
return reinit_status;
ret = av_read_frame(demuxer_ctx_, &pkt);
}
if (ret < 0) {
av_packet_unref(&pkt);
if (ret == AVERROR_EOF)
return Status::EndOfStream;
if (ret == AVERROR(ENOMEM))
return Status::OutOfMemory;
if (ret == AVERROR_INVALIDDATA)
return Status::InvalidContainerData;
HandleGenericFFmpegError(ret);
return Status::UnknownError;
}
UpdateEncryptionInitInfo();
// Ignore discard flags. The demuxer will set this when we try to read
// content behind media we have already read.
pkt.flags &= ~AV_PKT_FLAG_DISCARD;
VLOG(3) << "Read frame at dts=" << pkt.dts;
DCHECK_EQ(pkt.stream_index, 0);
DCHECK_EQ(demuxer_ctx_->nb_streams, 1u);
frame->reset(FFmpegEncodedFrame::MakeFrame(&pkt, demuxer_ctx_->streams[0],
codec_params_.size() - 1,
timestamp_offset_));
// No need to unref |pkt| since it was moved into the encoded frame.
return *frame ? Status::Success : Status::OutOfMemory;
}
Status InitializeDecoder(size_t stream_id, bool allow_hardware) {
const AVCodecParameters* params = codec_params_[stream_id];
const char* codec_name = avcodec_get_name(params->codec_id);
if (codec_ != codec_name) {
LOG(ERROR) << "Mismatch between codec string and media. Codec string: '"
<< codec_ << "', media codec: '" << codec_name << "' (0x"
<< std::hex << params->codec_id << ")";
return Status::DecoderMismatch;
}
const AVCodec* decoder = allow_hardware
? FindCodec(params->codec_id)
: avcodec_find_decoder(params->codec_id);
CHECK(decoder) << "Should have checked support already";
#ifdef ENABLE_HARDWARE_DECODE
AVHWDeviceType hw_type = AV_HWDEVICE_TYPE_NONE;
hw_pix_fmt_ = AV_PIX_FMT_NONE;
if (allow_hardware) {
for (int i = 0;; i++) {
const AVCodecHWConfig* config = avcodec_get_hw_config(decoder, i);
if (!config) {
# ifdef FORCE_HARDWARE_DECODE
if (!decoder->wrapper_name) {
LOG(DFATAL) << "No hardware-accelerators available for codec: "
<< codec_;
return Status::DecoderFailedInit;
}
# endif
LOG(INFO) << "No hardware-accelerators available, using decoder: "
<< decoder->name;
break;
}
if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) {
LOG(INFO) << "Using decoder: " << decoder->name
<< ", with hardware accelerator: "
<< av_hwdevice_get_type_name(config->device_type);
hw_type = config->device_type;
hw_pix_fmt_ = config->pix_fmt;
break;
}
}
}
#endif
avcodec_free_context(&decoder_ctx_);
decoder_ctx_ = avcodec_alloc_context3(decoder);
if (!decoder_ctx_) {
return Status::OutOfMemory;
}
const int param_code = avcodec_parameters_to_context(decoder_ctx_, params);
if (param_code < 0) {
if (param_code == AVERROR(ENOMEM)) {
return Status::OutOfMemory;
}
HandleGenericFFmpegError(param_code);
return Status::DecoderFailedInit;
}
decoder_ctx_->thread_count = 0; // Default is 1; 0 means auto-detect.
decoder_ctx_->opaque = this;
decoder_ctx_->pkt_timebase = time_scales_[stream_id];
#ifdef ENABLE_HARDWARE_DECODE
// If using a hardware accelerator, initialize it now.
av_buffer_unref(&hw_device_ctx_);
if (allow_hardware && hw_type != AV_HWDEVICE_TYPE_NONE) {
const int hw_device_code =
av_hwdevice_ctx_create(&hw_device_ctx_, hw_type, nullptr, nullptr, 0);
if (hw_device_code < 0) {
if (hw_device_code == AVERROR(ENOMEM)) {
return Status::OutOfMemory;
}
HandleGenericFFmpegError(hw_device_code);
return Status::DecoderFailedInit;
}
decoder_ctx_->get_format = &GetPixelFormat;
decoder_ctx_->hw_device_ctx = av_buffer_ref(hw_device_ctx_);
}
#endif
const int open_code = avcodec_open2(decoder_ctx_, decoder, nullptr);
if (open_code < 0) {
if (open_code == AVERROR(ENOMEM))
return Status::OutOfMemory;
#if defined(ENABLE_HARDWARE_DECODE) && !defined(FORCE_HARDWARE_DECODE)
if (allow_hardware) {
LOG(WARNING) << "Failed to initialize hardware decoder, falling back "
"to software.";
return InitializeDecoder(stream_id, false);
}
#endif
HandleGenericFFmpegError(open_code);
return Status::DecoderFailedInit;
}
decoder_stream_id_ = stream_id;
return Status::Success;
}
Status ReadFromDecoder(size_t stream_id, const FFmpegEncodedFrame* frame,
std::vector<std::unique_ptr<BaseFrame>>* decoded) {
while (true) {
const int code = avcodec_receive_frame(decoder_ctx_, received_frame_);
if (code == AVERROR(EAGAIN) || code == AVERROR_EOF)
return Status::Success;
if (code == AVERROR_INVALIDDATA)
return Status::InvalidCodecData;
if (code < 0) {
HandleGenericFFmpegError(code);
return Status::UnknownError;
}
const double timescale = av_q2d(time_scales_[stream_id]);
const int64_t timestamp = received_frame_->best_effort_timestamp;
const double offset =
frame ? frame->timestamp_offset() : prev_timestamp_offset_;
const double time = frame && timestamp == AV_NOPTS_VALUE
? frame->pts
: timestamp * timescale + offset;
auto* new_frame = FFmpegDecodedFrame::CreateFrame(
received_frame_, time, frame ? frame->duration : 0);
if (!new_frame) {
return Status::OutOfMemory;
}
decoded->emplace_back(new_frame);
}
}
Status DecodeFrame(double /* cur_time */, const BaseFrame* base_frame,
eme::Implementation* cdm,
std::vector<std::unique_ptr<BaseFrame>>* decoded) {
decoded->clear();
DCHECK(!base_frame ||
base_frame->frame_type() == FrameType::FFmpegEncodedFrame);
auto* frame = static_cast<const FFmpegEncodedFrame*>(base_frame);
if (!frame && !decoder_ctx_) {
// If there isn't a decoder, there is nothing to flush.
return Status::Success;
}
if (frame) {
// Wait for the signal before acquiring the lock to avoid a deadlock.
signal_.GetValue();
std::unique_lock<Mutex> lock(mutex_);
if (!decoder_ctx_ || frame->stream_id() != decoder_stream_id_) {
VLOG(1) << "Reconfiguring decoder";
// Flush the old decoder to get any existing frames.
if (decoder_ctx_) {
const int send_code = avcodec_send_packet(decoder_ctx_, nullptr);
if (send_code != 0) {
if (send_code == AVERROR(ENOMEM))
return Status::OutOfMemory;
if (send_code == AVERROR_INVALIDDATA)
return Status::InvalidCodecData;
HandleGenericFFmpegError(send_code);
return Status::UnknownError;
}
const Status read_result =
ReadFromDecoder(decoder_stream_id_, nullptr, decoded);
if (read_result != Status::Success)
return read_result;
}
const Status init_result = InitializeDecoder(frame->stream_id(), true);
if (init_result != Status::Success)
return init_result;
}
prev_timestamp_offset_ = frame->timestamp_offset();
}
// If the encoded frame is encrypted, decrypt it first.
AVPacket decrypted_packet{};
util::Finally free_decrypted_packet(
std::bind(&av_packet_unref, &decrypted_packet));
const AVPacket* frame_to_send = frame ? frame->raw_packet() : nullptr;
if (frame && frame->is_encrypted()) {
if (!cdm) {
LOG(WARNING) << "No CDM given for encrypted frame";
return Status::KeyNotFound;
}
int code = av_new_packet(&decrypted_packet, frame->raw_packet()->size);
if (code == 0)
code = av_packet_copy_props(&decrypted_packet, frame->raw_packet());
if (code == AVERROR(ENOMEM))
return Status::OutOfMemory;
if (code < 0) {
HandleGenericFFmpegError(code);
return Status::UnknownError;
}
Status decrypt_status = frame->Decrypt(cdm, &decrypted_packet);
if (decrypt_status != Status::Success)
return decrypt_status;
frame_to_send = &decrypted_packet;
}
bool sent_frame = false;
while (!sent_frame) {
// If we get EAGAIN, we should read some frames and try to send again.
const int send_code = avcodec_send_packet(decoder_ctx_, frame_to_send);
if (send_code == 0) {
sent_frame = true;
} else if (send_code == AVERROR_EOF) {
// If we get EOF, this is either a flush or we are closing. Either way,
// stop. If this is a flush, we can't reuse the decoder, so reset it.
ResetDecoder();
break;
} else if (send_code != AVERROR(EAGAIN)) {
if (send_code == AVERROR(ENOMEM))
return Status::OutOfMemory;
if (send_code == AVERROR_INVALIDDATA)
return Status::InvalidCodecData;
HandleGenericFFmpegError(send_code);
return Status::UnknownError;
}
const int stream_id = frame ? frame->stream_id() : decoder_stream_id_;
const Status read_result = ReadFromDecoder(stream_id, frame, decoded);
if (read_result != Status::Success)
return read_result;
}
return Status::Success;
}
void SetTimestampOffset(double offset) {
timestamp_offset_ = offset;
}
void ResetDecoder() {
avcodec_free_context(&decoder_ctx_);
}
private:
static int ReadCallback(void* opaque, uint8_t* buffer, int size) {
DCHECK_GE(size, 0);
const size_t count =
reinterpret_cast<Impl*>(opaque)->on_read_(buffer, size);
return count == 0 ? AVERROR_EOF : count;
}
#ifdef ENABLE_HARDWARE_DECODE
static AVPixelFormat GetPixelFormat(AVCodecContext* ctx,
const AVPixelFormat* formats) {
AVPixelFormat desired = reinterpret_cast<Impl*>(ctx->opaque)->hw_pix_fmt_;
for (size_t i = 0; formats[i] != AV_PIX_FMT_NONE; i++) {
if (formats[i] == desired)
return formats[i];
}
# ifdef FORCE_HARDWARE_DECODE
LOG(DFATAL) << "Hardware pixel format is unsupported.";
return AV_PIX_FMT_NONE;
# else
LOG(ERROR) << "Hardware pixel format is unsupported, may be falling back "
"to software decoder.";
return formats[0];
# endif
}
#endif
void UpdateEncryptionInitInfo() {
int side_data_size;
const uint8_t* side_data = av_stream_get_side_data(
demuxer_ctx_->streams[0], AV_PKT_DATA_ENCRYPTION_INIT_INFO,
&side_data_size);
if (side_data) {
AVEncryptionInitInfo* info =
av_encryption_init_info_get_side_data(side_data, side_data_size);
std::vector<uint8_t> pssh;
for (auto* cur_info = info; cur_info; cur_info = cur_info->next) {
if (cur_info->system_id_size) {
const std::vector<uint8_t> temp = CreatePssh(cur_info);
pssh.insert(pssh.end(), temp.begin(), temp.end());
} else {
for (size_t i = 0; i < cur_info->num_key_ids; i++) {
on_encrypted_init_data_(eme::MediaKeyInitDataType::WebM,
cur_info->key_ids[i],
cur_info->key_id_size);
}
}
}
if (!pssh.empty()) {
on_encrypted_init_data_(eme::MediaKeyInitDataType::Cenc, pssh.data(),
pssh.size());
}
av_encryption_init_info_free(info);
av_stream_remove_side_data(demuxer_ctx_->streams[0],
AV_PKT_DATA_ENCRYPTION_INIT_INFO);
}
}
mutable Mutex mutex_;
ThreadEvent<void> signal_;
std::function<void(eme::MediaKeyInitDataType, const uint8_t*, size_t)>
on_encrypted_init_data_;
std::function<size_t(uint8_t*, size_t)> on_read_;
std::function<void()> on_reset_read_;
const std::string container_;
const std::string codec_;
std::vector<AVCodecParameters*> codec_params_;
std::vector<AVRational> time_scales_;
AVIOContext* io_;
AVFormatContext* demuxer_ctx_;
AVCodecContext* decoder_ctx_;
AVFrame* received_frame_;
#ifdef ENABLE_HARDWARE_DECODE
AVBufferRef* hw_device_ctx_;
AVPixelFormat hw_pix_fmt_;
#endif
double timestamp_offset_;
double prev_timestamp_offset_;
// The stream ID the decoder is currently configured to use.
size_t decoder_stream_id_;
};
MediaProcessor::MediaProcessor(
const std::string& container, const std::string& codec,
std::function<void(eme::MediaKeyInitDataType, const uint8_t*, size_t)>
on_encrypted_init_data)
: impl_(new Impl(container, codec, std::move(on_encrypted_init_data))) {}
MediaProcessor::~MediaProcessor() {}
// static
void MediaProcessor::Initialize() {
CHECK_EQ(avformat_version(),
static_cast<unsigned int>(LIBAVFORMAT_VERSION_INT))
<< "Running against wrong shared library version!";
#ifdef NDEBUG
av_log_set_level(AV_LOG_ERROR);
#else
av_log_set_level(AV_LOG_VERBOSE);
#endif
}
std::string MediaProcessor::container() const {
return impl_->container();
}
std::string MediaProcessor::codec() const {
return impl_->codec();
}
double MediaProcessor::duration() const {
return impl_->duration();
}
Status MediaProcessor::InitializeDemuxer(
std::function<size_t(uint8_t*, size_t)> on_read,
std::function<void()> on_reset_read) {
return impl_->InitializeDemuxer(std::move(on_read), std::move(on_reset_read));
}
Status MediaProcessor::ReadDemuxedFrame(std::unique_ptr<BaseFrame>* frame) {
return impl_->ReadDemuxedFrame(frame);
}
Status MediaProcessor::DecodeFrame(
double cur_time, const BaseFrame* frame, eme::Implementation* cdm,
std::vector<std::unique_ptr<BaseFrame>>* decoded) {
return impl_->DecodeFrame(cur_time, frame, cdm, decoded);
}
void MediaProcessor::SetTimestampOffset(double offset) {
impl_->SetTimestampOffset(offset);
}
void MediaProcessor::ResetDecoder() {
impl_->ResetDecoder();
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/include/shaka/utils.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_UTILS_H_
#define SHAKA_EMBEDDED_UTILS_H_
#include <string>
#include "macros.h"
namespace shaka {
/**
* @defgroup utils Utilities
* @ingroup exported
* A number of utility methods that an app may want to use.
* @{
*/
/**
* A simple struct representing a rectangle, with integer precision.
*/
struct SHAKA_EXPORT ShakaRect {
int x;
int y;
int w;
int h;
};
/**
* Creates a rectangle that can be used as a rendering destination to draw the
* video while maintaining aspect ratio. This will produce a rectangle that
* will fit inside the window area, but will maintain the aspect ratio of the
* video.
*
* @param video_width The width of the video.
* @param video_height The height of the video.
* @param window_width The width of the window, or the portion to use.
* @param window_height The height of the window, or the portion to use.
* @param window_x The X offset of the window region to use.
* @param window_y The Y offset of the window region to use.
*/
SHAKA_EXPORT ShakaRect FitVideoToWindow(int video_width, int video_height,
int window_width, int window_height,
int window_x = 0, int window_y = 0);
/**
* This creates a configuration key that sets the license server URL for the
* given key system.
*
* \code{.cpp}
* player.Configure(LicenseServerConfig("com.widevine.alpha"),
* "https://example.com/server");
* \endcode
*/
inline std::string LicenseServerConfig(const std::string& key_system) {
std::string ret = key_system;
std::string::size_type pos = 0;
while ((pos = ret.find('.', pos)) != std::string::npos) {
ret.insert(pos, "\\");
pos += 2;
}
return "drm.servers." + ret;
}
/** @} */
} // namespace shaka
#endif // SHAKA_EMBEDDED_UTILS_H_
<file_sep>/sample_xcode_project/build.sh
#!/bin/bash
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
set -e
# Work around a change to script environment variables in XCode 10.
export arch=$ARCHS
cd "$PROJECT_DIR/.."
# Get the PATH variable from outside of XCode, so that the scripts can find depot_tools
PATH=$(bash -l -c 'echo $PATH')
# Determine configuration options and framework path.
CONFIG_FLAGS="--ios --disable-demo --disable-tests"
if [[ $EFFECTIVE_PLATFORM_NAME == "-iphoneos" ]]; then
CONFIG_NAME="sample_xcode_project_ios"
CONFIG_FLAGS+=" --cpu arm64"
else
CONFIG_NAME="sample_xcode_project_ios_sim"
fi
if [[ $CONFIGURATION == "Release" ]]; then
CONFIG_NAME+="_release"
CONFIG_FLAGS+=" --release"
fi
echo "Using $CONFIG_NAME!"
# Create the framework.
if [[ ! -d "./out/$CONFIG_NAME" ]]; then
./configure --config-name "$CONFIG_NAME" $CONFIG_FLAGS
fi
./build.py --config-name "$CONFIG_NAME"
# Copy the correct framework into that path.
rm -rf ./sample_xcode_project/ShakaPlayerEmbedded.framework
mv ./out/"$CONFIG_NAME"/ShakaPlayerEmbedded.framework ./sample_xcode_project/ShakaPlayerEmbedded.framework
<file_sep>/shaka/src/js/mse/text_track.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/mse/text_track.h"
#include <algorithm>
#include "src/mapping/enum.h"
namespace shaka {
namespace js {
namespace mse {
TextTrack::TextTrack(TextTrackKind kind, const std::string& label,
const std::string& language)
: kind(kind),
label(label),
language(language),
mode_(TextTrackMode::Hidden),
mutex_("TextTrack") {
AddListenerField(EventType::CueChange, &on_cue_change);
}
TextTrack::~TextTrack() {}
void TextTrack::AddCue(RefPtr<VTTCue> cue) {
std::unique_lock<Mutex> lock(mutex_);
cues.emplace_back(cue);
if (mode_ != TextTrackMode::Disabled) {
// TODO: Only fire event if new cue will be displayed.
ScheduleEvent<events::Event>(EventType::CueChange);
}
}
void TextTrack::RemoveCue(RefPtr<VTTCue> cue) {
std::unique_lock<Mutex> lock(mutex_);
cues.erase(std::remove(cues.begin(), cues.end(), cue), cues.end());
if (mode_ != TextTrackMode::Disabled) {
// TODO: Only fire event if old cue was being displayed.
ScheduleEvent<events::Event>(EventType::CueChange);
}
}
void TextTrack::CheckForCueChange(double newTime, double oldTime) {
std::unique_lock<Mutex> lock(mutex_);
if (mode_ == TextTrackMode::Disabled)
return;
const double earlier = std::min(oldTime, newTime);
const double later = std::max(oldTime, newTime);
for (const auto& cue : cues) {
if ((cue->startTime() > earlier && cue->startTime() <= later) ||
(cue->endTime() > earlier && cue->endTime() <= later)) {
// A cue just began, or ended.
ScheduleEvent<events::Event>(EventType::CueChange);
return;
}
}
}
TextTrackMode TextTrack::mode() const {
std::unique_lock<Mutex> lock(mutex_);
return mode_;
}
void TextTrack::SetMode(TextTrackMode mode) {
std::unique_lock<Mutex> lock(mutex_);
mode_ = mode;
ScheduleEvent<events::Event>(EventType::CueChange);
}
TextTrackFactory::TextTrackFactory() {
AddReadOnlyProperty("kind", &TextTrack::kind);
AddReadOnlyProperty("label", &TextTrack::label);
AddReadOnlyProperty("language", &TextTrack::language);
AddReadOnlyProperty("id", &TextTrack::id);
AddReadOnlyProperty("cues", &TextTrack::cues);
AddGenericProperty("mode", &TextTrack::mode, &TextTrack::SetMode);
AddMemberFunction("addCue", &TextTrack::AddCue);
AddMemberFunction("removeCue", &TextTrack::RemoveCue);
AddListenerField(EventType::CueChange, &TextTrack::on_cue_change);
NotImplemented("activeCues");
}
} // namespace mse
} // namespace js
} // namespace shaka
<file_sep>/shaka/src/media/locked_frame_list.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/locked_frame_list.h"
namespace shaka {
namespace media {
LockedFrameList::Guard::Guard() : list_(nullptr), frame_(nullptr) {}
LockedFrameList::Guard::Guard(LockedFrameList* list, const BaseFrame* frame)
: list_(list), frame_(frame) {}
LockedFrameList::Guard::Guard(Guard&& other)
: list_(other.list_), frame_(other.frame_) {
other.list_ = nullptr;
other.frame_ = nullptr;
}
LockedFrameList::Guard::~Guard() {
Destroy();
}
LockedFrameList::Guard& LockedFrameList::Guard::operator=(Guard&& other) {
Destroy();
list_ = other.list_;
frame_ = other.frame_;
other.list_ = nullptr;
other.frame_ = nullptr;
return *this;
}
void LockedFrameList::Guard::Destroy() {
if (list_) {
list_->UnguardFrame(frame_);
list_ = nullptr;
frame_ = nullptr;
}
}
LockedFrameList::LockedFrameList()
: mutex_("LockedFrameList"), cond_("Frame delete") {}
LockedFrameList::~LockedFrameList() {
DCHECK(frames_.empty());
}
LockedFrameList::Guard LockedFrameList::GuardFrame(const BaseFrame* frame) {
if (!frame)
return Guard();
std::unique_lock<Mutex> lock(mutex_);
#ifndef NDEBUG
frames_.push_back({frame, std::this_thread::get_id()});
#else
frames_.push_back({frame});
#endif
return Guard(this, frame);
}
void LockedFrameList::WaitToDeleteFrames(
const std::unordered_set<const BaseFrame*>& frames) {
std::unique_lock<Mutex> lock(mutex_);
#ifndef NDEBUG
for (auto& locked_frame : frames_) {
if (frames.count(locked_frame.frame) > 0)
CHECK_NE(locked_frame.locked_thread, std::this_thread::get_id())
<< "Cannot delete a frame in used by this thread.";
}
#endif
auto has_locked = [&]() {
for (auto& locked_frame : frames_) {
if (frames.count(locked_frame.frame) > 0)
return true;
}
return false;
};
while (has_locked()) {
cond_.ResetAndWaitWhileUnlocked(lock);
}
}
void LockedFrameList::UnguardFrame(const BaseFrame* frame) {
std::unique_lock<Mutex> lock(mutex_);
for (auto it = frames_.begin(); it != frames_.end(); it++) {
if (it->frame == frame) {
frames_.erase(it);
cond_.SignalAllIfNotSet();
return;
}
}
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/tools/utils.py
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""A number of helper utilities for the scripts."""
from __future__ import print_function
import os
import platform
import re
import subprocess
import sys
ROOT_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..')
def LoadSubmodule(path):
"""Downloads the submodule at the given path."""
# If the directory already has a clone (e.g. someone ran git-clone there),
# then absorb the .git directory so we can use it.
subprocess.check_output(
['git', '-C', ROOT_DIR, 'submodule', 'absorbgitdirs', path])
# Then update the module.
subprocess.check_output(
['git', '-C', ROOT_DIR, 'submodule', 'update', '--init', '--force', path])
def GetSourceFiles(path):
"""Returns a list of all the source files that are at the given path."""
extensions = ['.cc', '.m', '.mm']
files = []
for root, _, cur_files in os.walk(path):
for f in cur_files:
if os.path.splitext(f)[1] in extensions:
files.append(os.path.join(root, f))
return files
def SymLink(source, dest):
"""Creates a symlink at |dest| pointing at |source|."""
if not os.path.exists(dest):
# If the link is invalid, the link will exist, but it does not |exists()|,
# so delete the original to try to fix it.
if os.path.islink(dest):
os.remove(dest)
# TODO: This only works on Unix platforms. Add support for Windows.
os.symlink(source, dest)
def ConfigPath(config):
"""Returns the path to the given config name."""
return os.path.join(ROOT_DIR, 'out', config) if config else '.'
def CheckConfigName(config_name):
"""Checks that the given config name is valid, exists if invalid."""
path = ConfigPath(config_name)
if (not os.path.exists(os.path.join(path, 'args.gn')) or
not os.path.exists(os.path.join(path, 'build.ninja'))):
if config_name:
print('Unable to find configuration for --config-name %r' % config_name,
file=sys.stderr)
else:
print('Not configured, either run ./configure or pass --config-name',
file=sys.stderr)
sys.exit(1)
def ExistsOnPath(cmd):
"""Returns whether the given executable exists on PATH."""
paths = os.getenv('PATH').split(os.pathsep)
return any(os.path.exists(os.path.join(d, cmd)) for d in paths)
def FindGn():
"""Returns the full path to the gn executable for this platform."""
platform_name = platform.uname()[0]
if platform_name == 'Linux':
return os.path.join(ROOT_DIR, 'buildtools', 'linux64', 'gn')
elif platform_name == 'Darwin':
return os.path.join(ROOT_DIR, 'buildtools', 'mac', 'gn')
elif platform_name == 'Windows' or 'CYGWIN' in platform_name:
return os.path.join(ROOT_DIR, 'buildtools', 'win', 'gn.exe')
else:
raise Exception('Unknown platform name ' + platform_name)
def GetGnArg(config_dir, var_name, is_string=True):
"""Gets the value of a GN build argument."""
val = subprocess.check_output([FindGn(), '--root=' + ROOT_DIR, 'args',
config_dir, '--list=' + var_name, '--short'])
# Examine the output line by line, since it might contain lines that are
# warnings.
for line in val.splitlines():
fmt = r'^%s = "(.*)"$' if is_string else r'^%s = (.*)$'
match = re.match(fmt % var_name, line)
if match:
return match.group(1)
return None
def GetGnVar(config_dir, var_name):
"""Gets the value of a GN variable."""
val = subprocess.check_output([FindGn(), '--root=' + ROOT_DIR, 'desc',
config_dir, '//:get_' + var_name,
'include_dirs']).strip()
# Look for after the signal, "//value:/\n", to skip past any warnings.
after = val.partition('//value:/\n')[2]
if after == '//EMPTY/':
return ''
elif after and after[:2] == '//':
return ROOT_DIR + after[1:]
else:
return after
<file_sep>/shaka/src/mapping/struct.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MAPPING_STRUCT_H_
#define SHAKA_EMBEDDED_MAPPING_STRUCT_H_
#include <memory>
#include <string>
#include <type_traits>
#include <vector>
#include "src/mapping/convert_js.h"
#include "src/mapping/generic_converter.h"
#include "src/mapping/js_wrappers.h"
#include "src/memory/heap_tracer.h"
#include "src/util/templates.h"
namespace shaka {
// Gets the class for |*this|. Normally to get a pointer to member, you
// have to use |&MyType::member|, this allows us to avoid passing the current
// type name to the macro |&THIS_TYPE::member|.
#define THIS_TYPE std::decay<decltype(*this)>::type
#define ADD_NAMED_DICT_FIELD(Type, member, name) \
Type member = CreateFieldConverter(name, &THIS_TYPE::member)
#define ADD_DICT_FIELD(type, member) ADD_NAMED_DICT_FIELD(type, member, #member)
class Struct;
namespace impl {
/**
* Defines a base class for a field converter. This represents a member of
* a struct and will convert the JavaScript object member to the respective
* C++ object member, and vice versa.
*
* There needs to be a non-templated base class because we store a vector of
* them in Struct and they have different (and only known in
* CreateFieldMember) types.
*/
class FieldConverterBase {
public:
virtual ~FieldConverterBase() {}
/**
* Search the given object for a property with the name of the field this
* is converting. If found, try to convert it and store in the field.
*/
virtual void SearchAndStore(Struct* dict, Handle<JsObject> object) = 0;
/** Stores the value of the field in the given object. */
virtual void AddToObject(const Struct* dict,
Handle<JsObject> object) const = 0;
/** Traces the member on the given object. */
virtual void Trace(const Struct* dict, memory::HeapTracer* tracer) const = 0;
};
/**
* The implementation of the field converter. This will convert a field of
* type Field that is defined on the type Parent.
*/
template <typename Parent, typename Field>
class FieldConverter : public FieldConverterBase {
public:
FieldConverter(const std::string& name, Field Parent::*member)
: name_(name), member_(member) {}
void SearchAndStore(Struct* dict, Handle<JsObject> object) override {
auto parent = static_cast<Parent*>(dict);
LocalVar<JsValue> member(GetMemberRaw(object, name_));
(void)FromJsValue(member, &(parent->*member_));
}
void AddToObject(const Struct* dict, Handle<JsObject> object) const override {
auto parent = static_cast<const Parent*>(dict);
LocalVar<JsValue> value(ToJsValue(parent->*member_));
SetMemberRaw(object, name_, value);
}
void Trace(const Struct* dict, memory::HeapTracer* tracer) const override {
auto parent = static_cast<const Parent*>(dict);
tracer->Trace(&(parent->*member_));
}
private:
std::string name_;
// Store as a pointer to member so if we are copied, we don't need to update
// the pointers (or make the type non-copyable).
Field Parent::*member_;
};
} // namespace impl
/**
* Defines the base class for struct objects. These are JavaScript
* objects that have specific members. Passing in any JavaScript object is
* valid and the respective members will be converted. Any extra members will
* not be copied.
*
* This is a forgiving type, namely it will try to convert each field if
* possible. If it is not possible, the field will be the default. However,
* if the argument is not an object, it is invalid. This is non-nullable, so
* to accept null, use optional<Struct>.
*
* In addition to deriving from this type, a Struct must also have a
* static |name| method. This is similar to BackingObjects, but you should NOT
* use DECLARE_TYPE_INFO. It is required to have a default (argument-less)
* constructor which can be implicit or user defined. If it is defined you
* CANNOT have member initialization (field assignments before the '{'), you
* MUST use assignment within the constructor body, otherwise the field will
* not be registered (see the macro above).
*/
class Struct : public GenericConverter, public memory::Traceable {
public:
Struct();
~Struct() override;
// Chromium style requires out-of-line copy/move constructors, even though
// they are still the default.
Struct(const Struct&);
Struct(Struct&&);
Struct& operator=(const Struct&);
Struct& operator=(Struct&&);
bool TryConvert(Handle<JsValue> value) override;
ReturnVal<JsValue> ToJsValue() const override;
void Trace(memory::HeapTracer* tracer) const override;
protected:
template <typename Parent, typename Field>
Field CreateFieldConverter(const std::string& name, Field Parent::*field) {
static_assert(std::is_base_of<Struct, Parent>::value,
"Must be derived from Struct");
auto convert = new impl::FieldConverter<Parent, Field>(name, field);
converters_.emplace_back(convert);
return Field();
}
private:
std::vector<std::shared_ptr<impl::FieldConverterBase>> converters_;
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_MAPPING_STRUCT_H_
<file_sep>/shaka/src/memory/object_tracker.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/memory/object_tracker.h"
#include "src/core/js_manager_impl.h"
#include "src/mapping/backing_object.h"
#include "src/memory/heap_tracer.h"
#include "src/util/clock.h"
#include "src/util/utils.h"
namespace shaka {
namespace memory {
void ObjectTracker::RegisterObject(Traceable* object) {
std::unique_lock<Mutex> lock(mutex_);
DCHECK(objects_.count(object) == 0 || to_delete_.count(object) == 1);
objects_.emplace(object, 0u);
to_delete_.erase(object);
if (object->IsShortLived())
last_alive_time_.emplace(object, util::Clock::Instance.GetMonotonicTime());
}
void ObjectTracker::ForceAlive(const Traceable* ptr) {
std::unique_lock<Mutex> lock(mutex_);
tracer_->ForceAlive(ptr);
}
void ObjectTracker::AddRef(const Traceable* object) {
if (object) {
std::unique_lock<Mutex> lock(mutex_);
auto* key = const_cast<Traceable*>(object); // NOLINT
DCHECK_EQ(objects_.count(key), 1u);
objects_[key]++;
tracer_->ForceAlive(object);
}
}
void ObjectTracker::RemoveRef(const Traceable* object) {
if (object) {
std::unique_lock<Mutex> lock(mutex_);
auto* key = const_cast<Traceable*>(object); // NOLINT
DCHECK_EQ(objects_.count(key), 1u);
CHECK_GT(objects_[key], 0u);
objects_[key]--;
// Don't use IsShortLived() here since |object| may be an invalid pointer.
// During Dispose(), objects may be destroyed with existing references to
// them. This means that |object| may be an invalid pointer.
if (last_alive_time_.count(key) > 0)
last_alive_time_[key] = util::Clock::Instance.GetMonotonicTime();
}
}
std::unordered_set<const Traceable*> ObjectTracker::GetAliveObjects() const {
std::unique_lock<Mutex> lock(mutex_);
std::unordered_set<const Traceable*> ret;
ret.reserve(objects_.size() + 1);
ret.insert(JsManagerImpl::InstanceOrNull());
for (auto& pair : objects_) {
if (pair.second != 0 || IsJsAlive(pair.first))
ret.insert(pair.first);
}
return ret;
}
void ObjectTracker::FreeDeadObjects(
const std::unordered_set<const Traceable*>& alive) {
std::unique_lock<Mutex> lock(mutex_);
std::unordered_set<Traceable*> to_delete;
to_delete.reserve(objects_.size());
for (auto pair : objects_) {
// |alive| also contains objects that have a non-zero ref count. But we
// need to check against our ref count also to ensure new objects that
// are created while the GC is running are not deleted.
if (pair.second == 0u && alive.count(pair.first) == 0 &&
!IsJsAlive(pair.first)) {
to_delete.insert(pair.first);
}
}
to_delete_ = to_delete;
DestroyObjects(to_delete, &lock);
}
ObjectTracker::ObjectTracker()
: tracer_(new HeapTracer()), mutex_("ObjectTracker") {}
ObjectTracker::~ObjectTracker() {
CHECK(objects_.empty());
}
void ObjectTracker::UnregisterAllObjects() {
std::unique_lock<Mutex> lock(mutex_);
last_alive_time_.clear();
objects_.clear();
}
bool ObjectTracker::IsJsAlive(Traceable* object) const {
const uint64_t now = util::Clock::Instance.GetMonotonicTime();
if (object->IsShortLived()) {
if (last_alive_time_.count(object) == 0)
return false;
return last_alive_time_.at(object) + Traceable::kShortLiveDurationMs > now;
}
return object->IsRootedAlive();
}
uint32_t ObjectTracker::GetRefCount(Traceable* object) const {
std::unique_lock<Mutex> lock(mutex_);
DCHECK_EQ(1u, objects_.count(object));
return objects_.at(object);
}
std::vector<const Traceable*> ObjectTracker::GetAllObjects() const {
std::unique_lock<Mutex> lock(mutex_);
std::vector<const Traceable*> ret;
ret.reserve(objects_.size() + 1);
ret.push_back(JsManagerImpl::InstanceOrNull());
for (auto& pair : objects_)
ret.push_back(pair.first);
return ret;
}
void ObjectTracker::Dispose() {
std::unique_lock<Mutex> lock(mutex_);
while (!objects_.empty()) {
std::unordered_set<Traceable*> to_delete;
for (auto& pair : objects_)
to_delete.insert(pair.first);
to_delete_ = to_delete;
DestroyObjects(to_delete, &lock);
}
}
void ObjectTracker::DestroyObjects(
const std::unordered_set<Traceable*>& to_delete,
std::unique_lock<Mutex>* lock) {
DCHECK(lock->owns_lock());
{
util::Unlocker<Mutex> unlock(lock);
// Don't hold lock so destructor can call AddRef.
for (Traceable* item : to_delete)
delete item;
}
VLOG(1) << "Deleted " << to_delete.size() << " object(s).";
// Don't remove elements from |objects_| until after the destructor so the
// destructor can call AddRef.
for (auto it = objects_.begin(); it != objects_.end();) {
if (to_delete_.count(it->first) > 0) {
last_alive_time_.erase(it->first);
it = objects_.erase(it);
} else {
it++;
}
}
}
} // namespace memory
} // namespace shaka
<file_sep>/shaka/include/shaka/text_track.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_TEXT_TRACK_H_
#define SHAKA_EMBEDDED_TEXT_TRACK_H_
#include <functional>
#include <memory>
#include <vector>
#include "macros.h"
#include "vtt_cue.h"
namespace shaka {
namespace js {
namespace mse {
class TextTrack;
} // namespace mse
} // namespace js
/**
* Represents the type of the text track.
* @see https://html.spec.whatwg.org/multipage/media.html#text-track-kind
* @ingroup player
*/
enum class TextTrackKind {
/**
* The track defines subtitles.
*/
Subtitles,
/**
* The text track defines dialogue and sound effects, for the deaf.
*/
Captions,
/**
* The text track defines a textual description of the video, for the blind.
*/
Descriptions,
/**
* The text track defines chapter titles, for navigation.
*/
Chapters,
/**
* The text track defines content for use by scripts, which will not be viewed
* by users.
*/
Metadata,
};
/**
* Represents the current state of the text track.
* @see https://html.spec.whatwg.org/multipage/media.html#text-track-mode
* @ingroup player
*/
enum class TextTrackMode {
/**
* The text track is currently disabled. The user agent is completely ignoring
* it.
*/
Disabled,
/**
* The text track is active, but the cues are not being displayed. Events will
* still fire as appropriate.
*/
Hidden,
/**
* The text track is enabled and visible.
*/
Showing,
};
/**
* This defines a text track that stores text cues.
* This is a wrapper over an internal type.
*
* @see https://html.spec.whatwg.org/multipage/media.html#the-track-element
* @ingroup player
*/
class SHAKA_EXPORT TextTrack final {
public:
TextTrack(TextTrack&&);
TextTrack(const TextTrack&) = delete;
~TextTrack();
TextTrack& operator=(const TextTrack&) = delete;
TextTrack& operator=(TextTrack&& other);
/** @return The kind of the text track. */
TextTrackKind kind();
/** Sets the kind of the text track. */
void SetKind(TextTrackKind kind);
/** @return The label string of the text track. */
std::string label();
/** Sets the label string of the text track. */
void SetLabel(const std::string label);
/** @return The language string of the text track. */
std::string language();
/** Sets the language string of the text track. */
void SetLanguage(const std::string language);
/** @return The id string of the text track. */
std::string id();
/** Sets the id string of the text track. */
void SetId(const std::string id);
/** @return The mode of the text track. */
TextTrackMode mode();
/** Sets the mode of the text track. */
void SetMode(TextTrackMode mode);
/**
* Adds an event listener to the text track, that listens for a cue change.
* There can only be one such listener per text track.
* This will be invoked on a background thread.
* @param callback The listener for the event.
*/
void SetCueChangeEventListener(std::function<void()> callback);
/**
* Removes the cue change event listener from the text track.
*/
void UnsetCueChangeEventListener();
/**
* @return A vector containing the list of cues in the text track.
* Note that this is a copy of the internal cue list, so adding or removing
* elements directly from the vector will not change the internal cue list.
* Modifying the contents of individual cues will work, on the other hand.
* The cues will remain in memory until the video is unloaded.
*/
std::vector<VTTCue*> cues();
/** Adds a copy of the provided cue to the list of cues in the text track. */
void AddCue(const VTTCue& cue);
/**
* Removes an element from the list of cues in the text track.
* Note that the provided cue has to be a cue retrieved from the cues()
* method; a shaka::VTTCue object will not be valid otherwise, even if it
* has been added with AddCue.
*/
void RemoveCue(VTTCue* cue);
private:
class Impl;
std::unique_ptr<Impl> impl_;
friend class Video;
TextTrack(js::mse::TextTrack* inner);
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_TEXT_TRACK_H_
<file_sep>/shaka/src/media/media_utils.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_MEDIA_UTILS_H_
#define SHAKA_EMBEDDED_MEDIA_MEDIA_UTILS_H_
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include "src/js/js_error.h"
#include "src/media/types.h"
#include "src/util/utils.h"
namespace shaka {
namespace media {
/**
* Parses a MIME type string into the type, subtype, and parameters.
* e.g.: "video/mp4; codecs=vp9"
*
* @param source The MIME string to parse.
* @param type [OUT] Where to put the type (e.g. 'video').
* @param subtype [OUT] Where to put the subtype (e.g. 'mp4').
* @param params [OUT] Where to put a map of parameters.
* @returns True on success, false on parsing errors.
*/
bool ParseMimeType(const std::string& source, std::string* type,
std::string* subtype,
std::unordered_map<std::string, std::string>* params);
/** @return Whether the given container and codec are supported. */
bool IsTypeSupported(const std::string& container, const std::string& codecs,
int width, int height);
/**
* Parses the given MIME type and checks whether it is supported.
* @param mime_type The MIME type to parse.
* @param source_type [OUT] Where to put the MIME's source type.
* @param container [OUT] Where to put the MIME's media container type.
* @param codec [OUT] Where to put the MIME's media codec type.
* @return True on success, false on parse error or unsupported.
*/
bool ParseMimeAndCheckSupported(const std::string& mime_type,
SourceType* source_type, std::string* container,
std::string* codec);
/** @return The container converted to the name FFmpeg expects. */
std::string NormalizeContainer(const std::string& container);
/** @return The codec converted to the name FFmpeg expects. */
std::string NormalizeCodec(const std::string& codec);
/**
* Returns the buffered ranges that represent the regions that are buffered in
* all of the given sources.
*
* Note this doesn't account for key frames, so this may not represent the
* actual playable regions.
*/
BufferedRanges IntersectionOfBufferedRanges(
const std::vector<BufferedRanges>& sources);
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_MEDIA_UTILS_H_
<file_sep>/shaka/test/src/media/locked_frame_list_unittest.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/locked_frame_list.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
namespace shaka {
namespace media {
namespace {
std::unique_ptr<BaseFrame> MakeFrame() {
return std::unique_ptr<BaseFrame>(new BaseFrame(0, 0, 1, true));
}
} // namespace
using testing::InSequence;
using testing::MockFunction;
TEST(LockedFrameListTest, CanGuardFrames) {
std::unique_ptr<BaseFrame> frame = MakeFrame();
LockedFrameList list;
auto guard = list.GuardFrame(frame.get());
EXPECT_EQ(guard.get(), frame.get());
}
TEST(LockedFrameListTest, WillWaitForDelete) {
MockFunction<void(int)> task;
{
InSequence seq;
EXPECT_CALL(task, Call(1)).Times(1);
EXPECT_CALL(task, Call(10)).Times(1);
EXPECT_CALL(task, Call(11)).Times(1);
EXPECT_CALL(task, Call(2)).Times(1);
EXPECT_CALL(task, Call(12)).Times(1);
}
std::unique_ptr<BaseFrame> frame1 = MakeFrame();
std::unique_ptr<BaseFrame> frame2 = MakeFrame();
LockedFrameList list;
std::mutex mutex; // Protects the frames, similar to FrameBuffer.
ThreadEvent<void> delete_start("");
ThreadEvent<void> use_frame("");
auto get_guard = [&]() {
std::unique_lock<std::mutex> lock(mutex);
return list.GuardFrame(frame1.get());
};
std::thread user([&]() {
LockedFrameList::Guard guard = get_guard();
task.Call(1);
delete_start.SignalAll();
use_frame.GetValue();
usleep(2500);
task.Call(2);
});
std::thread deleter([&]() {
delete_start.GetValue();
std::unique_lock<std::mutex> lock(mutex);
task.Call(10);
// Should not have to wait for unrelated frames.
list.WaitToDeleteFrames({frame2.get()});
task.Call(11);
// Should have to wait for locked frame.
use_frame.SignalAll();
list.WaitToDeleteFrames({frame1.get()});
task.Call(12);
});
user.join();
deleter.join();
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/include/shaka/sdl_frame_drawer.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_SDL_FRAME_DRAWER_H_
#define SHAKA_EMBEDDED_SDL_FRAME_DRAWER_H_
#include <SDL2/SDL.h>
#include <memory>
#include "frame.h"
#include "macros.h"
namespace shaka {
/**
* A helper class that is used to convert Shaka Embedded Frame objects into an
* SDL texture.
*
* @ingroup utils
*/
class SHAKA_EXPORT SdlFrameDrawer final {
public:
SdlFrameDrawer();
SdlFrameDrawer(const SdlFrameDrawer&) = delete;
SdlFrameDrawer(SdlFrameDrawer&&);
~SdlFrameDrawer();
SdlFrameDrawer& operator=(const SdlFrameDrawer&) = delete;
SdlFrameDrawer& operator=(SdlFrameDrawer&&);
/**
* Sets the renderer used to create textures. This MUST be called at least
* once before calling Draw. This can be changed at any time, but will
* invalidate any existing textures.
*/
void SetRenderer(SDL_Renderer* renderer);
/**
* Draws the given frame onto a texture. This may invalidate any existing
* textures.
*
* @param frame The frame to draw.
* @return The created texture, or nullptr on error.
*/
SDL_Texture* Draw(Frame* frame);
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_SDL_FRAME_DRAWER_H_
<file_sep>/shaka/src/util/shared_lock.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_UTIL_SHARED_LOCK_H_
#define SHAKA_EMBEDDED_UTIL_SHARED_LOCK_H_
#include <condition_variable>
#include <mutex>
#include <thread>
#include <unordered_set>
#include <utility>
#include "src/util/macros.h"
namespace shaka {
namespace util {
/**
* A simple implementation of a reader-writer mutex where:
* - It doesn't handle any scheduling, so it will likely be inefficient.
* - It is not a recursive mutex, so you cannot use lock() or lock_shared() if
* this thread already holds a lock.
* - It cannot use both lock() and lock_shared() on the same thread at the same
* time.
*
* You can use std::unique_lock<T> to help locking this in exclusive mode. For
* example:
*
* \code{cpp}
* std::unique_lock<shared_mutex> lock(mutex);
* // In exclusive mode.
* \endcode
*
* Or you can use shared_lock to lock in shared mode:
*
* \code{cpp}
* shared_lock<shared_mutex> lock(mutex);
* // In shared mode.
* \endcode
*
* This implements the Lockable, Mutex, and SharedMutex concepts.
*/
class shared_mutex {
public:
shared_mutex();
~shared_mutex();
NON_COPYABLE_OR_MOVABLE_TYPE(shared_mutex);
/** Locks the mutex for exclusive access. */
void lock() {
maybe_try_lock(/* only_try */ false);
}
/** Tries to lock the mutex for exclusive access in a non-blocking way. */
bool try_lock() {
return maybe_try_lock(/* only_try */ true);
}
/** Unlocks the mutex from exclusive access. */
void unlock();
/** Locks the mutex for shared access. */
void lock_shared() {
maybe_try_lock_shared(/* only_try */ false);
}
/** Tries to lock the mutex for shared access in a non-blocking way. */
bool try_lock_shared() {
return maybe_try_lock_shared(/* only_try */ true);
}
/** Unlocks the mutex from shared access. */
void unlock_shared();
private:
bool maybe_try_lock(bool only_try);
bool maybe_try_lock_shared(bool only_try);
std::mutex mutex_;
std::condition_variable signal_;
uint32_t shared_count_ = 0;
bool is_exclusive_ = false;
bool is_exclusive_waiting_ = false;
};
/**
* Similar to std::unique_lock, this locks the given shared mutex in the shared
* mode.
*/
template <typename Mutex>
class shared_lock {
public:
using mutex_type = Mutex;
shared_lock() : mutex_(nullptr), owns_lock_(false) {}
explicit shared_lock(mutex_type& mutex) : mutex_(&mutex) {
mutex_->lock_shared();
owns_lock_ = true;
}
shared_lock(shared_lock&& other)
: mutex_(other.mutex_), owns_lock_(other.owns_lock_) {
other.mutex_ = nullptr;
other.owns_lock_ = false;
}
~shared_lock() {
if (owns_lock_)
mutex_->unlock_shared();
}
NON_COPYABLE_TYPE(shared_lock);
shared_lock& operator=(shared_lock&& other) {
other.swap(*this);
return *this;
}
operator bool() const { return owns_lock_; }
bool owns_lock() const { return owns_lock_; }
mutex_type* mutex() const { return mutex_; }
void swap(shared_lock& other) {
swap(mutex_, other.mutex_);
swap(owns_lock_, other.owns_lock_);
}
mutex_type* release() {
Mutex* ret = mutex_;
mutex_ = nullptr;
owns_lock_ = false;
return ret;
}
private:
mutex_type* mutex_;
bool owns_lock_;
};
template <typename Mutex>
void swap(shared_lock<Mutex>& a, shared_lock<Mutex>& b) {
a.swap(b);
}
} // namespace util
} // namespace shaka
#endif // SHAKA_EMBEDDED_UTIL_SHARED_LOCK_H_
<file_sep>/shaka/src/public/js_manager.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "shaka/js_manager.h"
#include "src/core/js_manager_impl.h"
namespace shaka {
JsManager::JsManager() : impl_(new JsManagerImpl(StartupOptions())) {}
JsManager::JsManager(const StartupOptions& options)
: impl_(new JsManagerImpl(options)) {}
JsManager::~JsManager() {}
JsManager::JsManager(JsManager&&) = default;
JsManager& JsManager::operator=(JsManager&&) = default;
void JsManager::Stop() {
impl_->Stop();
}
void JsManager::WaitUntilFinished() {
impl_->WaitUntilFinished();
}
AsyncResults<void> JsManager::RunScript(const std::string& path) {
auto run_future = impl_->RunScript(path)->future();
// This creates a std::future that will invoke the given method when the
// wait()/get() method is called. This exists to convert the
// std::future<bool> that is returned into a
// std::future<variant<monostate, Error>> that AsyncResults expects.
// TODO: Find a better way to do this.
auto future = std::async(
std::launch ::deferred, [run_future]() -> variant<monostate, Error> {
if (run_future.get())
return monostate();
return Error(ErrorType::NonShakaError, "Unknown script error");
});
return future.share();
}
} // namespace shaka
<file_sep>/shaka/src/mapping/backing_object.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MAPPING_BACKING_OBJECT_H_
#define SHAKA_EMBEDDED_MAPPING_BACKING_OBJECT_H_
#include <glog/logging.h>
#include <string>
#include "src/mapping/js_wrappers.h"
#include "src/mapping/weak_js_ptr.h"
#include "src/memory/heap_tracer.h"
namespace shaka {
namespace memory {
class HeapTracer;
class ObjectTracker;
} // namespace memory
namespace js {
class Debug;
} // namespace js
class BackingObjectFactoryBase;
#define DECLARE_TYPE_INFO(type) \
public: \
static std::string name() { \
return #type; \
} \
\
protected: \
~type() override; \
\
public: \
::shaka::BackingObjectFactoryBase* factory() const override
/**
* A base type for objects exposed to JavaScript. This is the backing type for
* a JavaScript object. This contains a weak pointer to the object that it
* backs.
*/
class BackingObject : public memory::Traceable {
public:
BackingObject();
/** The number of internal fields in a wrapper object. */
static constexpr const size_t kInternalFieldCount = 2;
// In WebKit, it says that MSVC requires delete[] for exported classes.
// https://goo.gl/eXrvjn
// Disable new[] and delete[] since we use 'delete' in the ObjectTracker to
// delete objects and that does not work with arrays.
static void* operator new[](size_t size) = delete;
static void operator delete[](void*) = delete;
void Trace(memory::HeapTracer* tracer) const override;
bool IsRootedAlive() const override;
/** @return The name of the type. */
std::string name() const;
/** @return the factory that created this object. */
virtual BackingObjectFactoryBase* factory() const = 0;
/** @return Whether this object derives from the type with the given name. */
bool DerivedFrom(const std::string& base);
/**
* Gets the JavaScript object that represents this instance. It is only
* valid to call this method on the Event thread.
*/
ReturnVal<JsValue> JsThis();
/** Sets the JavaScript instance that represents this object. */
void SetJsThis(Handle<JsObject> this_);
protected:
friend class memory::ObjectTracker;
~BackingObject() override;
private:
WeakJsPtr<JsObject> js_this_;
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_MAPPING_BACKING_OBJECT_H_
<file_sep>/shaka/src/js/events/event_target.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/events/event_target.h"
#include <vector>
#include "src/js/js_error.h"
#include "src/memory/heap_tracer.h"
namespace shaka {
namespace js {
namespace events {
EventTarget::EventTarget() : is_dispatching_(false) {}
// \cond Doxygen_Skip
EventTarget::~EventTarget() {}
// \endcond Doxygen_Skip
void EventTarget::Trace(memory::HeapTracer* tracer) const {
BackingObject::Trace(tracer);
for (auto& listener : listeners_) {
tracer->Trace(&listener.callback_);
}
for (auto& pair : on_listeners_) {
tracer->Trace(pair.second);
}
}
void EventTarget::AddEventListener(const std::string& type, Listener callback) {
if (FindListener(callback, type) != listeners_.end())
return;
listeners_.emplace_back(callback, type);
}
void EventTarget::SetCppEventListener(EventType type,
std::function<void()> callback) {
cpp_listeners_.emplace(to_string(type), callback);
}
void EventTarget::RemoveEventListener(const std::string& type,
Listener callback) {
auto it = FindListener(callback, type);
if (it != listeners_.end()) {
if (is_dispatching_) {
it->should_remove_ = true;
} else {
listeners_.erase(it);
}
}
}
void EventTarget::UnsetCppEventListener(EventType type) {
cpp_listeners_.erase(to_string(type));
}
ExceptionOr<bool> EventTarget::DispatchEvent(RefPtr<Event> event) {
if (is_dispatching_) {
return JsError::DOMException(InvalidStateError,
"Already dispatching events.");
}
is_dispatching_ = true;
event->target = this;
// Shaka Player does not use capturing or bubbling events, so we only care
// about the initial target. Normally we would need to construct a path
// going up the DOM.
event->event_phase = Event::AT_TARGET;
InvokeListeners(event);
// Now that we are done firing events, remove the event listeners that have
// been marked for removal.
for (auto it = listeners_.begin(); it != listeners_.end();) {
if (it->should_remove_)
it = listeners_.erase(it);
else
++it;
}
is_dispatching_ = false;
event->event_phase = Event::NONE;
event->current_target = nullptr;
return !event->default_prevented;
}
EventTarget::ListenerInfo::ListenerInfo(Listener listener,
const std::string& type)
: callback_(listener), type_(type), should_remove_(false) {}
EventTarget::ListenerInfo::~ListenerInfo() {}
void EventTarget::InvokeListeners(RefPtr<Event> event) {
if (event->is_stopped())
return;
event->current_target = this;
// First, evoke the cpp callbacks. They have priority, due to being internal.
// It is assumed that they will not change during this process.
if (cpp_listeners_.count(event->type) > 0)
cpp_listeners_.at(event->type)();
// Invoke the on-event listeners second. This is slightly different from
// Chrome which will invoke it in the order it was set (i.e. calling
// addEventListener then setting onerror will call callbacks in that order).
auto on_iter = on_listeners_.find(event->type);
if (on_iter != on_listeners_.end()) {
// Note that even though it exists in the map does not mean the field is
// set.
if (on_iter->second->has_value()) {
on_iter->second->value().CallWithThis(this, event);
if (event->is_immediate_stopped()) {
return;
}
}
}
if (listeners_.empty())
return;
// Store the end of the list. Elements are added to the end of the list so
// we will not fire events added after this one. This needs to be inclusive
// since the pseudo-value for end() may not remain valid after insertions.
auto end = --listeners_.end();
// We need to process all items in the range [begin, end]. We cannot use a
// for loop because we still need to process the |end| element. So we process
// |it|, then increment, then compare the old value to |end|. Note that
// since |end| is valid, the last increment is still valid.
auto it = listeners_.begin();
do {
if (it->should_remove_)
continue;
if (it->type_ == event->type && it->callback_.has_value()) {
it->callback_->CallWithThis(this, event);
}
if (event->is_immediate_stopped())
break;
} while ((it++) != end);
}
std::list<EventTarget::ListenerInfo>::iterator EventTarget::FindListener(
const Listener& callback, const std::string& type) {
auto it = listeners_.begin();
for (; it != listeners_.end(); it++) {
if (it->type_ == type && callback == it->callback_) {
break;
}
}
return it;
}
EventTargetFactory::EventTargetFactory() {
AddMemberFunction("addEventListener", &EventTarget::AddEventListener);
AddMemberFunction("removeEventListener", &EventTarget::RemoveEventListener);
AddMemberFunction("dispatchEvent", &EventTarget::DispatchEvent);
}
} // namespace events
} // namespace js
} // namespace shaka
<file_sep>/shaka/src/js/mse/media_source.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/mse/media_source.h"
#include <glog/logging.h>
#include <cmath>
#include <functional>
#include <utility>
#include "src/js/events/event.h"
#include "src/js/events/event_names.h"
#include "src/js/events/media_encrypted_event.h"
#include "src/js/mse/source_buffer.h"
#include "src/js/mse/video_element.h"
#include "src/media/media_utils.h"
#include "src/util/macros.h"
namespace shaka {
namespace js {
namespace mse {
namespace {
/** @returns A random blob URL using a randomly generated UUID. */
std::string RandomUrl() {
unsigned char bytes[16];
// Use pseudo-random since we don't need cryptographic security.
for (unsigned char& chr : bytes)
chr = static_cast<unsigned char>(rand()); // NOLINT
// Since it's random, don't care about host byte order.
#define _2_BYTES_AT(b) (*reinterpret_cast<uint16_t*>(b))
#define _4_BYTES_AT(b) (*reinterpret_cast<uint32_t*>(b))
return util::StringPrintf(
"blob:%08x-%04x-%04x-%04x-%08x%04x", _4_BYTES_AT(bytes),
_2_BYTES_AT(bytes + 4),
// Only output 3 hex chars, the first is the UUID version (4, Random).
(_2_BYTES_AT(bytes + 6) & 0xfff) | 0x4000,
// Drop the two high bits to set the variant (0b10xx).
(_2_BYTES_AT(bytes + 8) & 0x3fff) | 0x8000, _4_BYTES_AT(bytes + 10),
_2_BYTES_AT(bytes + 14));
}
} // namespace
using namespace std::placeholders; // NOLINT
BEGIN_ALLOW_COMPLEX_STATICS
std::unordered_map<std::string, Member<MediaSource>>
MediaSource::media_sources_;
END_ALLOW_COMPLEX_STATICS
MediaSource::MediaSource()
: ready_state(MediaSourceReadyState::CLOSED),
url(RandomUrl()),
controller_(std::bind(&MediaSource::OnMediaError, this, _1, _2),
std::bind(&MediaSource::OnWaitingForKey, this),
std::bind(&MediaSource::OnEncrypted, this, _1, _2),
std::bind(&MediaSource::OnReadyStateChanged, this, _1),
std::bind(&MediaSource::OnPipelineStatusChanged, this, _1)) {
AddListenerField(EventType::SourceOpen, &on_source_open);
AddListenerField(EventType::SourceEnded, &on_source_ended);
AddListenerField(EventType::SourceClose, &on_source_close);
DCHECK_EQ(0u, media_sources_.count(url));
media_sources_[url] = this;
}
// \cond Doxygen_Skip
MediaSource::~MediaSource() {
DCHECK_EQ(1u, media_sources_.count(url));
media_sources_.erase(url);
}
// \endcond Doxygen_Skip
// static
bool MediaSource::IsTypeSupported(const std::string& mime_type) {
std::string container;
std::string codec;
media::SourceType source_type;
return ParseMimeAndCheckSupported(mime_type, &source_type, &container,
&codec);
}
// static
RefPtr<MediaSource> MediaSource::FindMediaSource(const std::string& url) {
if (media_sources_.count(url) == 0)
return nullptr;
return media_sources_[url];
}
void MediaSource::Trace(memory::HeapTracer* tracer) const {
EventTarget::Trace(tracer);
for (auto& pair : source_buffers_)
tracer->Trace(&pair.second);
tracer->Trace(&video_element_);
}
ExceptionOr<RefPtr<SourceBuffer>> MediaSource::AddSourceBuffer(
const std::string& type) {
media::SourceType source_type;
const media::Status status = controller_.AddSource(type, &source_type);
if (status == media::Status::NotSupported) {
return JsError::DOMException(
NotSupportedError, "The given type ('" + type + "') is unsupported.");
}
if (status == media::Status::NotAllowed) {
return JsError::DOMException(
NotSupportedError, "Cannot add any additional SourceBuffer objects.");
}
CHECK(status == media::Status::Success);
DCHECK_EQ(0u, source_buffers_.count(source_type));
DCHECK_NE(source_type, media::SourceType::Unknown);
return (source_buffers_[source_type] = new SourceBuffer(this, source_type));
}
ExceptionOr<void> MediaSource::EndOfStream(optional<std::string> error) {
if (ready_state != MediaSourceReadyState::OPEN) {
return JsError::DOMException(
InvalidStateError,
R"(Cannot call endOfStream() unless MediaSource is "open".)");
}
for (auto& pair : source_buffers_) {
if (pair.second->updating) {
return JsError::DOMException(
InvalidStateError,
"Cannot call endOfStream() when a SourceBuffer is updating.");
}
}
if (error.has_value()) {
return JsError::DOMException(
NotSupportedError,
"Calling endOfStream() with an argument is not supported.");
}
ready_state = MediaSourceReadyState::ENDED;
ScheduleEvent<events::Event>(EventType::SourceEnded);
controller_.EndOfStream();
return {};
}
double MediaSource::GetDuration() const {
return controller_.GetPipelineManager()->GetDuration();
}
ExceptionOr<void> MediaSource::SetDuration(double duration) {
if (std::isnan(duration))
return JsError::TypeError("Cannot set duration to NaN.");
if (ready_state != MediaSourceReadyState::OPEN) {
return JsError::DOMException(
InvalidStateError,
R"(Cannot change duration unless MediaSource is "open".)");
}
for (auto& pair : source_buffers_) {
if (pair.second->updating) {
return JsError::DOMException(
InvalidStateError,
"Cannot change duration when a SourceBuffer is updating.");
}
}
controller_.GetPipelineManager()->SetDuration(duration);
return {};
}
void MediaSource::OpenMediaSource(RefPtr<HTMLVideoElement> video) {
DCHECK(ready_state == MediaSourceReadyState::CLOSED)
<< "MediaSource already attached to a <video> element.";
ready_state = MediaSourceReadyState::OPEN;
video_element_ = video;
ScheduleEvent<events::Event>(EventType::SourceOpen);
}
void MediaSource::CloseMediaSource() {
DCHECK(ready_state != MediaSourceReadyState::CLOSED)
<< "MediaSource not attached to a <video> element.";
ready_state = MediaSourceReadyState::CLOSED;
video_element_.reset();
controller_.Reset();
for (auto& pair : source_buffers_) {
pair.second->CloseMediaSource();
}
source_buffers_.clear();
ScheduleEvent<events::Event>(EventType::SourceClose);
}
void MediaSource::OnReadyStateChanged(media::MediaReadyState ready_state) {
if (video_element_)
video_element_->OnReadyStateChanged(ready_state);
}
void MediaSource::OnPipelineStatusChanged(media::PipelineStatus status) {
if (video_element_)
video_element_->OnPipelineStatusChanged(status);
}
void MediaSource::OnMediaError(media::SourceType source, media::Status error) {
if (video_element_)
video_element_->OnMediaError(source, error);
}
void MediaSource::OnWaitingForKey() {
if (video_element_)
video_element_->ScheduleEvent<events::Event>(EventType::WaitingForKey);
}
void MediaSource::OnEncrypted(eme::MediaKeyInitDataType init_data_type,
ByteBuffer init_data) {
if (video_element_) {
video_element_->ScheduleEvent<events::MediaEncryptedEvent>(
EventType::Encrypted, init_data_type, std::move(init_data));
}
}
MediaSourceFactory::MediaSourceFactory() {
AddListenerField(EventType::SourceOpen, &MediaSource::on_source_open);
AddListenerField(EventType::SourceEnded, &MediaSource::on_source_ended);
AddListenerField(EventType::SourceClose, &MediaSource::on_source_close);
AddReadOnlyProperty("readyState", &MediaSource::ready_state);
AddGenericProperty("duration", &MediaSource::GetDuration,
&MediaSource::SetDuration);
AddMemberFunction("addSourceBuffer", &MediaSource::AddSourceBuffer);
AddMemberFunction("endOfStream", &MediaSource::EndOfStream);
AddStaticFunction("isTypeSupported", &MediaSource::IsTypeSupported);
NotImplemented("activeSourceBuffers");
NotImplemented("clearLiveSeekableRange");
NotImplemented("removeSourceBuffer");
NotImplemented("setLiveSeekableRange");
NotImplemented("sourceBuffers");
}
} // namespace mse
} // namespace js
} // namespace shaka
<file_sep>/shaka/src/media/audio_renderer.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_AUDIO_RENDERER_H_
#define SHAKA_EMBEDDED_MEDIA_AUDIO_RENDERER_H_
#include <SDL2/SDL.h>
#include <functional>
#include "src/debug/mutex.h"
#include "src/debug/thread.h"
#include "src/debug/thread_event.h"
#include "src/media/renderer.h"
#include "src/media/stream.h"
#include "src/util/macros.h"
struct SwrContext;
namespace shaka {
namespace media {
class FFmpegDecodedFrame;
/**
* Defines a renderer that draws audio frames to the audio device.
*/
class AudioRenderer : public Renderer {
public:
AudioRenderer(std::function<double()> get_time,
std::function<double()> get_playback_rate, Stream* stream);
~AudioRenderer() override;
// TODO: Allow setting different output device.
NON_COPYABLE_OR_MOVABLE_TYPE(AudioRenderer);
void OnSeek() override;
void OnSeekDone() override;
/** Sets the volume of the audio. */
void SetVolume(double volume);
private:
void ThreadMain();
bool InitDevice(const FFmpegDecodedFrame* frame);
static void OnAudioCallback(void*, uint8_t*, int);
void AudioCallback(uint8_t* data, int size);
const std::function<double()> get_time_;
const std::function<double()> get_playback_rate_;
Stream* const stream_;
mutable Mutex mutex_;
ThreadEvent<void> on_reset_;
SDL_AudioSpec audio_spec_;
SDL_AudioSpec obtained_audio_spec_;
SDL_AudioDeviceID audio_device_;
SwrContext* swr_ctx_;
double cur_time_;
double volume_;
bool shutdown_ : 1;
bool need_reset_ : 1;
bool is_seeking_ : 1;
Thread thread_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_AUDIO_RENDERER_H_
<file_sep>/shaka/src/mapping/v8/js_wrappers.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/mapping/js_wrappers.h"
#include "src/mapping/backing_object.h"
#include "src/mapping/convert_js.h"
#include "src/util/file_system.h"
namespace shaka {
namespace {
class StaticExternalResource
: public v8::String::ExternalOneByteStringResource {
public:
StaticExternalResource(const uint8_t* data, size_t data_size)
: data_(data), data_size_(data_size) {}
NON_COPYABLE_OR_MOVABLE_TYPE(StaticExternalResource);
const char* data() const override {
return reinterpret_cast<const char*>(data_);
}
size_t length() const override {
return data_size_;
}
protected:
void Dispose() override {
delete this;
}
private:
~StaticExternalResource() override {}
const uint8_t* data_;
size_t data_size_;
};
v8::Local<v8::String> MakeExternalString(const uint8_t* data,
size_t data_size) {
#ifndef NDEBUG
for (size_t i = 0; i < data_size; i++)
CHECK_LT(data[i], 0x80) << "External string must be ASCII";
#endif
auto* res = new StaticExternalResource(data, data_size);
auto temp = v8::String::NewExternalOneByte(GetIsolate(), res); // NOLINT
return temp.ToLocalChecked();
}
template <typename T>
ReturnVal<JsValue> GetMemberImpl(Handle<JsObject> object, T ind) {
v8::Isolate* isolate = GetIsolate();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::MaybeLocal<v8::Value> maybe_field = object->Get(context, ind);
v8::Local<v8::Value> field;
if (!maybe_field.ToLocal(&field))
return v8::Undefined(isolate);
return field;
}
template <typename T>
void SetMemberImpl(Handle<JsObject> object, T ind, Handle<JsValue> value) {
auto context = GetIsolate()->GetCurrentContext();
// Set returns Maybe<bool>, which is nothing on error.
CHECK(object->Set(context, ind, value).IsJust());
}
bool RunScriptImpl(const std::string& path, Handle<JsString> source) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
auto context = isolate->GetCurrentContext();
v8::HandleScope handle_scope(GetIsolate());
v8::ScriptOrigin origin(ToJsValue(path));
// Compile the script.
v8::TryCatch trycatch(isolate);
v8::MaybeLocal<v8::Script> maybe_script =
v8::Script::Compile(context, source, &origin);
v8::Local<v8::Script> script;
if (!maybe_script.ToLocal(&script) || script.IsEmpty()) {
LOG(ERROR) << "Error loading script " << path;
return false;
}
// Run the script. Run() returns the return value from the script, which
// will be empty if the script failed to execute.
if (script->Run(context).IsEmpty()) {
OnUncaughtException(trycatch.Exception(), false);
return false;
}
return true;
}
} // namespace
std::vector<std::string> GetMemberNames(Handle<JsObject> object) {
std::vector<std::string> names;
v8::Isolate* isolate = GetIsolate();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::MaybeLocal<v8::Array> maybe_field = object->GetOwnPropertyNames(context);
v8::Local<v8::Array> array;
if (maybe_field.ToLocal(&array)) {
for (size_t i = 0; i < array->Length(); i++) {
v8::Local<v8::Value> name = GetArrayIndexRaw(array, i);
names.push_back(ConvertToString(name));
}
}
return names;
}
ReturnVal<JsValue> GetMemberRaw(Handle<JsObject> object,
const std::string& name) {
return GetMemberImpl(object, JsStringFromUtf8(name));
}
ReturnVal<JsValue> GetArrayIndexRaw(Handle<JsObject> object, size_t index) {
return GetMemberImpl(object, index);
}
void SetMemberRaw(Handle<JsObject> object, const std::string& name,
Handle<JsValue> value) {
SetMemberImpl(object, JsStringFromUtf8(name), value);
}
void SetArrayIndexRaw(Handle<JsObject> object, size_t i,
Handle<JsValue> value) {
SetMemberImpl(object, i, value);
}
void SetGenericPropertyRaw(Handle<JsObject> object, const std::string& name,
Handle<JsFunction> getter,
Handle<JsFunction> setter) {
object->SetAccessorProperty(JsStringFromUtf8(name), getter, setter);
}
bool InvokeConstructor(Handle<JsFunction> ctor, int argc,
LocalVar<JsValue>* argv,
LocalVar<JsValue>* result_or_except) {
v8::Isolate* isolate = GetIsolate();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::EscapableHandleScope handles(isolate);
v8::TryCatch trycatch(isolate);
v8::MaybeLocal<v8::Object> result = ctor->NewInstance(context, argc, argv);
if (result.IsEmpty()) {
*result_or_except = handles.Escape(trycatch.Exception());
return false;
}
*result_or_except = handles.Escape(result.ToLocalChecked());
return true;
}
bool InvokeMethod(Handle<JsFunction> method, Handle<JsObject> that, int argc,
LocalVar<JsValue>* argv,
LocalVar<JsValue>* result_or_except) {
v8::Isolate* isolate = GetIsolate();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::EscapableHandleScope handles(isolate);
if (that.IsEmpty())
that = context->Global();
v8::TryCatch trycatch(isolate);
v8::MaybeLocal<v8::Value> result = method->Call(context, that, argc, argv);
if (result.IsEmpty()) {
*result_or_except = handles.Escape(trycatch.Exception());
return false;
}
*result_or_except = handles.Escape(result.ToLocalChecked());
return true;
}
std::string ConvertToString(Handle<JsValue> value) {
if (!value.IsEmpty() && value->IsSymbol()) {
LocalVar<v8::Value> name = value.As<v8::Symbol>()->Name();
return name.IsEmpty() || name->IsUndefined() ? "" : ConvertToString(name);
}
v8::String::Utf8Value str(value);
return std::string(*str, str.length());
}
ReturnVal<JsValue> WrapPointer(void* ptr) {
return v8::External::New(GetIsolate(), ptr);
}
void* MaybeUnwrapPointer(Handle<JsValue> value) {
if (value.IsEmpty() || !value->IsExternal())
return nullptr;
return value.As<v8::External>()->Value();
}
BackingObject* GetInternalPointer(Handle<JsValue> value) {
if (value.IsEmpty() || !value->IsObject())
return nullptr;
v8::Local<v8::Object> object = value.As<v8::Object>();
if (object->InternalFieldCount() != BackingObject::kInternalFieldCount)
return nullptr;
return reinterpret_cast<BackingObject*>(
object->GetAlignedPointerFromInternalField(0));
}
bool IsDerivedFrom(BackingObject* ptr, const std::string& name) {
return ptr ? ptr->DerivedFrom(name) : false;
}
bool RunScript(const std::string& path) {
util::FileSystem fs;
std::vector<uint8_t> source;
CHECK(fs.ReadFile(path, &source));
v8::Local<v8::String> code =
v8::String::NewFromUtf8(GetIsolate(),
reinterpret_cast<const char*>(source.data()),
v8::NewStringType::kNormal, source.size())
.ToLocalChecked();
return RunScriptImpl(path, code);
}
bool RunScript(const std::string& path, const uint8_t* data, size_t data_size) {
v8::Local<v8::String> source = MakeExternalString(data, data_size);
return RunScriptImpl(path, source);
}
ReturnVal<JsValue> ParseJsonString(const std::string& json) {
v8::Local<v8::String> source = MakeExternalString(
reinterpret_cast<const uint8_t*>(json.data()), json.size());
v8::MaybeLocal<v8::Value> value =
v8::JSON::Parse(GetIsolate()->GetCurrentContext(), source);
if (value.IsEmpty())
return {};
return value.ToLocalChecked();
}
ReturnVal<JsString> JsStringFromUtf8(const std::string& str) {
// NewStringType determines where to put the string.
// - kNormal is for "normal", short-lived strings.
// - kInternalized is for common strings and are cached (taking up more space)
// TODO: Investigate using kInternalized for property names which are static
// and may be common, Chromium has a v8AtomicString method for this.
return v8::String::NewFromUtf8(GetIsolate(), str.c_str(),
v8::NewStringType::kNormal, str.size())
.ToLocalChecked();
}
ReturnVal<JsValue> JsUndefined() {
return v8::Undefined(GetIsolate());
}
ReturnVal<JsValue> JsNull() {
return v8::Null(GetIsolate());
}
ReturnVal<JsObject> CreateArray(size_t length) {
return v8::Array::New(GetIsolate(), length);
}
ReturnVal<JsObject> CreateObject() {
return v8::Object::New(GetIsolate());
}
ReturnVal<JsMap> CreateMap() {
return v8::Map::New(GetIsolate());
}
void SetMapValue(Handle<JsMap> map, Handle<JsValue> key,
Handle<JsValue> value) {
LocalVar<v8::Context> ctx = GetIsolate()->GetCurrentContext();
CHECK(!map->Set(ctx, key, value).IsEmpty());
}
bool IsNullOrUndefined(Handle<JsValue> value) {
return value.IsEmpty() || value->IsNull() || value->IsUndefined();
}
bool IsObject(Handle<JsValue> value) {
return !value.IsEmpty() && value->IsObject();
}
bool IsBuiltInObject(Handle<JsObject> object) {
// This calls Object.prototype.toString, which will produce something like
// '[object Promise]' for built-in types.
v8::MaybeLocal<v8::String> to_string =
object->ObjectProtoToString(GetIsolate()->GetCurrentContext());
if (to_string.IsEmpty())
return false;
return ConvertToString(to_string.ToLocalChecked()) != "[object Object]";
}
JSValueType GetValueType(Handle<JsValue> value) {
if (value.IsEmpty())
return JSValueType::Unknown;
if (value->IsUndefined())
return JSValueType::Undefined;
if (value->IsNull())
return JSValueType::Null;
if (value->IsBoolean())
return JSValueType::Boolean;
if (value->IsNumber())
return JSValueType::Number;
if (value->IsString())
return JSValueType::String;
if (value->IsSymbol())
return JSValueType::Symbol;
if (value->IsFunction())
return JSValueType::Function;
if (value->IsArray())
return JSValueType::Array;
if (value->IsPromise())
return JSValueType::Promise;
if (value->IsBooleanObject())
return JSValueType::BooleanObject;
if (value->IsNumberObject())
return JSValueType::NumberObject;
if (value->IsStringObject())
return JSValueType::StringObject;
if (value->IsArrayBuffer())
return JSValueType::ArrayBuffer;
if (value->IsInt8Array())
return JSValueType::Int8Array;
if (value->IsUint8Array())
return JSValueType::Uint8Array;
if (value->IsUint8ClampedArray())
return JSValueType::Uint8ClampedArray;
if (value->IsInt16Array())
return JSValueType::Int16Array;
if (value->IsUint16Array())
return JSValueType::Uint16Array;
if (value->IsInt32Array())
return JSValueType::Int32Array;
if (value->IsUint32Array())
return JSValueType::Uint32Array;
if (value->IsFloat32Array())
return JSValueType::Float32Array;
if (value->IsFloat64Array())
return JSValueType::Float64Array;
if (value->IsDataView())
return JSValueType::DataView;
if (value->IsObject())
return JSValueType::OtherObject;
// The only thing a value can be is a primitive or an object. We should
// be checking every primitive above so it should be an object.
LOG(WARNING) << "Unknown JavaScript value given=" << ConvertToString(value);
return JSValueType::Unknown;
}
double NumberFromValue(Handle<JsValue> value) {
DCHECK(!value.IsEmpty());
if (value->IsNumber()) {
return value.As<v8::Number>()->Value();
}
DCHECK(value->IsNumberObject());
return value.As<v8::NumberObject>()->ValueOf();
}
bool BooleanFromValue(Handle<JsValue> value) {
DCHECK(!value.IsEmpty());
if (value->IsBoolean()) {
return value->IsTrue();
}
DCHECK(value->IsBooleanObject());
return value.As<v8::BooleanObject>()->ValueOf();
}
} // namespace shaka
<file_sep>/shaka/src/js/dom/document.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_DOM_DOCUMENT_H_
#define SHAKA_EMBEDDED_JS_DOM_DOCUMENT_H_
#include <atomic>
#include <string>
#include "shaka/optional.h"
#include "src/js/dom/container_node.h"
namespace shaka {
namespace js {
namespace dom {
class Comment;
class Element;
class Text;
/**
* Implements the Document interface for DOM.
* https://dom.spec.whatwg.org/#document
*/
class Document : public ContainerNode {
DECLARE_TYPE_INFO(Document);
public:
Document();
static Document* Create() {
return new Document();
}
static Document* GetGlobalDocument() {
Document* ret = instance_;
CHECK(ret);
return ret;
}
static Document* CreateGlobalDocument();
/**
* @return The time, in milliseconds, the document was created, according to
* Clock's getMonotonicTime.
*/
uint64_t created_at() const { return created_at_; }
std::string node_name() const override;
optional<std::string> NodeValue() const override;
optional<std::string> TextContent() const override;
RefPtr<Element> DocumentElement() const;
RefPtr<Element> CreateElement(const std::string& name);
RefPtr<Comment> CreateComment(const std::string& data);
RefPtr<Text> CreateTextNode(const std::string& data);
private:
static std::atomic<Document*> instance_;
const uint64_t created_at_;
};
class DocumentFactory : public BackingObjectFactory<Document, ContainerNode> {
public:
DocumentFactory();
};
} // namespace dom
} // namespace js
} // namespace shaka
#endif // SHAKA_EMBEDDED_JS_DOM_DOCUMENT_H_
<file_sep>/shaka/src/media/media_processor.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_MEDIA_PROCESSOR_H_
#define SHAKA_EMBEDDED_MEDIA_MEDIA_PROCESSOR_H_
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include "shaka/eme/configuration.h"
#include "src/media/base_frame.h"
#include "src/media/types.h"
namespace shaka {
namespace eme {
class Implementation;
} // namespace eme
namespace media {
/**
* Handles processing the media frames. This includes demuxing media segments
* and decoding frames. This contains all the platform-specific code for
* processing media. This will handle processing of a single stream. A new
* instance should be created for different streams.
*
* Methods may spawn worker threads for parallelization, but all methods return
* synchronously when work is complete. Any callbacks will be serialized to
* only be called on one thread at a time, but it may not be the thread that
* called the method.
*
* This type is fully thread safe. But be sure to read the comments on each
* method for when each method can be called.
*/
class MediaProcessor {
public:
MediaProcessor(
const std::string& container, const std::string& codec,
std::function<void(eme::MediaKeyInitDataType, const uint8_t*, size_t)>
on_encrypted_init_data);
virtual ~MediaProcessor();
NON_COPYABLE_OR_MOVABLE_TYPE(MediaProcessor);
//@{
/**
* Gets the codec/container that this processor is using. This should only be
* used for debugging and not presented to the user. This may be altered
* (e.g. converted to FFmpeg expected format), so it may be different than
* what was originally requested.
*/
std::string container() const;
std::string codec() const;
//@}
/**
* Gets the duration of the media as defined by the most recent initialization
* segment received. This will return 0 if it is unknown or if we haven't
* received an init segment yet.
*/
double duration() const;
/**
* Performs any global initialization that is required (e.g. registering
* codecs). This can be called multiple times, but it must be called before
* any media objects are created.
*/
static void Initialize();
/**
* Initializes the demuxer. This will block until the init segment is read
* and processed. This method will call |on_read| to get the init segment.
* Then this will store |on_read| to be called later to read data.
*
* @param on_read A callback that will read from the source.
* @param on_reset_read A callback that will be called to reset the current
* read position inside the current segment. The caller should resend the
* data for the current segment on the next read.
*/
virtual Status InitializeDemuxer(
std::function<size_t(uint8_t*, size_t)> on_read,
std::function<void()> on_reset_read);
/**
* Reads the next demuxed (encoded) frame. This blocks until the next frame
* is received, or EOF is reached. This calls the |on_read| given to
* InitializeDemuxer to read data. This can only be called after
* InitializeDemuxer returns.
*
* @param frame [OUT] Will contain the next demuxed frame. Not changed on
* errors
*/
virtual Status ReadDemuxedFrame(std::unique_ptr<BaseFrame>* frame);
/**
* Adds the given frame to the decoder and decodes it into full frames. This
* may return no frames or multiple because of dependent frames. This can
* only be called after InitializeDecoder returns.
*
* The frames MUST be given in DTS order. This will discard any frames until
* the first keyframe. If there is a seek, call ResetDecoder before giving
* the new frames.
*
* If there is a decoder error, it is invalid to decode any more frames.
*
* @param cur_time The current playback time.
* @param frame The next encoded frame to decode.
* @param cdm The CDM used to decrypt protected frames.
* @param decoded [OUT] Will contain the decoded frames.
* @return The error code, or Success.
*/
virtual Status DecodeFrame(double cur_time, const BaseFrame* frame,
eme::Implementation* cdm,
std::vector<std::unique_ptr<BaseFrame>>* decoded);
/** Sets the offset, in seconds, to adjust timestamps in the demuxer. */
virtual void SetTimestampOffset(double offset);
/**
* Called when seeking to reset the decoder. This is different than
* adaptation since it will discard any un-flushed frames.
*/
virtual void ResetDecoder();
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_MEDIA_PROCESSOR_H_
<file_sep>/shaka/src/media/base_frame.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/base_frame.h"
namespace shaka {
namespace media {
BaseFrame::BaseFrame(double pts, double dts, double duration, bool is_key_frame)
: pts(pts), dts(dts), duration(duration), is_key_frame(is_key_frame) {}
BaseFrame::~BaseFrame() {}
FrameType BaseFrame::frame_type() const {
return FrameType::Unknown;
}
size_t BaseFrame::EstimateSize() const {
return 0;
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/media/frame_buffer.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_FRAME_BUFFER_H_
#define SHAKA_EMBEDDED_MEDIA_FRAME_BUFFER_H_
#include <list>
#include <memory>
#include <vector>
#include "src/debug/mutex.h"
#include "src/media/base_frame.h"
#include "src/media/locked_frame_list.h"
#include "src/media/media_utils.h"
#include "src/util/macros.h"
namespace shaka {
namespace media {
/**
* Defines a buffer of media frames. This is stored as a series of contiguous
* blocks of buffered ranges.
*
* This type is fully thread safe. Any thread that gets frames MUST only use
* the frame through the Guard instance to ensure that another thread doesn't
* delete the frame while it is in use.
*/
class FrameBuffer {
public:
/**
* The gap, in seconds, between frames that will still be considered part of
* the same buffered range. If two frames are further than this apart, then
* they will be part of different buffered ranges.
*/
static constexpr const double kMaxGapSize = 0.15;
/**
* Creates a new frame buffer.
* @param order_by_dts True to order frames using DTS order; false to order by
* PTS. When a frame is inserted, this determines where to insert the
* frame.
*/
explicit FrameBuffer(bool order_by_dts);
~FrameBuffer();
NON_COPYABLE_OR_MOVABLE_TYPE(FrameBuffer);
/** @return An estimate of the number of bytes being used by these frames. */
size_t EstimateSize() const;
/** Adds a new frame to the buffer. */
void AppendFrame(std::unique_ptr<const BaseFrame> frame);
/**
* Gets the ranges of buffered content in this buffer. The times given are
* based on the PTS time. Because of frame reordering, the start of a range
* may not have the same time as the first frame.
*/
BufferedRanges GetBufferedRanges() const;
/**
* Gets the number of frames between the given times. Both start and end are
* exclusive bounds.
* @return The number of frames.
*/
int FramesBetween(double start_time, double end_time) const;
/**
* Gets the frame that is nearest to the given time. This uses the start time
* of the next frame and the end time of the frame before it; whichever is
* closer will determine which frame to use. It is undefined which will be
* returned if the frames overlap.
*
* @returns The frame that is found, or nullptr if none are found.
*/
LockedFrameList::Guard GetFrameNear(double time) const;
/**
* Gets the first frame that is after the frame with the given time.
* Specifically, this will return the first frame whose start time is strictly
* higher than the given time.
* @returns The frame that is found, or nullptr if none are found.
*/
LockedFrameList::Guard GetFrameAfter(double time) const;
/**
* Searches backward from the given time to return the first key frame. If
* there is a key frame at |time|, this will return that.
* @returns The frame that is found, or nulptr if none are found.
*/
LockedFrameList::Guard GetKeyFrameBefore(double time) const;
/**
* Removes the frames that start in the given range. This will remove frames
* past @a end until the next keyframe to mirror MSE requirements.
*
* Also to mirror MSE, this always uses PTS to determine which frames to
* remove. This will mean that some frames before |start| may be removed
* because they depend on removed frames.
*
* If other threads are using frames from this buffer, this will block until
* they are no longer being used.
*/
void Remove(double start, double end);
private:
struct Range {
Range();
~Range();
NON_COPYABLE_TYPE(Range);
std::list<std::unique_ptr<const BaseFrame>> frames;
double start_pts;
double end_pts;
};
const BaseFrame* GetFrameNear(double time, bool allow_before) const;
void AssertRangesSorted() const;
mutable LockedFrameList used_frames_;
mutable Mutex mutex_;
std::list<Range> buffered_ranges_;
bool order_by_dts_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_FRAME_BUFFER_H_
<file_sep>/shaka/test/src/eme/clearkey_implementation_unittest.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/eme/clearkey_implementation.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "src/mapping/byte_buffer.h"
#include "src/memory/object_tracker.h"
#include "src/public/eme_promise_impl.h"
#include "src/test/v8_test.h"
namespace shaka {
namespace eme {
namespace {
class MockImplementationHelper : public ImplementationHelper {
public:
MOCK_CONST_METHOD0(DataPathPrefix, std::string());
MOCK_CONST_METHOD4(OnMessage, void(const std::string&, MediaKeyMessageType,
const uint8_t*, size_t));
MOCK_CONST_METHOD1(OnKeyStatusChange, void(const std::string&));
};
} // namespace
constexpr const uint8_t kKeyId[] = {'1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '1', '2', '3', '4', '5', '6'};
constexpr const uint8_t kKey[] = {'1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '1', '2', '3', '4', '5', '6'};
constexpr const uint8_t kClearData[] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7,
0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf,
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6};
constexpr const uint8_t kEncryptedData[] = {
0xaa, 0x33, 0x82, 0x87, 0x2b, 0x56, 0x0b, 0xda, 0xa5, 0xb0, 0xad, 0xe3,
0xe1, 0x4a, 0x29, 0x56, 0x66, 0x16, 0x65, 0xbd, 0xe0, 0xfe, 0x95};
constexpr const int kBlockOffset = 7;
// kClearData encrypted with a block offset of 7.
constexpr const uint8_t kBlockOffsetEncryptedData[] = {
0xdd, 0xac, 0xbb, 0xa4, 0xec, 0xe8, 0x41, 0x20, 0x51, 0x6f, 0x1d, 0x6c,
0xb2, 0xe9, 0xf5, 0x9c, 0xfe, 0xc6, 0xe6, 0xe6, 0x6b, 0x76, 0xcd};
constexpr const uint8_t kIv[] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7,
0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf};
using ::testing::_;
using ::testing::InSequence;
using ::testing::MockFunction;
using ::testing::NiceMock;
using ::testing::StrictMock;
// There are more tests in JavaScript: //shaka/test/tests/eme.js.
class ClearKeyImplementationTest : public V8Test {
protected:
class MockEmePromiseImpl : public EmePromise::Impl {
public:
MOCK_METHOD0(Resolve, void());
MOCK_METHOD1(ResolveWith, void(bool));
MOCK_METHOD2(Reject, void(ExceptionType, const std::string&));
};
void LoadKeyForTesting(ClearKeyImplementation* clear_key,
std::vector<uint8_t> key_id,
std::vector<uint8_t> key) {
clear_key->LoadKeyForTesting(std::move(key_id), std::move(key));
}
Data CreateData(const uint8_t* data, size_t size) {
ByteBuffer buffer(data, size);
return Data(&buffer);
}
EmePromise CreateEmePromise(MockEmePromiseImpl* mock) {
auto noop = [](EmePromise::Impl*) {};
std::shared_ptr<EmePromise::Impl> impl(mock, noop);
return EmePromise(impl);
}
void TearDown() override {
tracker_.Dispose();
}
memory::ObjectTracker tracker_;
};
TEST_F(ClearKeyImplementationTest, Decrypt) {
NiceMock<MockImplementationHelper> helper;
ClearKeyImplementation clear_key(&helper);
LoadKeyForTesting(&clear_key,
std::vector<uint8_t>(kKeyId, kKeyId + sizeof(kKeyId)),
std::vector<uint8_t>(kKey, kKey + sizeof(kKey)));
// Decryption on a block boundary.
{
std::vector<uint8_t> data(kEncryptedData, kEncryptedData + AES_BLOCK_SIZE);
EXPECT_EQ(clear_key.Decrypt(EncryptionScheme::AesCtr, EncryptionPattern(),
0, kKeyId, sizeof(kKeyId), kIv, sizeof(kIv),
data.data(), data.size(), data.data()),
DecryptStatus::Success);
EXPECT_EQ(data,
std::vector<uint8_t>(kClearData, kClearData + AES_BLOCK_SIZE));
}
// Decryption with a partial block at the end.
{
std::vector<uint8_t> data(kEncryptedData,
kEncryptedData + sizeof(kEncryptedData));
EXPECT_EQ(clear_key.Decrypt(EncryptionScheme::AesCtr, EncryptionPattern(),
0, kKeyId, sizeof(kKeyId), kIv, sizeof(kIv),
data.data(), data.size(), data.data()),
DecryptStatus::Success);
EXPECT_EQ(data, std::vector<uint8_t>(kClearData,
kClearData + sizeof(kClearData)));
}
// Decryption with a block offset and a second block.
{
std::vector<uint8_t> data(
kBlockOffsetEncryptedData,
kBlockOffsetEncryptedData + sizeof(kBlockOffsetEncryptedData));
EXPECT_EQ(
clear_key.Decrypt(EncryptionScheme::AesCtr, EncryptionPattern(),
kBlockOffset, kKeyId, sizeof(kKeyId), kIv,
sizeof(kIv), data.data(), data.size(), data.data()),
DecryptStatus::Success);
EXPECT_EQ(data, std::vector<uint8_t>(kClearData,
kClearData + sizeof(kClearData)));
}
// Decryption with a block offset that doesn't fill a block.
{
constexpr const size_t kSize = 5;
std::vector<uint8_t> data(kBlockOffsetEncryptedData,
kBlockOffsetEncryptedData + kSize);
EXPECT_EQ(
clear_key.Decrypt(EncryptionScheme::AesCtr, EncryptionPattern(),
kBlockOffset, kKeyId, sizeof(kKeyId), kIv,
sizeof(kIv), data.data(), data.size(), data.data()),
DecryptStatus::Success);
EXPECT_EQ(data, std::vector<uint8_t>(kClearData, kClearData + kSize));
}
}
TEST_F(ClearKeyImplementationTest, Decrypt_KeyNotFound) {
NiceMock<MockImplementationHelper> helper;
ClearKeyImplementation clear_key(&helper);
std::vector<uint8_t> real_key_id(16, 1);
ASSERT_EQ(real_key_id.size(), 16u);
LoadKeyForTesting(&clear_key, real_key_id,
std::vector<uint8_t>(kKey, kKey + sizeof(kKey)));
std::vector<uint8_t> data(kEncryptedData, kEncryptedData + AES_BLOCK_SIZE);
std::vector<uint8_t> key_id(16, 0);
ASSERT_EQ(key_id.size(), 16u);
EXPECT_EQ(clear_key.Decrypt(EncryptionScheme::AesCtr, EncryptionPattern(), 0,
key_id.data(), key_id.size(), kIv, sizeof(kIv),
data.data(), data.size(), data.data()),
DecryptStatus::KeyNotFound);
}
TEST_F(ClearKeyImplementationTest, HandlesMissingSessionId) {
StrictMock<MockImplementationHelper> helper;
StrictMock<MockEmePromiseImpl> promise_impl;
MockFunction<void(int)> call;
{
InSequence seq;
EXPECT_CALL(call, Call(0)).Times(1);
EXPECT_CALL(promise_impl, Reject(_, _));
EXPECT_CALL(call, Call(1)).Times(1);
EXPECT_CALL(promise_impl, Reject(_, _));
}
ClearKeyImplementation clear_key(&helper);
int64_t expiration;
EXPECT_FALSE(clear_key.GetExpiration("nope", &expiration));
std::vector<KeyStatusInfo> statuses;
EXPECT_FALSE(clear_key.GetKeyStatuses("nope", &statuses));
call.Call(0);
clear_key.Load("nope", CreateEmePromise(&promise_impl));
call.Call(1);
constexpr const uint8_t kResponse[] =
"{\"keys\":[{}],\"type\":\"temporary\"}";
clear_key.Update("nope", CreateEmePromise(&promise_impl),
CreateData(kResponse, sizeof(kResponse) - 1));
// Note that close() on an unknown session is ignored.
}
} // namespace eme
} // namespace shaka
<file_sep>/shaka/src/mapping/weak_js_ptr.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_CORE_WEAK_JS_PTR_H_
#define SHAKA_EMBEDDED_CORE_WEAK_JS_PTR_H_
#include <glog/logging.h>
#include <type_traits>
#include "src/mapping/js_wrappers.h"
#include "src/memory/heap_tracer.h"
namespace shaka {
/**
* Represents a weak pointer to a JavaScript value. When the GC runs, when
* this is traced it will mark the value alive so it is not freed. If this is
* not traced, the GC will free the value.
*
* This MUST be traced. If the GC runs and the object is freed, this object
* may become invalid. JSC does not keep track of weak pointers, so
* this must be traced to remain valid.
*
* This is NOT a GenericConverter and should not be used as arguments, fields,
* etc.. This should only be used in the mapping types to store JavaScript
* objects.
*/
template <typename T>
class WeakJsPtr : public memory::Traceable {
public:
WeakJsPtr() {}
WeakJsPtr(std::nullptr_t) {} // NOLINT(runtime/explicit)
template <typename U = T>
WeakJsPtr(Handle<U> other) { // NOLINT(runtime/explicit)
ResetInternal(other);
}
WeakJsPtr(const WeakJsPtr& other) {
// Need to define an explicit copy-constructor since v8::Global is
// non-copyable.
ResetInternal(other.ptr_);
}
WeakJsPtr(WeakJsPtr&& other) {
// There are problems using the v8::Global<T> move constructor. So just
// copy and clear the original.
ResetInternal(other.ptr_);
other.reset();
}
~WeakJsPtr() override {
#ifdef USING_V8
// V8 tracks the address of |ptr_| so it can reset it once the object is
// cleared. We need to clear this so V8 doesn't modify other memory.
if (!empty()) {
DCHECK(ptr_.IsWeak());
ptr_.ClearWeak();
}
#endif
}
WeakJsPtr& operator=(const WeakJsPtr& other) {
ResetInternal(other.ptr_);
return *this;
}
WeakJsPtr& operator=(WeakJsPtr&& other) {
// There are problems using the v8::Global<T> move constructor. So just
// copy and clear the original.
ResetInternal(other.ptr_);
other.reset();
return *this;
}
template <typename U = T>
bool operator==(const WeakJsPtr<U>& other) const {
return ptr_ == other.ptr_;
}
template <typename U = T>
bool operator==(const Handle<U>& other) const {
return ptr_ == other;
}
template <typename U = T>
bool operator!=(const WeakJsPtr<U>& other) const {
return ptr_ != other.ptr_;
}
template <typename U = T>
bool operator!=(const Handle<U>& other) const {
return ptr_ != other;
}
/** @return Whether the pointer is empty. */
bool empty() const {
#if defined(USING_V8)
return ptr_.IsEmpty();
#elif defined(USING_JSC)
return !ptr_;
#endif
}
/** @return A local handle to the weak pointer. */
Handle<T> handle() const {
CHECK(!empty());
#if defined(USING_V8)
return ptr_.Get(GetIsolate());
#elif defined(USING_JSC)
return ptr_;
#endif
}
/** @return A value containing the stored value. */
ReturnVal<JsValue> value() const {
return RawToJsValue(handle());
}
void reset() {
#if defined(USING_V8)
ptr_.Reset();
#elif defined(USING_JSC)
ptr_ = nullptr;
#endif
}
template <typename U>
void reset(Handle<U> other) {
ResetInternal(other);
}
void Trace(memory::HeapTracer* tracer) const override {
if (!empty()) {
#if defined(USING_V8)
# ifndef NDEBUG
// Create a handle scope so the handle local() is freed when this returns.
v8::HandleScope handles(GetIsolate());
CHECK(empty() || !handle()->IsNumber());
# endif
ptr_.RegisterExternalReference(GetIsolate());
#endif
}
}
private:
template <typename>
friend class WeakJsPtr;
template <typename U>
void ResetInternal(const U& other) {
#if defined(USING_V8)
// Don't do anything if they are both empty. This allows using WeakJsPtr
// in a background thread where GetIsolate() would fail a CHECK.
if (ptr_.IsEmpty() && other.IsEmpty())
return;
// Mark the Global as weak so the object can be destroyed even though we
// hold a pointer. If |this| is alive, the HeapTracer will call MarkAlive.
ptr_.Reset(GetIsolate(), other);
if (!ptr_.IsEmpty())
ptr_.SetWeak();
#else
ptr_ = other;
#endif
}
#if defined(USING_V8)
v8::Global<T> ptr_;
#elif defined(USING_JSC)
Handle<T> ptr_;
#endif
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_CORE_WEAK_JS_PTR_H_
<file_sep>/shaka/src/js/timeouts.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/timeouts.h"
#include "src/core/js_manager_impl.h"
#include "src/mapping/register_member.h"
namespace shaka {
namespace js {
void Timeouts::Install() {
RegisterGlobalFunction("setTimeout", &Timeouts::SetTimeout);
RegisterGlobalFunction("setInterval", &Timeouts::SetInterval);
RegisterGlobalFunction("clearTimeout", &Timeouts::ClearTimeout);
RegisterGlobalFunction("clearInterval", &Timeouts::ClearInterval);
}
int Timeouts::SetTimeout(Callback callback, optional<uint64_t> timeout) {
return JsManagerImpl::Instance()->MainThread()->AddTimer(timeout.value_or(0),
callback);
}
int Timeouts::SetInterval(Callback callback, optional<uint64_t> timeout) {
return JsManagerImpl::Instance()->MainThread()->AddRepeatedTimer(
timeout.value_or(0), callback);
}
void Timeouts::ClearTimeout(optional<int> id) {
if (id.has_value())
JsManagerImpl::Instance()->MainThread()->CancelTimer(id.value());
}
void Timeouts::ClearInterval(optional<int> id) {
if (id.has_value())
JsManagerImpl::Instance()->MainThread()->CancelTimer(id.value());
}
} // namespace js
} // namespace shaka
<file_sep>/shaka/src/media/pipeline_monitor.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_PIPELINE_MONITOR_H_
#define SHAKA_EMBEDDED_MEDIA_PIPELINE_MONITOR_H_
#include <atomic>
#include <functional>
#include "src/debug/thread.h"
#include "src/media/pipeline_manager.h"
#include "src/media/types.h"
#include "src/util/clock.h"
namespace shaka {
namespace media {
/**
* This manages a thread that monitors the media pipeline and updates the state
* based on the currently buffered content. This also handles transitioning to
* ended.
*/
class PipelineMonitor {
public:
PipelineMonitor(std::function<BufferedRanges()> get_buffered,
std::function<BufferedRanges()> get_decoded,
std::function<void(MediaReadyState)> ready_state_changed,
const util::Clock* clock, PipelineManager* pipeline);
~PipelineMonitor();
/** Stops the background thread and joins it. */
void Stop();
private:
void ThreadMain();
void ChangeReadyState(MediaReadyState new_state);
const std::function<BufferedRanges()> get_buffered_;
const std::function<BufferedRanges()> get_decoded_;
const std::function<void(MediaReadyState)> ready_state_changed_;
const util::Clock* const clock_;
PipelineManager* const pipeline_;
std::atomic<bool> shutdown_;
MediaReadyState ready_state_;
Thread thread_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_PIPELINE_MONITOR_H_
<file_sep>/shaka/src/js/js_error.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_JS_ERROR_H_
#define SHAKA_EMBEDDED_JS_JS_ERROR_H_
#include <string>
#include "src/js/dom/exception_code.h"
#include "src/mapping/js_wrappers.h"
namespace shaka {
namespace js {
/**
* Contains several static methods that will be used to throw a C++ exception
* that will be converted to the correct JavaScript error.
*/
class JsError {
public:
static std::string GetJsStack();
static JsError RangeError(const std::string& message);
static JsError ReferenceError(const std::string& message);
static JsError TypeError(const std::string& message);
static JsError SyntaxError(const std::string& message);
static JsError Error(const std::string& message);
#ifdef USING_V8
static JsError Rethrow(const v8::TryCatch& trycatch);
#endif
static JsError DOMException(ExceptionCode code);
static JsError DOMException(ExceptionCode code, const std::string& message);
~JsError();
JsError(JsError&&);
ReturnVal<JsValue> error() const {
return error_;
}
private:
explicit JsError(ReturnVal<JsValue> error);
ReturnVal<JsValue> error_;
};
} // namespace js
} // namespace shaka
#endif // SHAKA_EMBEDDED_JS_JS_ERROR_H_
<file_sep>/shaka/src/util/decryptor_openssl.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/util/decryptor.h"
#include <glog/logging.h>
#include <openssl/conf.h>
#include <openssl/err.h>
#include <openssl/evp.h>
namespace shaka {
namespace util {
struct Decryptor::Impl {
std::unique_ptr<EVP_CIPHER_CTX, void (*)(EVP_CIPHER_CTX*)> ctx{
nullptr, &EVP_CIPHER_CTX_free};
};
Decryptor::Decryptor(eme::EncryptionScheme scheme,
const std::vector<uint8_t>& key,
const std::vector<uint8_t>& iv)
: scheme_(scheme), key_(key), iv_(iv), extra_(new Impl) {
DCHECK_EQ(AES_BLOCK_SIZE, key.size());
DCHECK_EQ(AES_BLOCK_SIZE, iv.size());
}
Decryptor::~Decryptor() {}
bool Decryptor::DecryptPartialBlock(const uint8_t* data, size_t data_size,
uint32_t block_offset, uint8_t* dest) {
DCHECK_LE(block_offset + data_size, AES_BLOCK_SIZE);
if (!InitIfNeeded())
return false;
if (scheme_ != eme::EncryptionScheme::AesCtr) {
LOG(ERROR) << "Cannot have block offset when using CBC";
return false;
}
uint8_t temp_source[AES_BLOCK_SIZE] = {0};
uint8_t temp_dest[AES_BLOCK_SIZE];
const size_t partial_size =
std::min<size_t>(AES_BLOCK_SIZE - block_offset, data_size);
memcpy(temp_source + block_offset, data, partial_size);
int num_bytes_read;
if (!EVP_DecryptUpdate(extra_->ctx.get(), temp_dest, &num_bytes_read,
temp_source, AES_BLOCK_SIZE) ||
num_bytes_read != AES_BLOCK_SIZE) {
LOG(ERROR) << "Error decrypting data: "
<< ERR_error_string(ERR_get_error(), nullptr);
return false;
}
memcpy(dest, temp_dest + block_offset, partial_size);
return true;
}
bool Decryptor::Decrypt(const uint8_t* data, size_t data_size, uint8_t* dest) {
if (!InitIfNeeded())
return false;
int num_bytes_read;
if (!EVP_DecryptUpdate(extra_->ctx.get(), dest, &num_bytes_read, data,
data_size) ||
static_cast<size_t>(num_bytes_read) != data_size) {
LOG(ERROR) << "Error decrypting data: "
<< ERR_error_string(ERR_get_error(), nullptr);
return false;
}
return true;
}
bool Decryptor::InitIfNeeded() {
if (!extra_->ctx) {
extra_->ctx.reset(EVP_CIPHER_CTX_new());
if (!extra_->ctx) {
LOG(ERROR) << "Error allocating OpenSSL context: "
<< ERR_error_string(ERR_get_error(), nullptr);
return false;
}
const bool is_ctr = scheme_ == eme::EncryptionScheme::AesCtr;
if (!EVP_DecryptInit_ex(extra_->ctx.get(),
is_ctr ? EVP_aes_128_ctr() : EVP_aes_128_cbc(),
nullptr, key_.data(), iv_.data()) ||
!EVP_CIPHER_CTX_set_padding(extra_->ctx.get(), 0)) {
LOG(ERROR) << "Error setting up OpenSSL context: "
<< ERR_error_string(ERR_get_error(), nullptr);
return false;
}
}
return true;
}
} // namespace util
} // namespace shaka
<file_sep>/shaka/include/shaka/variant.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_VARIANT_H_
#define SHAKA_EMBEDDED_VARIANT_H_
#include <assert.h>
#include <stddef.h>
#include <type_traits>
#include <utility>
namespace shaka {
// Note that we shouldn't use the C++17 type even if we are compiling with that
// version of C++. This is because Shaka Embedded is compiled using C++11 and
// will use this type. So the app should always use this type for our API.
// Otherwise using different types will cause subtle bugs.
template <typename... Choices>
class variant;
namespace impl {
/** Contains a |type| member for the type at the given index in the pack. */
template <size_t I, typename... Choices>
struct get_type_at;
template <size_t I, typename T, typename... Choices>
struct get_type_at<I, T, Choices...> final {
static_assert(I > 0, "Bad specialization chosen.");
using type = typename get_type_at<I - 1, Choices...>::type;
};
template <typename T, typename... Choices>
struct get_type_at<0, T, Choices...> final {
using type = T;
};
template <size_t I, typename... Choices>
using get_type_at_t = typename get_type_at<I, Choices...>::type;
template <size_t I, typename... Choices>
using get_const_reference_at_t =
typename std::add_lvalue_reference<typename std::add_const<
typename get_type_at<I, Choices...>::type>::type>::type;
/** Contains an |index| member for the index of the given type in the pack. */
template <typename T, typename... Choices>
struct get_type_index;
template <typename T, typename... Choices>
struct get_type_index<T, T, Choices...> {
static constexpr const size_t index = 0;
};
template <typename T, typename A, typename... Choices>
struct get_type_index<T, A, Choices...> {
static_assert(!std::is_same<T, A>::value, "Bad specialization chosen");
static constexpr const size_t index =
get_type_index<T, Choices...>::index + 1;
};
/**
* Contains an |index| member for the index of the first type that can be
* constructed with an argument of type Arg.
*/
template <typename Arg, typename T, typename... Choices>
struct get_construct_index {
private:
// We can't use a ternary conditional to terminate the recursion, so we have
// to use a specialization like this.
template <bool CanConstruct, typename Dummy = void>
struct Helper { // CanConstruct = true;
static constexpr const size_t index = 0;
};
template <typename Dummy>
struct Helper<false, Dummy> {
static constexpr const size_t index =
get_construct_index<Arg, Choices...>::index + 1;
};
public:
static constexpr const size_t index =
Helper<std::is_constructible<T, Arg&&>::value>::index;
};
/**
* Represents a union of the given types. This doesn't track which type is
* contained and assumes the caller will. The caller needs to explicitly call
* emplace() and reset() to set and clear the value respectively.
*/
template <typename T, typename... Rest>
class union_ final {
public:
union_() {}
union_(const union_&) = delete;
union_(union_&&) = delete;
~union_() {}
union_& operator=(const union_&) = delete;
union_& operator=(union_&&) = delete;
void copy(const union_& other, size_t i) {
if (i == 0) {
new (&value_) T(other.value_);
} else {
new (&rest_) union_<Rest...>;
rest_.copy(other.rest_, i - 1);
}
}
void move(union_&& other, size_t i) {
if (i == 0) {
new (&value_) T(std::move(other.value_));
} else {
new (&rest_) union_<Rest...>;
rest_.move(std::move(other.rest_), i - 1);
}
}
template <size_t I>
get_const_reference_at_t<I, T, Rest...> get() const {
return GetHelper<I, void*>::get(this);
}
template <size_t I>
get_type_at_t<I, T, Rest...>& get() {
return GetHelper<I, void*>::get(this);
}
// Note this works for copy- and move-constructors too.
template <size_t I, typename... U>
void emplace(U&&... args) {
EmplaceHelper<I, U...>::emplace(this, std::forward<U>(args)...);
}
void reset(size_t i) {
if (i == 0) {
value_.~T();
} else {
rest_.reset(i - 1);
rest_.~union_<Rest...>();
}
}
bool equals(const union_& other, size_t i) const {
if (i == 0)
return value_ == other.value_;
else
return rest_.equals(other.rest_, i - 1);
}
private:
template <size_t I, typename... U>
struct EmplaceHelper {
static void emplace(union_* that, U&&... args) {
new (&that->rest_) union_<Rest...>;
that->rest_.template emplace<I - 1>(std::forward<U>(args)...);
}
};
template <typename... U>
struct EmplaceHelper<0, U...> {
static void emplace(union_* that, U&&... args) {
new (&that->value_) T(std::forward<U>(args)...);
}
};
template <size_t I, typename Dummy = void>
struct GetHelper {
static get_const_reference_at_t<I, T, Rest...> get(const union_* that) {
return that->rest_.template get<I - 1>();
}
static get_type_at_t<I, T, Rest...>& get(union_* that) {
return that->rest_.template get<I - 1>();
}
};
template <typename Dummy>
struct GetHelper<0, Dummy> {
static const T& get(const union_* that) {
return that->value_;
}
static T& get(union_* that) {
return that->value_;
}
};
union {
T value_;
union_<Rest...> rest_;
};
};
template <typename T>
class union_<T> final {
public:
union_() {}
union_(const union_&) = delete;
union_(union_&&) = delete;
~union_() {}
union_& operator=(const union_&) = delete;
union_& operator=(union_&&) = delete;
void copy(const union_& other, size_t i) {
assert(i == 0);
new (&value_) T(other.value_);
}
void move(union_&& other, size_t i) {
assert(i == 0);
new (&value_) T(std::move(other.value_));
}
template <size_t I>
const T& get() const {
static_assert(I == 0, "Index out of range");
return value_;
}
template <size_t I>
T& get() {
static_assert(I == 0, "Index out of range");
return value_;
}
// Note this works for copy- and move-constructors too.
template <size_t I, typename... U>
void emplace(U&&... args) {
static_assert(I == 0, "Index out of range");
new (&value_) T(std::forward<U>(args)...);
}
void reset(size_t i) {
assert(i == 0);
value_.~T();
}
bool equals(const union_& other, size_t i) const {
assert(i == 0);
return value_ == other.value_;
}
private:
union {
T value_;
void* dummy_;
};
};
template <typename T>
struct is_variant : std::false_type {};
template <typename... Choices>
struct is_variant<variant<Choices...>> : std::true_type {};
} // namespace impl
template <size_t I, typename Variant>
struct variant_alternative;
template <size_t I, typename... Choices>
struct variant_alternative<I, variant<Choices...>> {
using type = typename impl::get_type_at<I, Choices...>::type;
};
template <size_t I, typename Variant>
using variant_alternative_t = typename variant_alternative<I, Variant>::type;
struct monostate {};
/**
* This is a look-alike for the std::variant type. The most common
* usages of this type have been implemented, but this is not a general
* implementation. For example, this doesn't throw exceptions and instead
* asserts.
*
* @see https://en.cppreference.com/w/cpp/utility/variant
*/
template <typename... Types>
class variant {
public:
variant() : index_(0) {
union_.template emplace<0>();
}
template <typename U,
typename = typename std::enable_if<!impl::is_variant<
typename std::remove_reference<U>::type>::value>::type>
variant(U&& value) {
constexpr const size_t I = impl::get_construct_index<U, Types...>::index;
union_.template emplace<I>(std::forward<U>(value));
index_ = I;
}
variant(const variant& other) : index_(other.index_) {
union_.copy(other.union_, other.index_);
}
variant(variant&& other) : index_(other.index_) {
union_.move(std::move(other.union_), other.index_);
}
~variant() {
union_.reset(index_);
}
variant& operator=(const variant& other) {
union_.reset(index_);
union_.copy(other.union_, other.index_);
index_ = other.index_;
return *this;
}
variant& operator=(variant&& other) {
union_.reset(index_);
union_.move(std::move(other.union_), other.index_);
index_ = other.index_;
return *this;
}
size_t index() const {
return index_;
}
template <typename T, typename... Args>
T& emplace(Args&&... args) {
constexpr const size_t I = impl::get_type_index<T, Types...>::index;
union_.reset(index_);
union_.template emplace<I>(std::forward<Args>(args)...);
index_ = I;
return union_.template get<I>();
}
template <size_t I, typename... Args>
variant_alternative_t<I, variant>& emplace(Args&&... args) {
union_.reset(index_);
union_.template emplace<I>(std::forward<Args>(args)...);
index_ = I;
return union_.template get<I>();
}
private:
template <typename...>
friend class variant;
template <typename... Choices>
friend bool operator==(const variant<Choices...>&,
const variant<Choices...>&);
template <size_t I, typename... Choices>
friend impl::get_const_reference_at_t<I, Choices...> get(
const variant<Choices...>&);
template <size_t I, typename... Choices>
friend variant_alternative_t<I, variant<Choices...>>& get(
variant<Choices...>&);
template <typename T, typename... Choices>
friend const T& get(const variant<Choices...>&);
template <typename T, typename... Choices>
friend T& get(variant<Choices...>&);
template <size_t I, typename... Choices>
friend typename std::add_const<
variant_alternative_t<I, variant<Choices...>>>::type*
get_if(const variant<Choices...>&);
template <size_t I, typename... Choices>
friend variant_alternative_t<I, variant<Choices...>>* get_if(
variant<Choices...>&);
template <typename T, typename... Choices>
friend const T* get_if(const variant<Choices...>&);
template <typename T, typename... Choices>
friend T* get_if(variant<Choices...>&);
bool equals(const variant& other) const {
return index_ == other.index_ && union_.equals(other.union_, index_);
}
template <size_t I>
impl::get_const_reference_at_t<I, Types...> get() const {
assert(I == index_);
return union_.template get<I>();
}
template <size_t I>
variant_alternative_t<I, variant>& get() {
assert(I == index_);
return union_.template get<I>();
}
impl::union_<Types...> union_;
size_t index_;
};
template <typename... Choices>
bool operator==(const variant<Choices...>& lhs,
const variant<Choices...>& rhs) {
return lhs.equals(rhs);
}
template <typename... Choices>
bool operator!=(const variant<Choices...>& lhs,
const variant<Choices...>& rhs) {
return !(lhs == rhs);
}
template <typename T, typename... Choices>
bool holds_alternative(const variant<Choices...>& variant) {
constexpr const size_t I = impl::get_type_index<T, Choices...>::index;
return variant.index() == I;
}
template <size_t I, typename... Choices>
impl::get_const_reference_at_t<I, Choices...> get(
const variant<Choices...>& variant) {
return variant.template get<I>();
}
template <size_t I, typename... Choices>
variant_alternative_t<I, variant<Choices...>>& get(
variant<Choices...>& variant) {
return variant.template get<I>();
}
template <typename T, typename... Choices>
const T& get(const variant<Choices...>& variant) {
constexpr const size_t I = impl::get_type_index<T, Choices...>::index;
return variant.template get<I>();
}
template <typename T, typename... Choices>
T& get(variant<Choices...>& variant) {
constexpr const size_t I = impl::get_type_index<T, Choices...>::index;
return variant.template get<I>();
}
template <size_t I, typename... Choices>
typename std::add_const<variant_alternative_t<I, variant<Choices...>>>::type*
get_if(const variant<Choices...>& variant) {
if (variant.index() == I)
return &variant.template get<I>();
else
return nullptr;
}
template <size_t I, typename... Choices>
variant_alternative_t<I, variant<Choices...>>* get_if(
variant<Choices...>& variant) {
if (variant.index() == I)
return &variant.template get<I>();
else
return nullptr;
}
template <typename T, typename... Choices>
const T* get_if(const variant<Choices...>& variant) {
constexpr const size_t I = impl::get_type_index<T, Choices...>::index;
if (variant.index() == I)
return &variant.template get<I>();
else
return nullptr;
}
template <typename T, typename... Choices>
T* get_if(variant<Choices...>& variant) {
constexpr const size_t I = impl::get_type_index<T, Choices...>::index;
if (variant.index() == I)
return &variant.template get<I>();
else
return nullptr;
}
} // namespace shaka
#endif // SHAKA_EMBEDDED_VARIANT_H_
<file_sep>/shaka/src/media/video_controller.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/video_controller.h"
#include <glog/logging.h>
#include <algorithm>
#include <cmath>
#include <utility>
#include <vector>
#include "src/core/js_manager_impl.h"
#include "src/media/audio_renderer.h"
#include "src/media/media_utils.h"
#include "src/media/video_renderer.h"
#include "src/util/clock.h"
namespace shaka {
namespace media {
namespace {
std::string FormatSize(const FrameBuffer* buffer) {
const char* kSuffixes[] = {"", " KB", " MB", " GB", " TB"};
size_t size = buffer->EstimateSize();
for (const char* suffix : kSuffixes) {
if (size < 3 * 1024)
return std::to_string(size) + suffix;
size /= 1024;
}
LOG(FATAL) << "Size too large to print.";
}
std::string FormatBuffered(const FrameBuffer* buffer) {
std::string ret;
for (auto& range : buffer->GetBufferedRanges()) {
if (!ret.empty())
ret += ", ";
ret += util::StringPrintf("%.2f - %.2f", range.start, range.end);
}
return "[" + ret + "]";
}
Renderer* CreateRenderer(SourceType source, std::function<double()> get_time,
std::function<double()> get_playback_rate,
Stream* stream) {
switch (source) {
case SourceType::Audio:
return new AudioRenderer(std::move(get_time),
std::move(get_playback_rate), stream);
case SourceType::Video:
return new VideoRenderer(std::move(get_time), stream);
default:
LOG(FATAL) << "Unknown source type: " << source;
}
}
/**
* A task that invokes the encrypted init data callback on the main thread.
* We can't use PlainCallbackTask since that uses std::bind, which requires
* the arguments to be copyable, which ByteBuffer isn't.
*/
class EncryptedInitDataTask : public memory::Traceable {
public:
EncryptedInitDataTask(
std::function<void(eme::MediaKeyInitDataType, ByteBuffer)> cb,
eme::MediaKeyInitDataType type, ByteBuffer buffer)
: cb_(cb), type_(type), buffer_(std::move(buffer)) {}
void Trace(memory::HeapTracer* tracer) const override {
// This shouldn't really be needed since there isn't a JavaScript buffer
// backing it; but do it just to be safe.
tracer->Trace(&buffer_);
}
void operator()() {
cb_(type_, std::move(buffer_));
}
private:
const std::function<void(eme::MediaKeyInitDataType, ByteBuffer)> cb_;
const eme::MediaKeyInitDataType type_;
ByteBuffer buffer_;
};
} // namespace
VideoController::VideoController(
std::function<void(SourceType, Status)> on_error,
std::function<void()> on_waiting_for_key,
std::function<void(eme::MediaKeyInitDataType, ByteBuffer)>
on_encrypted_init_data,
std::function<void(MediaReadyState)> on_ready_state_changed,
std::function<void(PipelineStatus)> on_pipeline_changed)
: mutex_("VideoController"),
on_error_(std::move(on_error)),
on_waiting_for_key_(std::move(on_waiting_for_key)),
on_encrypted_init_data_(std::move(on_encrypted_init_data)),
pipeline_(MainThreadCallback(std::move(on_pipeline_changed)),
std::bind(&VideoController::OnSeek, this),
&util::Clock::Instance),
monitor_(std::bind(&VideoController::GetBufferedRanges, this,
SourceType::Unknown),
std::bind(&VideoController::GetDecodedRanges, this),
MainThreadCallback(std::move(on_ready_state_changed)),
&util::Clock::Instance, &pipeline_),
cdm_(nullptr) {
Reset();
}
VideoController::~VideoController() {
util::shared_lock<SharedMutex> lock(mutex_);
for (const auto& source : sources_) {
source.second->demuxer.Stop();
source.second->decoder.Stop();
}
monitor_.Stop();
}
void VideoController::SetVolume(double volume) {
std::unique_lock<SharedMutex> lock(mutex_);
volume_ = volume;
Source* source = GetSource(SourceType::Audio);
if (source && source->renderer)
static_cast<AudioRenderer*>(source->renderer.get())->SetVolume(volume);
}
Frame VideoController::DrawFrame(double* delay) {
std::unique_lock<SharedMutex> lock(mutex_);
Source* source = GetSource(SourceType::Video);
if (!source || !source->renderer)
return Frame();
int dropped_frame_count = 0;
bool is_new_frame = false;
Frame ret =
source->renderer->DrawFrame(&dropped_frame_count, &is_new_frame, delay);
quality_info_.droppedVideoFrames += dropped_frame_count;
quality_info_.totalVideoFrames += dropped_frame_count;
if (is_new_frame)
quality_info_.totalVideoFrames++;
#ifndef NDEBUG
static uint64_t last_print_time = 0;
static uint64_t last_dropped_frame_count = 0;
const uint64_t cur_time = util::Clock::Instance.GetMonotonicTime();
if (quality_info_.droppedVideoFrames != last_dropped_frame_count &&
cur_time - last_print_time > 250) {
const int delta_frames =
quality_info_.droppedVideoFrames - last_dropped_frame_count;
LOG(INFO) << "Dropped " << delta_frames << " frames.";
last_print_time = cur_time;
last_dropped_frame_count = quality_info_.droppedVideoFrames;
}
#endif
return ret;
}
void VideoController::SetCdm(eme::Implementation* cdm) {
std::unique_lock<SharedMutex> lock(mutex_);
cdm_ = cdm;
for (auto& pair : sources_) {
pair.second->decoder.SetCdm(cdm);
}
}
Status VideoController::AddSource(const std::string& mime_type,
SourceType* source_type) {
std::unique_lock<SharedMutex> lock(mutex_);
using namespace std::placeholders; // NOLINT
std::string container;
std::string codec;
if (!ParseMimeAndCheckSupported(mime_type, source_type, &container, &codec))
return Status::NotSupported;
if (sources_.count(*source_type) != 0)
return Status::NotAllowed;
std::unique_ptr<Source> source(new Source(
*source_type, &pipeline_, container, codec,
MainThreadCallback(on_waiting_for_key_),
std::bind(&VideoController::OnEncryptedInitData, this, _1, _2, _3),
std::bind(&PipelineManager::GetCurrentTime, &pipeline_),
std::bind(&VideoController::GetPlaybackRate, this),
std::bind(&VideoController::OnError, this, *source_type, _1),
std::bind(&VideoController::OnLoadMeta, this, *source_type)));
if (source->renderer) {
if (*source_type == SourceType::Audio)
static_cast<AudioRenderer*>(source->renderer.get())->SetVolume(volume_);
}
source->decoder.SetCdm(cdm_);
sources_.emplace(*source_type, std::move(source));
return Status::Success;
}
bool VideoController::AppendData(SourceType type, double timestamp_offset,
double window_start, double window_end,
const uint8_t* data, size_t data_size,
std::function<void(Status)> on_complete) {
util::shared_lock<SharedMutex> lock(mutex_);
Source* source = GetSource(type);
if (!source) {
LOG(ERROR) << "Missing media source for " << type;
return false;
}
source->demuxer.AppendData(timestamp_offset, window_start, window_end, data,
data_size, std::move(on_complete));
return true;
}
bool VideoController::Remove(SourceType type, double start, double end) {
util::shared_lock<SharedMutex> lock(mutex_);
Source* source = GetSource(type);
if (!source) {
LOG(ERROR) << "Missing media source for " << type;
return false;
}
source->stream.GetDemuxedFrames()->Remove(start, end);
return true;
}
void VideoController::EndOfStream() {
double duration = 0;
{
util::shared_lock<SharedMutex> lock(mutex_);
for (auto& pair : sources_) {
auto buffered = pair.second->stream.GetBufferedRanges();
// Use the maximum duration of any stream as the total media duration.
// See: https://w3c.github.io/media-source/#end-of-stream-algorithm
if (!buffered.empty())
duration = std::max(duration, buffered.back().end);
}
}
pipeline_.SetDuration(duration);
}
BufferedRanges VideoController::GetBufferedRanges(SourceType type) const {
util::shared_lock<SharedMutex> lock(mutex_);
if (type == SourceType::Unknown) {
std::vector<BufferedRanges> sources;
sources.reserve(sources_.size());
for (auto& pair : sources_)
sources.push_back(pair.second->stream.GetBufferedRanges());
return IntersectionOfBufferedRanges(sources);
}
const Source* source = GetSource(type);
return source ? source->stream.GetBufferedRanges() : BufferedRanges();
}
void VideoController::Reset() {
{
util::shared_lock<SharedMutex> shared(mutex_);
for (auto& source : sources_) {
source.second->demuxer.Stop();
source.second->decoder.Stop();
}
}
std::unique_lock<SharedMutex> unique(mutex_);
sources_.clear();
cdm_ = nullptr;
quality_info_.creationTime = NAN;
quality_info_.totalVideoFrames = 0;
quality_info_.droppedVideoFrames = 0;
quality_info_.corruptedVideoFrames = 0;
}
void VideoController::DebugDumpStats() const {
util::shared_lock<SharedMutex> lock(mutex_);
printf("Video Stats:\n");
printf(" Pipeline Status: %s\n",
to_string(pipeline_.GetPipelineStatus()).c_str());
printf(" Current Time: %.2f\n", pipeline_.GetCurrentTime());
printf(" Duration: %.2f\n", pipeline_.GetDuration());
printf(" Playback Rate: %.2f\n", pipeline_.GetPlaybackRate());
for (auto& pair : sources_) {
printf(" Buffer (%s):\n", to_string(pair.first).c_str());
printf(" Demuxed (%s): %s\n",
FormatSize(pair.second->stream.GetDemuxedFrames()).c_str(),
FormatBuffered(pair.second->stream.GetDemuxedFrames()).c_str());
printf(" Decoded (%s): %s\n",
FormatSize(pair.second->stream.GetDecodedFrames()).c_str(),
FormatBuffered(pair.second->stream.GetDecodedFrames()).c_str());
}
}
void VideoController::OnSeek() {
util::shared_lock<SharedMutex> lock(mutex_);
for (auto& pair : sources_) {
// No need to reset |processor| since that is done by the decoder.
pair.second->decoder.OnSeek();
if (pair.second->renderer)
pair.second->renderer->OnSeek();
}
}
void VideoController::OnLoadMeta(SourceType type) {
bool done = true;
double duration;
{
util::shared_lock<SharedMutex> lock(mutex_);
DCHECK_EQ(1u, sources_.count(type));
DCHECK(!sources_.at(type)->ready);
sources_.at(type)->ready = true;
duration = sources_.at(type)->processor.duration();
for (auto& pair : sources_) {
if (!pair.second->ready)
done = false;
}
}
if (std::isnan(pipeline_.GetDuration()))
pipeline_.SetDuration(duration == 0 ? HUGE_VAL : duration);
if (done)
pipeline_.DoneInitializing();
}
void VideoController::OnError(SourceType type, Status error) {
pipeline_.OnError();
JsManagerImpl::Instance()->MainThread()->AddInternalTask(
TaskPriority::Internal, "VideoController::OnError",
PlainCallbackTask(std::bind(on_error_, type, error)));
}
void VideoController::OnEncryptedInitData(
eme::MediaKeyInitDataType init_data_type, const uint8_t* data,
size_t data_size) {
JsManagerImpl::Instance()->MainThread()->AddInternalTask(
TaskPriority::Internal, "VideoController::OnEncryptedInitData",
EncryptedInitDataTask(on_encrypted_init_data_, init_data_type,
ByteBuffer(data, data_size)));
}
BufferedRanges VideoController::GetDecodedRanges() const {
util::shared_lock<SharedMutex> lock(mutex_);
std::vector<BufferedRanges> sources;
sources.reserve(sources_.size());
for (auto& pair : sources_) {
sources.push_back(
pair.second->stream.GetDecodedFrames()->GetBufferedRanges());
}
return IntersectionOfBufferedRanges(sources);
}
double VideoController::GetPlaybackRate() const {
if (pipeline_.GetPipelineStatus() != PipelineStatus::Playing)
return 0;
return pipeline_.GetPlaybackRate();
}
VideoController::Source::Source(
SourceType source_type, PipelineManager* pipeline,
const std::string& container, const std::string& codecs,
std::function<void()> on_waiting_for_key,
std::function<void(eme::MediaKeyInitDataType, const uint8_t*, size_t)>
on_encrypted_init_data,
std::function<double()> get_time, std::function<double()> get_playback_rate,
std::function<void(Status)> on_error, std::function<void()> on_load_meta)
: processor(container, codecs, std::move(on_encrypted_init_data)),
decoder(get_time, std::bind(&VideoController::Source::OnSeekDone, this),
std::move(on_waiting_for_key), std::move(on_error), &processor,
pipeline, &stream),
demuxer(std::move(on_load_meta), &processor, &stream),
renderer(CreateRenderer(source_type, get_time,
std::move(get_playback_rate), &stream)),
ready(false) {}
VideoController::Source::~Source() {}
void VideoController::Source::OnSeekDone() {
if (renderer)
renderer->OnSeekDone();
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/js/mse/time_ranges.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_MSE_TIME_RANGES_H_
#define SHAKA_EMBEDDED_JS_MSE_TIME_RANGES_H_
#include "src/mapping/backing_object.h"
#include "src/mapping/backing_object_factory.h"
#include "src/mapping/exception_or.h"
#include "src/media/video_controller.h"
namespace shaka {
namespace js {
namespace mse {
class TimeRanges : public BackingObject {
DECLARE_TYPE_INFO(TimeRanges);
public:
explicit TimeRanges(media::BufferedRanges ranges);
bool IsShortLived() const override;
uint32_t length() const {
return ranges_.size();
}
ExceptionOr<double> Start(uint32_t index) const;
ExceptionOr<double> End(uint32_t index) const;
private:
media::BufferedRanges ranges_;
};
class TimeRangesFactory : public BackingObjectFactory<TimeRanges> {
public:
TimeRangesFactory();
};
} // namespace mse
} // namespace js
} // namespace shaka
#endif // SHAKA_EMBEDDED_JS_MSE_TIME_RANGES_H_
<file_sep>/shaka/include/shaka/error.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_ERROR_H_
#define SHAKA_EMBEDDED_ERROR_H_
#include <iostream>
#include <memory>
#include <string>
#include "macros.h"
namespace shaka {
/**
* @ingroup player
*/
enum class ErrorType : uint8_t {
/**
* A Shaka error was thrown. See the |category| and |code| members for the
* more specific error type.
*/
ShakaError,
/**
* The required JavaScript member was missing or of an incorrect type. This
* can happen if the Shaka Player compiled script is incompatible with this
* library.
*/
BadMember,
/**
* A JavaScript exception was thrown, but it wasn't a Shaka error object. See
* the logs for more info.
*/
NonShakaError,
};
/**
* Represents a Player error. This can be either a Shaka error or a more
* generic JavaScript error.
*
* @see https://github.com/google/shaka-player/blob/master/lib/util/error.js
* @ingroup player
*/
class SHAKA_EXPORT Error final {
public:
/** Creates an object with the given error category and code. */
Error(ErrorType type, const std::string& message);
/** Creates an object with the given error category and code. */
Error(int category, int code, int severity, const std::string& message);
Error(const Error&);
Error(Error&&);
~Error();
Error& operator=(const Error&);
Error& operator=(Error&&);
// TODO: Consider adding the data field. Or consider adding a PrintError
// method to print it without requiring the app to depend on V8.
/** The error message. */
std::string message;
/** The kind of error. */
ErrorType type;
/**
* The category of the error, if this is a Shaka error. This is the same as
* shaka.util.Error.Category.
*/
int category;
/**
* The specific code of the error, if this is a Shaka error. This is the same
* as shaka.util.Error.Code.
*/
int code;
/**
* The Shaka severity of the error, if this is a Shaka error. This is the
* same as shaka.util.Error.Severity.
*
* Only available in Shaka Player v2.1.0+.
*/
int severity;
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
inline std::ostream& operator<<(std::ostream& os, const Error& error) {
return os << error.message;
}
} // namespace shaka
#endif // SHAKA_EMBEDDED_ERROR_H_
<file_sep>/shaka/src/eme/clearkey_implementation.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/eme/clearkey_implementation.h"
#include <algorithm>
#include <utility>
#include "src/js/base_64.h"
#include "src/js/js_error.h"
#include "src/mapping/js_wrappers.h"
#include "src/util/buffer_reader.h"
#include "src/util/decryptor.h"
#include "src/util/utils.h"
namespace shaka {
namespace eme {
namespace {
bool ParseKeyIds(const Data& data, std::vector<std::string>* base64_keyids) {
LocalVar<JsValue> data_val =
ParseJsonString(std::string(data.data(), data.data() + data.size()));
if (!IsObject(data_val)) {
LOG(ERROR) << "Init data is not valid JSON.";
return false;
}
LocalVar<JsObject> data_obj = UnsafeJsCast<JsObject>(data_val);
LocalVar<JsValue> kids = GetMemberRaw(data_obj, "kids");
if (GetValueType(kids) != JSValueType::Array) {
LOG(ERROR) << "Init data doesn't have valid 'kids' member.";
return false;
}
LocalVar<JsObject> kids_obj = UnsafeJsCast<JsObject>(kids);
const size_t kid_count = ArrayLength(kids_obj);
base64_keyids->reserve(kid_count);
for (size_t i = 0; i < kid_count; i++) {
LocalVar<JsValue> entry = GetArrayIndexRaw(kids_obj, i);
if (GetValueType(entry) != JSValueType::String) {
LOG(ERROR) << "Init data doesn't have valid 'kids' member.";
return false;
}
base64_keyids->emplace_back(ConvertToString(entry));
}
return true;
}
bool ParsePssh(const Data& data, std::vector<std::string>* base64_keyids) {
// 4 box size
// 4 box type
// 4 version + flags
// 16 system-id
// if (version > 0)
// 4 key id count
// for (key id count)
// 16 key id
// 4 data size
// [data size] data
constexpr const size_t kSystemIdSize = 16;
constexpr const size_t kKeyIdSize = 16;
constexpr const uint8_t kCommonSystemId[] = {
0x10, 0x77, 0xef, 0xec, 0xc0, 0xb2, 0x4d, 0x02,
0xac, 0xe3, 0x3c, 0x1e, 0x52, 0xe2, 0xfb, 0x4b};
util::BufferReader reader(data.data(), data.size());
while (!reader.empty()) {
const size_t box_start_remaining = reader.BytesRemaining();
const uint32_t box_size = reader.ReadUint32();
if (reader.ReadUint32() != 0x70737368) { // 'pssh'
LOG(ERROR) << "Init data is not a PSSH box";
return false;
}
const uint8_t version = reader.ReadUint8();
reader.Skip(3);
uint8_t system_id[kSystemIdSize];
if (reader.Read(system_id, kSystemIdSize) != kSystemIdSize) {
LOG(ERROR) << "Truncated init data";
return false;
}
if (memcmp(system_id, kCommonSystemId, kSystemIdSize) != 0) {
VLOG(1) << "Ignoring non-common PSSH box";
const size_t bytes_read = box_start_remaining - reader.BytesRemaining();
reader.Skip(box_size - bytes_read);
continue;
}
if (version == 0) {
LOG(ERROR) << "PSSH version 0 is not supported for clear-key";
return false;
}
const uint32_t key_id_count = reader.ReadUint32();
if (reader.BytesRemaining() / kKeyIdSize < key_id_count) {
LOG(ERROR) << "Truncated init data";
return false;
}
base64_keyids->reserve(key_id_count);
for (uint32_t i = 0; i < key_id_count; i++) {
uint8_t key_id[kKeyIdSize];
if (reader.Read(key_id, kKeyIdSize) != kKeyIdSize) {
LOG(ERROR) << "Truncated init data";
return false;
}
base64_keyids->emplace_back(
js::Base64::EncodeUrl(ByteString(key_id, key_id + kKeyIdSize)));
}
return true;
}
LOG(ERROR) << "No PSSH box with common system ID found";
return false;
}
bool ParseAndGenerateRequest(MediaKeyInitDataType type, const Data& data,
std::string* message) {
std::vector<std::string> key_ids;
switch (type) {
case MediaKeyInitDataType::KeyIds:
if (!ParseKeyIds(data, &key_ids))
return false;
break;
case MediaKeyInitDataType::Cenc:
if (!ParsePssh(data, &key_ids))
return false;
break;
default:
LOG(ERROR) << "Init data type not supported.";
return false;
}
std::string ids_json;
for (const std::string& id : key_ids) {
if (ids_json.empty())
ids_json = '"' + id + '"';
else
ids_json += R"(,")" + id + '"';
}
*message = R"({"kids":[)" + ids_json + R"(],"type":"temporary"})";
return true;
}
// This needs to be a template to access the private type |Session::Key|.
template <typename KeyType>
bool ParseResponse(const Data& data, std::list<KeyType>* keys) {
LocalVar<JsValue> data_val =
ParseJsonString(std::string(data.data(), data.data() + data.size()));
if (!IsObject(data_val)) {
LOG(ERROR) << "License response is not valid JSON.";
return false;
}
LocalVar<JsObject> data_obj = UnsafeJsCast<JsObject>(data_val);
LocalVar<JsValue> keys_val = GetMemberRaw(data_obj, "keys");
if (GetValueType(keys_val) != JSValueType::Array) {
LOG(ERROR) << "License response doesn't contain a valid 'keys' member.";
return false;
}
LocalVar<JsObject> keys_array = UnsafeJsCast<JsObject>(keys_val);
const size_t key_count = ArrayLength(keys_array);
for (size_t i = 0; i < key_count; i++) {
LocalVar<JsValue> entry = GetArrayIndexRaw(keys_array, i);
if (!IsObject(entry)) {
LOG(ERROR) << "License response doesn't contain a valid 'keys' member.";
return false;
}
LocalVar<JsObject> entry_obj = UnsafeJsCast<JsObject>(entry);
LocalVar<JsValue> k_val = GetMemberRaw(entry_obj, "k");
LocalVar<JsValue> kid_val = GetMemberRaw(entry_obj, "kid");
if (GetValueType(k_val) != JSValueType::String ||
GetValueType(kid_val) != JSValueType::String) {
LOG(ERROR) << "License response contains invalid key object.";
return false;
}
ExceptionOr<ByteString> k = js::Base64::DecodeUrl(ConvertToString(k_val));
ExceptionOr<ByteString> kid =
js::Base64::DecodeUrl(ConvertToString(kid_val));
if (holds_alternative<js::JsError>(k) ||
holds_alternative<js::JsError>(kid)) {
LOG(ERROR) << "License response contains invalid base-64 encoding.";
return false;
}
if (get<ByteString>(k).size() != 16 || get<ByteString>(kid).size() != 16) {
LOG(ERROR) << "Key or key ID is not correct size.";
return false;
}
keys->emplace_back(std::move(get<ByteString>(kid)),
std::move(get<ByteString>(k)));
}
return true;
}
} // namespace
ClearKeyImplementation::ClearKeyImplementation(ImplementationHelper* helper)
: helper_(helper), cur_session_id_(0) {}
ClearKeyImplementation::~ClearKeyImplementation() {}
void ClearKeyImplementation::Destroy() {
delete this;
}
bool ClearKeyImplementation::GetExpiration(const std::string& session_id,
int64_t* expiration) const {
*expiration = -1;
return sessions_.count(session_id) != 0;
}
bool ClearKeyImplementation::GetKeyStatuses(
const std::string& session_id, std::vector<KeyStatusInfo>* statuses) const {
std::unique_lock<std::mutex> lock(mutex_);
if (sessions_.count(session_id) == 0)
return false;
statuses->clear();
for (auto& key : sessions_.at(session_id).keys)
statuses->emplace_back(key.key_id, MediaKeyStatus::Usable);
return true;
}
void ClearKeyImplementation::SetServerCertificate(EmePromise promise,
Data /* cert */) {
promise.ResolveWith(false);
}
void ClearKeyImplementation::CreateSessionAndGenerateRequest(
EmePromise promise, std::function<void(const std::string&)> set_session_id,
MediaKeySessionType session_type, MediaKeyInitDataType init_data_type,
Data data) {
DCHECK(session_type == MediaKeySessionType::Temporary);
std::unique_lock<std::mutex> lock(mutex_);
const std::string session_id = std::to_string(++cur_session_id_);
// The indexer will create a new object since it doesn't exist.
Session* session = &sessions_[session_id];
DCHECK(!session->callable);
std::string message;
if (!ParseAndGenerateRequest(init_data_type, data, &message)) {
promise.Reject(ExceptionType::TypeError,
"Invalid initialization data given.");
return;
}
session->callable = true;
set_session_id(session_id);
helper_->OnMessage(session_id, MediaKeyMessageType::LicenseRequest,
reinterpret_cast<const uint8_t*>(message.c_str()),
message.size());
promise.Resolve();
}
void ClearKeyImplementation::Load(const std::string& /* session_id */,
EmePromise promise) {
promise.Reject(ExceptionType::NotSupported,
"Clear-key doesn't support persistent licences.");
}
void ClearKeyImplementation::Update(const std::string& session_id,
EmePromise promise, Data data) {
std::unique_lock<std::mutex> lock(mutex_);
if (sessions_.count(session_id) == 0) {
promise.Reject(ExceptionType::InvalidState,
"Unable to find given session ID.");
return;
}
Session* session = &sessions_.at(session_id);
if (!session->callable) {
promise.Reject(ExceptionType::InvalidState, "Not expecting an update.");
return;
}
std::list<Session::Key> keys;
if (!ParseResponse(data, &keys)) {
promise.Reject(ExceptionType::InvalidState, "Invalid response data.");
return;
}
session->callable = false;
// Move all keys into the session.
session->keys.splice(session->keys.end(), std::move(keys));
helper_->OnKeyStatusChange(session_id);
promise.Resolve();
}
void ClearKeyImplementation::Close(const std::string& session_id,
EmePromise promise) {
std::unique_lock<std::mutex> lock(mutex_);
sessions_.erase(session_id);
promise.Resolve();
}
void ClearKeyImplementation::Remove(const std::string& /* session_id */,
EmePromise promise) {
promise.Reject(ExceptionType::NotSupported,
"Clear-key doesn't support persistent licences.");
}
DecryptStatus ClearKeyImplementation::Decrypt(
EncryptionScheme scheme, EncryptionPattern pattern, uint32_t block_offset,
const uint8_t* key_id, size_t key_id_size, const uint8_t* iv,
size_t iv_size, const uint8_t* data, size_t data_size,
uint8_t* dest) const {
std::unique_lock<std::mutex> lock(mutex_);
const std::vector<uint8_t> key_id_vec(key_id, key_id + key_id_size);
const std::vector<uint8_t>* key = nullptr;
for (auto& session_pair : sessions_) {
for (auto& cur_key : session_pair.second.keys) {
if (cur_key.key_id == key_id_vec) {
key = &cur_key.key;
break;
}
}
}
if (!key) {
LOG(ERROR) << "Unable to find key ID: "
<< util::ToHexString(key_id, key_id_size);
return DecryptStatus::KeyNotFound;
}
util::Decryptor decryptor(scheme, *key,
std::vector<uint8_t>{iv, iv + iv_size});
size_t num_bytes_read = 0;
block_offset %= AES_BLOCK_SIZE;
if (block_offset != 0) {
if (pattern.clear_blocks != 0) {
LOG(ERROR) << "Cannot have block offset when using pattern encryption";
return DecryptStatus::OtherError;
}
num_bytes_read = std::min<int>(data_size, AES_BLOCK_SIZE - block_offset);
if (!decryptor.DecryptPartialBlock(data, num_bytes_read, block_offset,
dest)) {
return DecryptStatus::OtherError;
}
}
if (pattern.clear_blocks != 0) {
const size_t protected_size = AES_BLOCK_SIZE * pattern.encrypted_blocks;
const size_t clear_size = AES_BLOCK_SIZE * pattern.clear_blocks;
const size_t pattern_size_in_blocks =
pattern.encrypted_blocks + pattern.clear_blocks;
const size_t data_size_in_blocks =
(data_size - num_bytes_read) / AES_BLOCK_SIZE;
for (size_t i = 0; i < data_size_in_blocks / pattern_size_in_blocks; i++) {
if (!decryptor.Decrypt(data + num_bytes_read, protected_size,
dest + num_bytes_read)) {
return DecryptStatus::OtherError;
}
num_bytes_read += protected_size;
memcpy(dest + num_bytes_read, data + num_bytes_read, clear_size);
num_bytes_read += clear_size;
}
// If the last pattern block isn't big enough for the whole
// encrypted_blocks, then it is ignored.
if (data_size_in_blocks % pattern_size_in_blocks >=
pattern.encrypted_blocks) {
if (!decryptor.Decrypt(data + num_bytes_read, protected_size,
dest + num_bytes_read)) {
return DecryptStatus::OtherError;
}
num_bytes_read += protected_size;
}
memcpy(dest + num_bytes_read, data + num_bytes_read,
data_size - num_bytes_read);
} else {
if (!decryptor.Decrypt(data + num_bytes_read, data_size - num_bytes_read,
dest + num_bytes_read)) {
return DecryptStatus::OtherError;
}
}
return DecryptStatus::Success;
}
void ClearKeyImplementation::LoadKeyForTesting(std::vector<uint8_t> key_id,
std::vector<uint8_t> key) {
std::unique_lock<std::mutex> lock(mutex_);
const std::string session_id = std::to_string(++cur_session_id_);
sessions_.emplace(session_id, Session());
sessions_.at(session_id).keys.emplace_back(std::move(key_id), std::move(key));
}
ClearKeyImplementation::Session::Key::Key(std::vector<uint8_t> key_id,
std::vector<uint8_t> key)
: key_id(std::move(key_id)), key(std::move(key)) {}
ClearKeyImplementation::Session::Key::~Key() {}
ClearKeyImplementation::Session::Session() {}
ClearKeyImplementation::Session::~Session() {}
ClearKeyImplementation::Session::Session(Session&&) = default;
ClearKeyImplementation::Session& ClearKeyImplementation::Session::operator=(
Session&&) = default;
} // namespace eme
} // namespace shaka
<file_sep>/shaka/src/media/demuxer_thread.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_DEMUXER_THREAD_H_
#define SHAKA_EMBEDDED_MEDIA_DEMUXER_THREAD_H_
#include <atomic>
#include <functional>
#include "src/debug/mutex.h"
#include "src/debug/thread.h"
#include "src/debug/thread_event.h"
#include "src/media/types.h"
#include "src/util/buffer_reader.h"
#include "src/util/macros.h"
namespace shaka {
namespace media {
class MediaProcessor;
class Stream;
/**
* Handles the thread that demuxes input content. This handles synchronizing
* the threads and connecting the demuxer part of MediaProcessor to the Stream.
*
* All callbacks given to this object will be called on the event thread.
*/
class DemuxerThread {
public:
/**
* Creates a new Demuxer instance that pushes to the given stream.
* @param on_load_meta A callback to be invoked once we have loaded metadata.
* @param processor The object that will process the input media.
* @param stream The stream to push frames to.
*/
DemuxerThread(std::function<void()> on_load_meta, MediaProcessor* processor,
Stream* stream);
~DemuxerThread();
NON_COPYABLE_OR_MOVABLE_TYPE(DemuxerThread);
/** Stops the background thread and joins it. */
void Stop();
/**
* Appends the given data to be demuxed.
*
* @param timestamp_offset The number of seconds to move the media timestamps
* forward.
* @param window_start The time (in seconds) to start the append window. Any
* frames outside the append window are ignored.
* @param window_end The time (in seconds) to end the append window.
* @param data The data pointer; it must remain alive until a call to either
* on_complete or on_error.
* @param data_size The number of bytes in |data|.
* @param on_complete The callback to invoke once the append completes.
*/
void AppendData(double timestamp_offset, double window_start,
double window_end, const uint8_t* data, size_t data_size,
std::function<void(Status)> on_complete);
private:
/**
* Called by the MediaProcessor to read data. This should fill |*data| with
* the read data.
* @param data Where to put the data that was read.
* @param data_size The number of bytes in |data|.
* @return The number of bytes read, or 0 on EOF.
*/
size_t OnRead(uint8_t* data, size_t data_size);
void OnResetRead();
void ThreadMain();
void CallOnComplete(Status status);
Mutex mutex_;
ThreadEvent<void> new_data_;
std::function<void(Status)> on_complete_;
std::function<void()> on_load_meta_;
std::atomic<bool> shutdown_;
util::BufferReader input_;
const uint8_t* cur_data_;
size_t cur_size_;
double window_start_;
double window_end_;
bool need_key_frame_;
MediaProcessor* processor_;
Stream* stream_;
// Should be last so the thread starts after all the fields are initialized.
Thread thread_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_DEMUXER_THREAD_H_
<file_sep>/shaka/src/core/js_manager_impl.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_CORE_JS_MANAGER_IMPL_H_
#define SHAKA_EMBEDDED_CORE_JS_MANAGER_IMPL_H_
#include <glog/logging.h>
#include <functional>
#include <memory>
#include <string>
#include "shaka/js_manager.h"
#include "src/core/environment.h"
#include "src/core/network_thread.h"
#include "src/core/task_runner.h"
#include "src/debug/thread_event.h"
#include "src/memory/heap_tracer.h"
#include "src/memory/object_tracker.h"
#ifdef USING_V8
# include "src/memory/v8_heap_tracer.h"
#endif
#include "src/util/pseudo_singleton.h"
namespace shaka {
class JsManagerImpl : public memory::Traceable,
public PseudoSingleton<JsManagerImpl> {
public:
explicit JsManagerImpl(const JsManager::StartupOptions& options);
~JsManagerImpl() override;
void Trace(memory::HeapTracer* tracer) const override;
TaskRunner* MainThread() {
return &event_loop_;
}
NetworkThread* NetworkThread() {
return &network_thread_;
}
std::string GetPathForStaticFile(const std::string& file) const;
std::string GetPathForDynamicFile(const std::string& file) const;
void Run();
void Stop() {
event_loop_.Stop();
}
void WaitUntilFinished();
std::shared_ptr<ThreadEvent<bool>> RunScript(const std::string& path);
std::shared_ptr<ThreadEvent<bool>> RunScript(const std::string& path,
const uint8_t* data,
size_t data_size);
private:
void EventThreadWrapper(TaskRunner::RunLoop run_loop);
memory::ObjectTracker tracker_;
#ifdef USING_V8
memory::V8HeapTracer v8_heap_tracer_{tracker_.heap_tracer(), &tracker_};
#endif
JsManager::StartupOptions startup_options_;
TaskRunner event_loop_;
class NetworkThread network_thread_;
};
/**
* Creates a callback that, when invoked, will invoke the given callback on the
* main thread.
*/
template <typename... Args>
std::function<void(Args...)> MainThreadCallback(
std::function<void(Args...)> cb) {
return [=](Args... args) {
JsManagerImpl::Instance()->MainThread()->AddInternalTask(
TaskPriority::Internal, "", PlainCallbackTask(std::bind(cb, args...)));
};
}
} // namespace shaka
#endif // SHAKA_EMBEDDED_CORE_JS_MANAGER_IMPL_H_
<file_sep>/shaka/src/public/eme_promise.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "shaka/eme/eme_promise.h"
#include <atomic>
#include "src/core/js_manager_impl.h"
#include "src/js/js_error.h"
#include "src/mapping/promise.h"
#include "src/memory/heap_tracer.h"
#include "src/public/eme_promise_impl.h"
namespace shaka {
namespace eme {
namespace {
/**
* A task that will resolve the given Promise with the given value.
*/
class DoResolvePromise : public memory::Traceable {
public:
DoResolvePromise(Promise promise, bool has_value, bool value)
: promise_(promise), has_value_(has_value), value_(value) {}
void Trace(memory::HeapTracer* tracer) const override {
tracer->Trace(&promise_);
}
void operator()() {
LocalVar<JsValue> value;
if (has_value_)
value = ToJsValue(value_);
else
value = JsUndefined();
promise_.ResolveWith(value);
}
private:
Promise promise_;
const bool has_value_;
const bool value_;
};
/**
* A task that will reject the given Promise with the given value.
*/
class DoRejectPromise : public memory::Traceable {
public:
DoRejectPromise(Promise promise, ExceptionType type,
const std::string& message)
: promise_(promise), message_(message), type_(type) {}
void Trace(memory::HeapTracer* tracer) const override {
tracer->Trace(&promise_);
}
void operator()() {
switch (type_) {
case ExceptionType::TypeError:
promise_.RejectWith(js::JsError::TypeError(message_));
break;
case ExceptionType::RangeError:
promise_.RejectWith(js::JsError::RangeError(message_));
break;
case ExceptionType::NotSupported:
promise_.RejectWith(
js::JsError::DOMException(NotSupportedError, message_));
break;
case ExceptionType::InvalidState:
promise_.RejectWith(
js::JsError::DOMException(InvalidStateError, message_));
break;
case ExceptionType::QuotaExceeded:
promise_.RejectWith(
js::JsError::DOMException(QuotaExceededError, message_));
break;
default:
promise_.RejectWith(js::JsError::DOMException(UnknownError, message_));
break;
}
}
private:
Promise promise_;
const std::string message_;
const ExceptionType type_;
};
} // namespace
EmePromise::Impl::Impl(const Promise& promise, bool has_value)
: is_pending_(false), has_value_(has_value) {
// We need to register the object before we store in RefPtr<T>.
auto* p = new Promise(promise);
memory::ObjectTracker::Instance()->RegisterObject(p);
promise_.reset(p);
}
EmePromise::Impl::Impl() : is_pending_(false), has_value_(false) {}
EmePromise::Impl::~Impl() {}
void EmePromise::Impl::Resolve() {
bool expected = false;
if (is_pending_.compare_exchange_strong(expected, true)) {
if (has_value_) {
LOG(WARNING) << "Resolve called on Promise that should have a "
"value, resolving with false.";
}
JsManagerImpl::Instance()->MainThread()->AddInternalTask(
TaskPriority::Internal, "DoResolvePromise",
DoResolvePromise(*promise_, has_value_, false));
}
}
void EmePromise::Impl::ResolveWith(bool value) {
bool expected = false;
if (is_pending_.compare_exchange_strong(expected, true)) {
if (!has_value_) {
LOG(WARNING) << "ResolveWith called on Promise that shouldn't have a "
"value, ignoring value.";
}
JsManagerImpl::Instance()->MainThread()->AddInternalTask(
TaskPriority::Internal, "DoResolvePromise",
DoResolvePromise(*promise_, has_value_, value));
}
}
void EmePromise::Impl::Reject(ExceptionType except_type,
const std::string& message) {
bool expected = false;
if (is_pending_.compare_exchange_strong(expected, true)) {
JsManagerImpl::Instance()->MainThread()->AddInternalTask(
TaskPriority::Internal, "DoRejectPromise",
DoRejectPromise(*promise_, except_type, message));
}
}
EmePromise::EmePromise() : impl_(nullptr) {}
EmePromise::EmePromise(const Promise& promise, bool has_value)
: impl_(new Impl(promise, has_value)) {}
EmePromise::EmePromise(std::shared_ptr<Impl> impl) : impl_(impl) {}
EmePromise::EmePromise(const EmePromise& other) = default;
EmePromise::EmePromise(EmePromise&& other) = default;
EmePromise::~EmePromise() {}
EmePromise& EmePromise::operator=(const EmePromise& other) = default;
EmePromise& EmePromise::operator=(EmePromise&& other) = default;
bool EmePromise::valid() const {
return impl_.get();
}
void EmePromise::Resolve() {
impl_->Resolve();
}
void EmePromise::ResolveWith(bool value) {
impl_->ResolveWith(value);
}
void EmePromise::Reject(ExceptionType except_type, const std::string& message) {
impl_->Reject(except_type, message);
}
} // namespace eme
} // namespace shaka
<file_sep>/shaka/src/mapping/byte_buffer.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/mapping/byte_buffer.h"
#include <utility>
#include "src/memory/heap_tracer.h"
namespace shaka {
namespace {
#ifdef USING_V8
uint8_t* GetDataPointer(v8::Local<v8::ArrayBuffer> buffer) {
return reinterpret_cast<uint8_t*>(buffer->GetContents().Data());
}
#elif defined(USING_JSC)
void FreeData(void* data, void*) {
std::free(data); // NOLINT
}
#endif
} // namespace
ByteBuffer::ByteBuffer() {}
ByteBuffer::ByteBuffer(const uint8_t* data, size_t data_size) {
SetFromBuffer(data, data_size);
}
ByteBuffer::ByteBuffer(ByteBuffer&& other)
: buffer_(std::move(other.buffer_)),
ptr_(other.ptr_),
size_(other.size_),
own_ptr_(other.own_ptr_) {
other.ClearFields();
}
ByteBuffer::~ByteBuffer() {
Clear();
}
ByteBuffer& ByteBuffer::operator=(ByteBuffer&& other) {
Clear();
buffer_ = std::move(other.buffer_);
ptr_ = other.ptr_;
size_ = other.size_;
own_ptr_ = other.own_ptr_;
other.ClearFields();
return *this;
}
void ByteBuffer::Clear() {
if (own_ptr_)
std::free(ptr_); // NOLINT
ClearFields();
}
void ByteBuffer::SetFromDynamicBuffer(const util::DynamicBuffer& other) {
ClearAndAllocateBuffer(other.Size());
other.CopyDataTo(ptr_, size_);
}
void ByteBuffer::SetFromBuffer(const void* buffer, size_t size) {
ClearAndAllocateBuffer(size);
std::memcpy(ptr_, buffer, size_);
}
bool ByteBuffer::TryConvert(Handle<JsValue> value) {
#if defined(USING_V8)
if (value.IsEmpty())
return false;
if (value->IsArrayBuffer()) {
v8::Local<v8::ArrayBuffer> buffer = value.As<v8::ArrayBuffer>();
ptr_ = GetDataPointer(buffer);
size_ = buffer->ByteLength();
} else if (value->IsArrayBufferView()) {
v8::Local<v8::ArrayBufferView> view = value.As<v8::ArrayBufferView>();
ptr_ = GetDataPointer(view->Buffer()) + view->ByteOffset();
size_ = view->ByteLength();
} else {
return false;
}
buffer_ = value.As<v8::Object>();
#elif defined(USING_JSC)
JSContextRef cx = GetContext();
auto type = JSValueGetTypedArrayType(cx, value, nullptr);
if (type == kJSTypedArrayTypeNone)
return false;
LocalVar<JsObject> object = UnsafeJsCast<JsObject>(value);
if (type == kJSTypedArrayTypeArrayBuffer) {
ptr_ = reinterpret_cast<uint8_t*>(
JSObjectGetArrayBufferBytesPtr(cx, object, nullptr));
size_ = JSObjectGetArrayBufferByteLength(cx, object, nullptr);
} else {
ptr_ = reinterpret_cast<uint8_t*>(
JSObjectGetTypedArrayBytesPtr(cx, object, nullptr));
size_ = JSObjectGetTypedArrayByteLength(cx, object, nullptr);
}
buffer_ = object;
#endif
own_ptr_ = false;
return true;
}
ReturnVal<JsValue> ByteBuffer::ToJsValue() const {
if (buffer_.empty()) {
DCHECK(own_ptr_);
#if defined(USING_V8)
buffer_ = v8::ArrayBuffer::New(GetIsolate(), ptr_, size_,
v8::ArrayBufferCreationMode::kInternalized);
#elif defined(USING_JSC)
buffer_ = Handle<JsObject>(JSObjectMakeArrayBufferWithBytesNoCopy(
GetContext(), ptr_, size_, &FreeData, nullptr, nullptr));
#endif
CHECK(!buffer_.empty());
own_ptr_ = false;
}
return buffer_.value();
}
void ByteBuffer::Trace(memory::HeapTracer* tracer) const {
tracer->Trace(&buffer_);
}
void ByteBuffer::ClearFields() {
ptr_ = nullptr;
size_ = 0;
own_ptr_ = false;
}
void ByteBuffer::ClearAndAllocateBuffer(size_t size) {
Clear();
// Use malloc here, the same as in JsEngine::ArrayBufferAllocator.
// Must also be compatible with JSC (uses free()).
own_ptr_ = true;
size_ = size;
ptr_ = reinterpret_cast<uint8_t*>(std::malloc(size_)); // NOLINT
CHECK(ptr_);
}
} // namespace shaka
<file_sep>/shaka/src/media/renderer.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_RENDERER_H_
#define SHAKA_EMBEDDED_MEDIA_RENDERER_H_
#include "shaka/frame.h"
namespace shaka {
namespace media {
/**
* Defines a base class for a renderer. Derived classes will handle rendering
* the decompressed frames. For example, video streams will draw frames to a
* texture so the app can draw it to the screen.
*/
class Renderer {
public:
virtual ~Renderer() {}
/**
* For a video renderer, this will draw a frame to a texture and return it.
* For other renderers, this returns an invalid frame.
*
* @param dropped_frame_count [OUT] Will contain the number of frames that
* were dropped since the last call to DrawFrame.
* @param is_new_frame [OUT] Will contain whether this frame is a different
* frame than the previous call to DrawFrame.
* @param delay [OUT] Optional, will contain the delay, in seconds, until the
* next frame should be drawn.
*/
virtual Frame DrawFrame(int* dropped_frame_count, bool* is_new_frame,
double* delay);
/** Called when the video seeks. */
virtual void OnSeek();
/**
* Called when a seek has been completed. This happens once the first frame
* at the new time has been decoded.
*/
virtual void OnSeekDone();
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_RENDERER_H_
<file_sep>/shaka/src/media/locked_frame_list.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_LOCKED_FRAME_LIST_H_
#define SHAKA_EMBEDDED_MEDIA_LOCKED_FRAME_LIST_H_
#include <list>
#include <thread>
#include <unordered_set>
#include "src/debug/mutex.h"
#include "src/debug/thread_event.h"
#include "src/media/base_frame.h"
#include "src/util/macros.h"
namespace shaka {
namespace media {
/**
* This tracks which frames are being used by other threads. This also allows
* for waiting until some set of them are no longer being used. This handles
* any internal synchronization needed.
*/
class LockedFrameList {
public:
LockedFrameList();
~LockedFrameList();
NON_COPYABLE_OR_MOVABLE_TYPE(LockedFrameList);
/**
* A RAII type that is used to wrap and protect a single frame. This object
* MUST remain alive so long as the wrapped frame is being used. Once this
* object is destroyed, the contained frame can be destroyed.
*
* This is movable, but not copyable. As such, this can be returned from
* methods. If this is moved, then the original instance no longer protects
* (or contains) the frame, only the destination does.
*/
class Guard {
public:
Guard();
Guard(Guard&&);
~Guard();
Guard& operator=(Guard&&);
NON_COPYABLE_TYPE(Guard);
operator bool() const {
return frame_;
}
const BaseFrame* operator->() const {
return frame_;
}
const BaseFrame& operator*() const {
return *frame_;
}
bool operator==(const Guard& other) const {
return frame_ == other.frame_;
}
bool operator!=(const Guard& other) const {
return !(*this == other);
}
const BaseFrame* get() const {
return frame_;
}
private:
friend LockedFrameList;
Guard(LockedFrameList* list, const BaseFrame* frame);
void Destroy();
LockedFrameList* list_;
const BaseFrame* frame_;
};
/**
* Protects the given frame from being deleted. So long as the returned value
* is kept alive, the frame can't be deleted (assuming the calling code uses
* WaitToDeleteFrames).
*
* This may require external synchronization to avoid races between calling
* this method and WaitToDeleteFrames; but once this call completes, no other
* external synchronization is needed.
*/
Guard GuardFrame(const BaseFrame* frame);
/**
* Blocks the current thread until all the given frames are unprotected.
*
* This may require external synchronization to avoid having the frame be
* protected again once this returns.
*/
void WaitToDeleteFrames(const std::unordered_set<const BaseFrame*>& frames);
private:
struct LockedFrame {
const BaseFrame* frame;
#ifndef NDEBUG
std::thread::id locked_thread;
#endif
};
void UnguardFrame(const BaseFrame* frame);
Mutex mutex_;
ThreadEvent<void> cond_;
std::list<LockedFrame> frames_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_LOCKED_FRAME_LIST_H_
<file_sep>/shaka/src/memory/heap_tracer.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/memory/heap_tracer.h"
#include <utility>
#include "src/core/js_manager_impl.h"
#include "src/mapping/backing_object.h"
#include "src/memory/object_tracker.h"
#include "src/util/utils.h"
namespace shaka {
namespace memory {
bool Traceable::IsRootedAlive() const {
return false;
}
bool Traceable::IsShortLived() const {
return false;
}
HeapTracer::HeapTracer() : mutex_("HeapTracer") {}
HeapTracer::~HeapTracer() {}
void HeapTracer::ForceAlive(const Traceable* ptr) {
std::unique_lock<Mutex> lock(mutex_);
pending_.insert(ptr);
}
void HeapTracer::Trace(const Traceable* ptr) {
std::unordered_set<const Traceable*> to_trace;
{
std::unique_lock<Mutex> lock(mutex_);
to_trace = std::move(pending_);
to_trace.insert(ptr);
DCHECK(pending_.empty());
// We need to be careful about circular dependencies. It should not
// happen, but we do not want to get into an infinite loop. Only
// traverse if we have not seen it before.
for (auto it = to_trace.begin(); it != to_trace.end();) {
if (*it && alive_.count(*it) == 0) {
alive_.insert(*it);
++it;
} else {
it = to_trace.erase(it);
}
}
}
for (const Traceable* item : to_trace)
item->Trace(this);
}
void HeapTracer::BeginPass() {
ResetState();
}
void HeapTracer::TraceCommon(
const std::unordered_set<const Traceable*> ref_alive) {
for (const Traceable* ptr : ref_alive) {
Trace(ptr);
}
}
void HeapTracer::ResetState() {
std::unique_lock<Mutex> lock(mutex_);
alive_.clear();
pending_.clear();
}
} // namespace memory
} // namespace shaka
<file_sep>/shaka/src/mapping/jsc/js_wrappers.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/mapping/js_wrappers.h"
#include <fstream>
#include "src/mapping/backing_object.h"
#include "src/mapping/convert_js.h"
#include "src/mapping/js_utils.h"
#include "src/util/file_system.h"
namespace shaka {
namespace {
JSClassDefinition wrapper_class_def = {
.className = "<pointer wrapper>",
.version = 1,
};
JSClassRef GetWrapperClass() {
static JSClassRef class_ = nullptr;
if (!class_) {
class_ = JSClassCreate(&wrapper_class_def);
CHECK(class_);
}
return class_;
}
bool IsInstanceOfStandardType(Handle<JsValue> value, const std::string& type) {
JSContextRef cx = GetContext();
JSValueRef ctor = GetMemberRaw(JSContextGetGlobalObject(cx), type);
return JSValueIsInstanceOfConstructor(cx, value, UnsafeJsCast<JsObject>(ctor),
nullptr);
}
} // namespace
namespace util {
template <>
struct RefTypeTraits<JSPropertyNameArrayRef> {
static constexpr const bool AcquireWithRaw = false;
static JSPropertyNameArrayRef Duplicate(JSPropertyNameArrayRef arg) {
if (arg)
return JSPropertyNameArrayRetain(arg);
else
return nullptr;
}
static void Release(JSPropertyNameArrayRef arg) {
if (arg)
JSPropertyNameArrayRelease(arg);
}
};
} // namespace util
// \cond Doxygen_Skip
CallbackArguments::CallbackArguments(const JSValueRef* args, size_t count,
JSObjectRef callee, JSObjectRef thisv,
JSValueRef* except)
: except_(except),
callee_(callee),
this_(thisv),
args_(args),
count_(count) {}
CallbackArguments::~CallbackArguments() {}
ReturnVal<JsValue> CallbackArguments::operator[](size_t i) const {
if (i >= count_)
return nullptr;
return args_[i];
}
void CallbackArguments::SetReturn(Handle<JsValue> ret) const {
DCHECK(!ret_);
ret_ = ret;
}
void CallbackArguments::SetException(Handle<JsValue> except) const {
DCHECK(!ret_);
*except_ = except;
}
std::vector<std::string> GetMemberNames(Handle<JsObject> object) {
auto* cx = GetContext();
util::CFRef<JSPropertyNameArrayRef> props =
JSObjectCopyPropertyNames(cx, object);
const size_t max = JSPropertyNameArrayGetCount(props);
std::vector<std::string> ret;
ret.reserve(max);
for (size_t i = 0; i < max; i++) {
LocalVar<JsString> name(JSPropertyNameArrayGetNameAtIndex(props, i));
ret.emplace_back(ConvertToString(RawToJsValue(name)));
}
return ret;
}
ReturnVal<JsValue> GetMemberRaw(Handle<JsObject> object,
const std::string& name) {
return JSObjectGetProperty(GetContext(), object, JsStringFromUtf8(name),
nullptr);
}
ReturnVal<JsValue> GetArrayIndexRaw(Handle<JsObject> object, size_t index) {
return JSObjectGetPropertyAtIndex(GetContext(), object, index, nullptr);
}
void SetMemberRaw(Handle<JsObject> object, const std::string& name,
Handle<JsValue> value) {
JSObjectSetProperty(GetContext(), object, JsStringFromUtf8(name), value,
kJSPropertyAttributeNone, nullptr);
}
void SetArrayIndexRaw(Handle<JsObject> object, size_t i,
Handle<JsValue> value) {
JSObjectSetPropertyAtIndex(GetContext(), object, i, value, nullptr);
}
void SetGenericPropertyRaw(Handle<JsObject> object, const std::string& name,
Handle<JsFunction> getter,
Handle<JsFunction> setter) {
// TODO: Find a better way to do this.
// This works by effectively running the following JavaScript:
// Object.defineProperty($object, $name, {get: $getter, set: $setter});
LocalVar<JsValue> js_Object =
GetMemberRaw(JSContextGetGlobalObject(GetContext()), "Object");
CHECK(js_Object && IsObject(js_Object));
LocalVar<JsValue> define_prop =
GetMemberRaw(UnsafeJsCast<JsObject>(js_Object), "defineProperty");
CHECK(define_prop && GetValueType(define_prop) == JSValueType::Function);
LocalVar<JsObject> props(CreateObject());
SetMemberRaw(props, "get", getter);
if (setter)
SetMemberRaw(props, "set", setter);
LocalVar<JsValue> args[] = {object, ToJsValue(name), props};
LocalVar<JsValue> except;
CHECK(InvokeMethod(UnsafeJsCast<JsObject>(define_prop),
UnsafeJsCast<JsObject>(js_Object), 3, args, &except))
<< ConvertToString(except);
}
bool InvokeConstructor(Handle<JsFunction> ctor, int argc,
LocalVar<JsValue>* argv,
LocalVar<JsValue>* result_or_except) {
JSValueRef except = nullptr;
std::vector<JSValueRef> args(argv, argv + argc);
LocalVar<JsValue> ret =
JSObjectCallAsConstructor(GetContext(), ctor, argc, args.data(), &except);
if (except) {
*result_or_except = except;
return false;
} else {
*result_or_except = ret;
return true;
}
}
bool InvokeMethod(Handle<JsFunction> func, Handle<JsObject> that, int argc,
LocalVar<JsValue>* argv,
LocalVar<JsValue>* result_or_except) {
JSValueRef except = nullptr;
std::vector<JSValueRef> args(argv, argv + argc);
LocalVar<JsValue> ret = JSObjectCallAsFunction(GetContext(), func, that, argc,
args.data(), &except);
if (except) {
*result_or_except = except;
return false;
} else {
*result_or_except = ret;
return true;
}
}
std::string ConvertToString(Handle<JsValue> value) {
LocalVar<JsString> str(JSValueToStringCopy(GetContext(), value, nullptr));
if (!str)
return "";
const size_t max_size = JSStringGetMaximumUTF8CStringSize(str);
std::string ret(max_size, '\0');
const size_t real_size = JSStringGetUTF8CString(str, &ret[0], ret.size());
ret.resize(real_size - 1); // Subtract 1 to remove the null-terminator.
return ret;
}
ReturnVal<JsValue> WrapPointer(void* ptr) {
return JSObjectMake(GetContext(), GetWrapperClass(), ptr);
}
void* MaybeUnwrapPointer(Handle<JsValue> value) {
if (!JSValueIsObjectOfClass(GetContext(), value, GetWrapperClass()))
return nullptr;
return JSObjectGetPrivate(JSValueToObject(GetContext(), value, nullptr));
}
BackingObject* GetInternalPointer(Handle<JsValue> value) {
LocalVar<JsObject> obj(JSValueToObject(GetContext(), value, nullptr));
if (!obj)
return nullptr;
return reinterpret_cast<BackingObject*>(JSObjectGetPrivate(obj));
}
bool IsDerivedFrom(BackingObject* ptr, const std::string& name) {
return ptr ? ptr->DerivedFrom(name) : false;
}
bool RunScript(const std::string& path) {
util::FileSystem fs;
std::vector<uint8_t> code;
CHECK(fs.ReadFile(path, &code));
return RunScript(path, code.data(), code.size());
}
bool RunScript(const std::string& path, const uint8_t* data, size_t size) {
const std::vector<uint16_t> data_utf16(data, data + size);
LocalVar<JsString> code =
JSStringCreateWithCharacters(data_utf16.data(), data_utf16.size());
LocalVar<JsString> source = JsStringFromUtf8(path);
JSValueRef except = nullptr;
(void)JSEvaluateScript(GetContext(), code, nullptr, source, 0, &except);
if (except) {
OnUncaughtException(except, false);
return false;
}
return true;
}
ReturnVal<JsValue> ParseJsonString(const std::string& json) {
LocalVar<JsString> input = JsStringFromUtf8(json);
return JSValueMakeFromJSONString(GetContext(), input);
}
ReturnVal<JsString> JsStringFromUtf8(const std::string& str) {
util::CFRef<CFStringRef> cf_str(CFStringCreateWithBytes(
nullptr, reinterpret_cast<const uint8_t*>(str.data()), str.size(),
kCFStringEncodingUTF8, false));
return JSStringCreateWithCFString(cf_str);
}
ReturnVal<JsValue> JsUndefined() {
return JSValueMakeUndefined(GetContext());
}
ReturnVal<JsValue> JsNull() {
return JSValueMakeNull(GetContext());
}
ReturnVal<JsObject> CreateArray(size_t length) {
JSContextRef cx = GetContext();
LocalVar<JsObject> arr(JSObjectMakeArray(cx, 0, nullptr, nullptr));
SetMemberRaw(arr, "length", JSValueMakeNumber(cx, length));
return arr;
}
ReturnVal<JsObject> CreateObject() {
return JSObjectMake(GetContext(), nullptr, nullptr);
}
ReturnVal<JsMap> CreateMap() {
JSContextRef cx = GetContext();
LocalVar<JsObject> global = JSContextGetGlobalObject(cx);
JSValueRef ctor = GetMemberRaw(global, "Map");
DCHECK(ctor && IsObject(ctor));
LocalVar<JsObject> ctor_obj = UnsafeJsCast<JsObject>(ctor);
LocalVar<JsValue> ret;
CHECK(InvokeConstructor(ctor_obj, 0, nullptr, &ret));
return UnsafeJsCast<JsObject>(ret);
}
void SetMapValue(Handle<JsMap> map, Handle<JsValue> key,
Handle<JsValue> value) {
LocalVar<JsValue> func_value = GetMemberRaw(map, "set");
DCHECK(GetValueType(func_value) == JSValueType::Function);
LocalVar<JsFunction> func = UnsafeJsCast<JsFunction>(func_value);
LocalVar<JsValue> args[] = {key, value};
LocalVar<JsValue> ignored;
CHECK(InvokeMethod(func, map, 2, args, &ignored));
}
bool IsNullOrUndefined(Handle<JsValue> value) {
JSContextRef cx = GetContext();
return !value || JSValueIsNull(cx, value) || JSValueIsUndefined(cx, value);
}
bool IsObject(Handle<JsValue> value) {
return JSValueIsObject(GetContext(), value);
}
bool IsBuiltInObject(Handle<JsObject> object) {
LocalVar<JsValue> to_string_val =
GetDescendant(JSContextGetGlobalObject(GetContext()),
{"Object", "prototype", "toString"});
CHECK(IsObject(to_string_val));
LocalVar<JsObject> to_string = UnsafeJsCast<JsObject>(to_string_val);
LocalVar<JsValue> value;
CHECK(InvokeMethod(to_string, object, 0, nullptr, &value));
return ConvertToString(value) != "[object Object]";
}
JSValueType GetValueType(Handle<JsValue> value) {
JSContextRef cx = GetContext();
switch (JSValueGetType(cx, value)) {
case kJSTypeUndefined:
return JSValueType::Undefined;
case kJSTypeNull:
return JSValueType::Null;
case kJSTypeBoolean:
return JSValueType::Boolean;
case kJSTypeNumber:
return JSValueType::Number;
case kJSTypeString:
return JSValueType::String;
case kJSTypeObject:
break;
default:
LOG(FATAL) << "Unknown JavaScript value type";
}
// Note JSC doesn't support symbols.
if (JSValueIsArray(cx, value))
return JSValueType::Array;
if (JSObjectIsFunction(cx, JSValueToObject(cx, value, nullptr)))
return JSValueType::Function;
switch (JSValueGetTypedArrayType(cx, value, nullptr)) {
case kJSTypedArrayTypeArrayBuffer:
return JSValueType::ArrayBuffer;
case kJSTypedArrayTypeFloat32Array:
return JSValueType::Float32Array;
case kJSTypedArrayTypeFloat64Array:
return JSValueType::Float64Array;
case kJSTypedArrayTypeInt16Array:
return JSValueType::Int16Array;
case kJSTypedArrayTypeInt32Array:
return JSValueType::Int32Array;
case kJSTypedArrayTypeInt8Array:
return JSValueType::Int8Array;
case kJSTypedArrayTypeUint16Array:
return JSValueType::Uint16Array;
case kJSTypedArrayTypeUint32Array:
return JSValueType::Uint32Array;
case kJSTypedArrayTypeUint8Array:
return JSValueType::Uint8Array;
case kJSTypedArrayTypeUint8ClampedArray:
return JSValueType::Uint8ClampedArray;
case kJSTypedArrayTypeNone:
break;
default:
LOG(FATAL) << "Unknown JavaScript TypedArray type";
}
if (IsInstanceOfStandardType(value, "Boolean"))
return JSValueType::BooleanObject;
if (IsInstanceOfStandardType(value, "String"))
return JSValueType::StringObject;
if (IsInstanceOfStandardType(value, "Number"))
return JSValueType::NumberObject;
if (IsInstanceOfStandardType(value, "Promise"))
return JSValueType::Promise;
return JSValueType::OtherObject;
}
double NumberFromValue(Handle<JsValue> value) {
JSContextRef cx = GetContext();
DCHECK(JSValueIsNumber(cx, value) ||
IsInstanceOfStandardType(value, "Number"));
return JSValueToNumber(cx, value, nullptr);
}
bool BooleanFromValue(Handle<JsValue> value) {
JSContextRef cx = GetContext();
DCHECK(JSValueIsBoolean(cx, value) ||
IsInstanceOfStandardType(value, "Boolean"));
return JSValueToBoolean(cx, value);
}
// \endcond Doxygen_Skip
} // namespace shaka
<file_sep>/gen_docs.py
#!/usr/bin/python
# Copyright 2016 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Generates HTML documentation for the project."""
import argparse
import os
import subprocess
import sys
ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
BUILD_PATH = os.path.join(ROOT_DIR, 'third_party', 'doxygen', 'build')
BIN_PATH = os.path.join(BUILD_PATH, 'bin', 'doxygen')
sys.path.append(os.path.join(ROOT_DIR, 'shaka', 'tools'))
import utils
def CompileDoxygen():
"""Compiles the doxygen program, if needed."""
if os.path.exists(BIN_PATH):
return 0
if not os.path.exists(BUILD_PATH):
os.mkdir(BUILD_PATH)
if subprocess.call(['cmake', '../src'], cwd=BUILD_PATH) != 0:
return 1
return subprocess.call(['make', '-j4'], cwd=BUILD_PATH)
def GenDocs():
"""Generates the library documentation."""
utils.LoadSubmodule('third_party/doxygen/src')
if CompileDoxygen() != 0:
return 1
return subprocess.call([BIN_PATH], cwd=ROOT_DIR)
def GenerateDoxyfile(extra_path):
"""Generates the Doxyfile configuration file."""
with open(os.path.join(ROOT_DIR, 'Doxyfile.in'), 'r') as in_file:
with open(os.path.join(ROOT_DIR, 'Doxyfile'), 'w') as out_file:
out_file.write(in_file.read().replace('{{EXTRA_PATH}}', extra_path))
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'--config-name', dest='config',
help='Do a special in-tree build with this configuration name.')
ns = parser.parse_args(args)
utils.CheckConfigName(ns.config)
build_dir = utils.ConfigPath(ns.config)
GenerateDoxyfile(os.path.join(build_dir, 'gen', 'shaka'))
return GenDocs()
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
<file_sep>/shaka/src/public/video.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "shaka/video.h"
#include "src/core/js_manager_impl.h"
#include "src/js/dom/document.h"
#include "src/js/mse/media_source.h"
#include "src/js/mse/video_element.h"
#include "src/util/js_wrapper.h"
namespace shaka {
using JSVideo = js::mse::HTMLVideoElement;
class Video::Impl : public util::JSWrapper<JSVideo> {};
Video::Video(JsManager* engine) : impl_(new Impl) {
CHECK(engine) << "Must pass a JsManager instance";
}
Video::Video(Video&&) = default;
Video::~Video() {}
Video& Video::operator=(Video&&) = default;
void Video::Initialize() {
// This can be called immediately after the JsManager constructor. Since the
// Environment might not be setup yet, run this in an internal task so we know
// it is ready.
const auto callback = [this]() {
impl_->inner =
new js::mse::HTMLVideoElement(js::dom::Document::GetGlobalDocument());
};
JsManagerImpl::Instance()
->MainThread()
->AddInternalTask(TaskPriority::Internal, "Video init",
PlainCallbackTask(callback))
->GetValue();
}
Frame Video::DrawFrame(double* delay) {
DCHECK(impl_->inner) << "Must call Initialize.";
RefPtr<js::mse::MediaSource> source = impl_->inner->GetMediaSource();
if (!source)
return Frame();
return source->GetController()->DrawFrame(delay);
}
double Video::Duration() const {
return impl_->CallInnerMethod(&JSVideo::Duration);
}
bool Video::Ended() const {
return impl_->CallInnerMethod(&JSVideo::Ended);
}
bool Video::Seeking() const {
return impl_->CallInnerMethod(&JSVideo::Seeking);
}
bool Video::Paused() const {
return impl_->CallInnerMethod(&JSVideo::Paused);
}
bool Video::Muted() const {
return impl_->CallInnerMethod(&JSVideo::Muted);
}
void Video::SetMuted(bool muted) {
impl_->CallInnerMethod(&JSVideo::SetMuted, muted);
}
std::vector<TextTrack> Video::TextTracks() {
std::vector<Member<js::mse::TextTrack>> original =
impl_->GetMemberVariable(&JSVideo::text_tracks);
// For each element in [begin, end), transform it using |callback| and
// insert the result at the back of |text_tracks|.
std::vector<TextTrack> text_tracks;
auto begin = original.begin();
auto end = original.end();
const auto callback = [](const Member<js::mse::TextTrack> track) {
return TextTrack(track);
};
std::transform(begin, end, std::back_inserter(text_tracks), callback);
return text_tracks;
}
double Video::Volume() const {
return impl_->CallInnerMethod(&JSVideo::Volume);
}
void Video::SetVolume(double volume) {
impl_->CallInnerMethod(&JSVideo::SetVolume, volume);
}
double Video::CurrentTime() const {
return impl_->CallInnerMethod(&JSVideo::CurrentTime);
}
void Video::SetCurrentTime(double time) {
impl_->CallInnerMethod(&JSVideo::SetCurrentTime, time);
}
double Video::PlaybackRate() const {
return impl_->CallInnerMethod(&JSVideo::PlaybackRate);
}
void Video::SetPlaybackRate(double rate) {
impl_->CallInnerMethod(&JSVideo::SetPlaybackRate, rate);
}
void Video::Play() {
impl_->CallInnerMethod(&JSVideo::Play);
}
void Video::Pause() {
impl_->CallInnerMethod(&JSVideo::Pause);
}
js::mse::HTMLVideoElement* Video::GetJavaScriptObject() {
DCHECK(impl_->inner) << "Must call Initialize.";
return impl_->inner;
}
} // namespace shaka
<file_sep>/shaka/test/src/media/media_processor_integration.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/media_processor.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
extern "C" {
#include <libavutil/imgutils.h>
}
#include "src/eme/clearkey_implementation.h"
#include "src/media/ffmpeg_decoded_frame.h"
#include "src/media/ffmpeg_encoded_frame.h"
#include "src/media/frame_converter.h"
#include "src/media/media_utils.h"
#include "src/test/media_files.h"
#include "src/util/crypto.h"
namespace shaka {
namespace media {
namespace {
using namespace std::placeholders; // NOLINT
using testing::_;
using testing::Gt;
using testing::Invoke;
using testing::MockFunction;
using testing::NiceMock;
using testing::ReturnPointee;
constexpr const char* kMp4LowInit = "clear_low_frag_init.mp4";
constexpr const char* kMp4LowSeg = "clear_low_frag_seg1.mp4";
// This isn't fragmented, so it doesn't need an explicit init segment.
constexpr const char* kMp4High = "clear_high.mp4";
constexpr const char* kMp4Encrypted = "encrypted_low.mp4";
constexpr const char* kMp4KeyRotation = "encrypted_key_rotation.mp4";
constexpr const char* kHashFile = "hash_file.txt";
/**
* A simple helper that reads from one or more buffers into the MediaProcessor.
*/
class SegmentReader {
public:
SegmentReader() : segment_idx_(0), segment_offset_(0) {}
void AppendSegment(std::vector<uint8_t> buffer) {
segments_.emplace_back(std::move(buffer));
}
std::function<size_t(uint8_t*, size_t)> MakeReadCallback() {
return [this](uint8_t* dest, size_t dest_size) -> size_t {
if (segment_idx_ >= segments_.size())
return 0;
std::vector<uint8_t>* segment = &segments_[segment_idx_];
dest_size = std::min(dest_size, segment->size() - segment_offset_);
memcpy(dest, segment->data() + segment_offset_, dest_size);
segment_offset_ += dest_size;
if (segment_offset_ >= segment->size()) {
segment_idx_++;
segment_offset_ = 0;
}
return dest_size;
};
}
std::function<void()> MakeResetReadCallback() {
return [this]() { segment_offset_ = 0; };
}
private:
std::vector<std::vector<uint8_t>> segments_;
size_t segment_idx_;
size_t segment_offset_;
};
std::string GetFrameHash(const uint8_t* data, const int size) {
const std::vector<uint8_t> digest = util::HashData(data, size);
return util::ToHexString(digest.data(), digest.size());
}
void DecodeFramesAndCheckHashes(MediaProcessor* processor,
eme::Implementation* cdm) {
FrameConverter converter;
std::string results;
Status status = Status::Success;
while (status != Status::EndOfStream) {
std::unique_ptr<BaseFrame> frame;
status = processor->ReadDemuxedFrame(&frame);
if (status != Status::EndOfStream)
ASSERT_EQ(status, Status::Success);
std::vector<std::unique_ptr<BaseFrame>> decoded_frames;
ASSERT_EQ(processor->DecodeFrame(0, frame.get(), cdm, &decoded_frames),
Status::Success);
for (auto& decoded : decoded_frames) {
ASSERT_EQ(decoded->frame_type(), FrameType::FFmpegDecodedFrame);
auto* cast_frame = static_cast<FFmpegDecodedFrame*>(decoded.get());
uint8_t* const* data = cast_frame->data();
const int* linesize = cast_frame->linesize();
if (cast_frame->pixel_format() != AV_PIX_FMT_ARGB) {
ASSERT_TRUE(converter.ConvertFrame(cast_frame->raw_frame(), &data,
&linesize, AV_PIX_FMT_ARGB));
}
results +=
GetFrameHash(data[0], linesize[0] * cast_frame->height()) + "\n";
}
}
const std::vector<uint8_t> expected = GetMediaFile(kHashFile);
EXPECT_EQ(results, std::string(expected.begin(), expected.end()));
}
void ExpectNoAdaptation() {
EXPECT_FALSE(true) << "Not expecting adaptation.";
}
void IgnoreInitData(eme::MediaKeyInitDataType, const uint8_t*, size_t) {}
} // namespace
class MediaProcessorIntegration : public testing::Test {
protected:
void LoadKeyForTesting(eme::ClearKeyImplementation* clear_key,
const std::vector<uint8_t>& key_id,
const std::vector<uint8_t>& key) {
clear_key->LoadKeyForTesting(key_id, key);
}
};
TEST_F(MediaProcessorIntegration, ReadsInitSegment) {
SegmentReader reader;
reader.AppendSegment(GetMediaFile(kMp4LowInit));
MediaProcessor::Initialize();
MediaProcessor processor("mp4", "avc1.42c01e", &IgnoreInitData);
ASSERT_EQ(processor.InitializeDemuxer(reader.MakeReadCallback(),
&ExpectNoAdaptation),
Status::Success);
}
TEST_F(MediaProcessorIntegration, ReadsDemuxedFrames) {
SegmentReader reader;
reader.AppendSegment(GetMediaFile(kMp4LowInit));
reader.AppendSegment(GetMediaFile(kMp4LowSeg));
MediaProcessor::Initialize();
MediaProcessor processor("mp4", "avc1.42c01e", &IgnoreInitData);
ASSERT_EQ(processor.InitializeDemuxer(reader.MakeReadCallback(),
&ExpectNoAdaptation),
Status::Success);
for (size_t i = 0; i < 120; i++) {
std::unique_ptr<BaseFrame> frame;
ASSERT_EQ(processor.ReadDemuxedFrame(&frame), Status::Success);
// Don't test the body of the frame, it will be tested by the decoding test
// below.
EXPECT_NEAR(frame->dts, i * 0.041666, 0.0001);
}
std::unique_ptr<BaseFrame> frame;
ASSERT_EQ(processor.ReadDemuxedFrame(&frame), Status::EndOfStream);
}
TEST_F(MediaProcessorIntegration, HandlesMp4Adaptation) {
SegmentReader reader;
reader.AppendSegment(GetMediaFile(kMp4LowInit));
reader.AppendSegment(GetMediaFile(kMp4LowSeg));
reader.AppendSegment(GetMediaFile(kMp4High));
MediaProcessor::Initialize();
MediaProcessor processor("mp4", "avc1.42c01e", &IgnoreInitData);
ASSERT_EQ(processor.InitializeDemuxer(reader.MakeReadCallback(),
reader.MakeResetReadCallback()),
Status::Success);
// Low segment.
for (size_t i = 0; i < 120; i++) {
std::unique_ptr<BaseFrame> frame;
ASSERT_EQ(processor.ReadDemuxedFrame(&frame), Status::Success);
EXPECT_NEAR(frame->dts, i * 0.041666, 0.0001);
}
// High segment.
for (size_t i = 0; i < 120; i++) {
std::unique_ptr<BaseFrame> frame;
ASSERT_EQ(processor.ReadDemuxedFrame(&frame), Status::Success);
// The high segment also starts at 0.
EXPECT_NEAR(frame->dts, i * 0.041666, 0.0001);
}
std::unique_ptr<BaseFrame> frame;
ASSERT_EQ(processor.ReadDemuxedFrame(&frame), Status::EndOfStream);
}
TEST_F(MediaProcessorIntegration, AccountsForTimestampOffset) {
SegmentReader reader;
reader.AppendSegment(GetMediaFile(kMp4LowInit));
reader.AppendSegment(GetMediaFile(kMp4LowSeg));
MediaProcessor::Initialize();
MediaProcessor processor("mp4", "avc1.42c01e", &IgnoreInitData);
processor.SetTimestampOffset(20);
ASSERT_EQ(processor.InitializeDemuxer(reader.MakeReadCallback(),
&ExpectNoAdaptation),
Status::Success);
std::unique_ptr<BaseFrame> frame;
ASSERT_EQ(processor.ReadDemuxedFrame(&frame), Status::Success);
EXPECT_NEAR(frame->dts, 20, 0.0001);
EXPECT_NEAR(frame->pts, 20, 0.0001);
ASSERT_EQ(processor.ReadDemuxedFrame(&frame), Status::Success);
EXPECT_NEAR(frame->dts, 20.041666, 0.0001);
EXPECT_NEAR(frame->pts, 20.041666, 0.0001);
}
TEST_F(MediaProcessorIntegration, DemuxerReportsEncryptedFrames) {
SegmentReader reader;
reader.AppendSegment(GetMediaFile(kMp4Encrypted));
MediaProcessor::Initialize();
MediaProcessor processor("mp4", "avc1.42c01e", &IgnoreInitData);
ASSERT_EQ(processor.InitializeDemuxer(reader.MakeReadCallback(),
&ExpectNoAdaptation),
Status::Success);
for (size_t i = 0; i < 120; i++) {
std::unique_ptr<BaseFrame> frame;
ASSERT_EQ(processor.ReadDemuxedFrame(&frame), Status::Success);
ASSERT_EQ(frame->frame_type(), FrameType::FFmpegEncodedFrame);
auto* ffmpeg_frame = static_cast<FFmpegEncodedFrame*>(frame.get());
// The first 96 frames are clear, until the second keyframe.
EXPECT_EQ(ffmpeg_frame->is_encrypted(), i >= 96);
}
}
TEST_F(MediaProcessorIntegration, ReportsEncryptionInitInfo) {
using namespace std::placeholders;
SegmentReader reader;
reader.AppendSegment(GetMediaFile(kMp4KeyRotation));
MockFunction<void(eme::MediaKeyInitDataType, const uint8_t*, size_t)>
on_init_info;
EXPECT_CALL(on_init_info, Call(_, _, _)).Times(0);
// There should be two media segments each with 2 'pssh' boxes. This should
// combine the 'pssh' boxes that appear in the same segment.
EXPECT_CALL(on_init_info, Call(eme::MediaKeyInitDataType::Cenc, _, Gt(0u)))
.Times(2);
auto cb = std::bind(&decltype(on_init_info)::Call, &on_init_info, _1, _2, _3);
MediaProcessor::Initialize();
MediaProcessor processor("mp4", "avc1.42c01e", cb);
ASSERT_EQ(processor.InitializeDemuxer(reader.MakeReadCallback(),
&ExpectNoAdaptation),
Status::Success);
for (size_t i = 0; i < 120; i++) {
std::unique_ptr<BaseFrame> frame;
ASSERT_EQ(processor.ReadDemuxedFrame(&frame), Status::Success);
}
std::unique_ptr<BaseFrame> frame;
ASSERT_EQ(processor.ReadDemuxedFrame(&frame), Status::EndOfStream);
}
TEST_F(MediaProcessorIntegration, CanDecodeFrames) {
SegmentReader reader;
reader.AppendSegment(GetMediaFile(kMp4LowInit));
reader.AppendSegment(GetMediaFile(kMp4LowSeg));
MediaProcessor::Initialize();
MediaProcessor processor("mp4", "avc1.42c01e", &IgnoreInitData);
ASSERT_EQ(processor.InitializeDemuxer(reader.MakeReadCallback(),
&ExpectNoAdaptation),
Status::Success);
DecodeFramesAndCheckHashes(&processor, nullptr);
}
TEST_F(MediaProcessorIntegration, CanDecodeWithAdaptation) {
SegmentReader reader;
reader.AppendSegment(GetMediaFile(kMp4LowInit));
reader.AppendSegment(GetMediaFile(kMp4LowSeg));
reader.AppendSegment(GetMediaFile(kMp4High));
MediaProcessor::Initialize();
MediaProcessor processor("mp4", "avc1.42c01e", &IgnoreInitData);
ASSERT_EQ(processor.InitializeDemuxer(reader.MakeReadCallback(),
reader.MakeResetReadCallback()),
Status::Success);
bool saw_first_stream = false;
bool saw_second_stream = false;
size_t first_stream_id = -1;
while (true) {
std::unique_ptr<BaseFrame> frame;
const Status status = processor.ReadDemuxedFrame(&frame);
if (status == Status::EndOfStream)
break;
ASSERT_EQ(frame->frame_type(), FrameType::FFmpegEncodedFrame);
auto* ffmpeg_frame = static_cast<FFmpegEncodedFrame*>(frame.get());
if (!saw_first_stream) {
saw_first_stream = true;
first_stream_id = ffmpeg_frame->stream_id();
} else {
if (ffmpeg_frame->stream_id() != first_stream_id)
saw_second_stream = true;
}
std::vector<std::unique_ptr<BaseFrame>> decoded_frames;
ASSERT_EQ(status, Status::Success);
ASSERT_EQ(processor.DecodeFrame(0, frame.get(), nullptr, &decoded_frames),
Status::Success);
}
EXPECT_TRUE(saw_first_stream);
EXPECT_TRUE(saw_second_stream);
}
class MediaProcessorDecryptIntegration
: public testing::TestWithParam<const char*> {
protected:
MediaProcessorDecryptIntegration() : cdm_(nullptr) {
cdm_.LoadKeyForTesting({<KEY>,
0xbd, 0x2e, 0x86, 0xa4, 0x34, 0xa9, 0xa5, 0xd9},
{0x69, 0xea, 0xa8, 0x02, 0xa6, 0x76, 0x3a, 0xf9,
0x79, 0xe8, 0xd1, 0x94, 0x0f, 0xb8, 0x83, 0x92});
}
eme::ClearKeyImplementation cdm_;
};
TEST_P(MediaProcessorDecryptIntegration, CanDecryptFrames) {
SegmentReader reader;
reader.AppendSegment(GetMediaFile(GetParam()));
auto ends_with = [this](const std::string& sub) {
const std::string param = GetParam();
return sub.size() <= param.size() &&
param.substr(param.size() - sub.size()) == sub;
};
MediaProcessor::Initialize();
const std::string container = ends_with(".webm") ? "webm" : "mp4";
const std::string codec = ends_with(".webm") ? "vp9" : "avc1.42c01e";
if (!IsTypeSupported(container, codec, 0, 0)) {
LOG(WARNING) << "Skipping test since we don't have support for the media.";
return;
}
MediaProcessor processor(container, codec, &IgnoreInitData);
ASSERT_EQ(processor.InitializeDemuxer(reader.MakeReadCallback(),
&ExpectNoAdaptation),
Status::Success);
DecodeFramesAndCheckHashes(&processor, &cdm_);
}
INSTANTIATE_TEST_CASE_P(SupportsNormalCase, MediaProcessorDecryptIntegration,
testing::Values("encrypted_low.mp4",
"encrypted_low.webm"));
INSTANTIATE_TEST_CASE_P(SupportsUnusualCases, MediaProcessorDecryptIntegration,
testing::Values("encrypted_low_cenc.mp4",
"encrypted_low_cens.mp4",
"encrypted_low_cbc1.mp4",
"encrypted_low_cbcs.mp4"));
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/mapping/callback.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/mapping/callback.h"
#include "src/memory/heap_tracer.h"
namespace shaka {
Callback::Callback() {}
Callback::~Callback() {}
Callback::Callback(const Callback&) = default;
Callback::Callback(Callback&&) = default;
Callback& Callback::operator=(const Callback&) = default;
Callback& Callback::operator=(Callback&&) = default;
bool Callback::TryConvert(Handle<JsValue> given) {
if (GetValueType(given) != JSValueType::Function)
return false;
callback_ = UnsafeJsCast<JsFunction>(given);
return true;
}
ReturnVal<JsValue> Callback::ToJsValue() const {
return callback_.value();
}
void Callback::Trace(memory::HeapTracer* tracer) const {
tracer->Trace(&callback_);
}
} // namespace shaka
<file_sep>/shaka/include/shaka/frame.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_FRAME_H_
#define SHAKA_EMBEDDED_FRAME_H_
#include <cstddef>
#include <cstdint>
#include <memory>
#include "macros.h"
struct AVFrame;
namespace shaka {
namespace media {
class FrameDrawer;
} // namespace media
/**
* Defines possible binary formats of raw texture data.
*
* @ingroup player
*/
enum class PixelFormat {
Unknown,
/**
* Planar YUV 4:2:0, 12bpp. This is FFmpeg's AV_PIX_FMT_YUV420P.
*
* The first plane holds the Y values for each pixel; each pixel has one byte.
* The second and third planes hold U and V data respectively. Each byte
* in the row represents a 2x2 pixel region on the image. This means that
* the second and third planes have half as many bytes in each row.
*/
YUV420P,
/**
* Planar YUV 4:2:0, 12bpp, using interleaved U/V components. This is
* FFmpeg's AV_PIX_FMT_NV12.
*
* The first plane holds Y values for each pixel, as a single byte. The
* second plane holds interleaved U/V components. Each byte is alternating
* U/V data where each pair represent a 2x2 pixel region on the image.
*/
NV12,
/**
* Packed RGB 8:8:8, 24bpp. This is FFmpeg's AV_PIX_FMT_RGB24.
*
* There is only one plane holding the data. Each pixel is represented by
* three bytes for R-G-B.
*/
RGB24,
/**
* A VideoToolbox hardware encoded frame. @a data[3] will contain a
* CVPixelBufferRef object containing the texture.
*/
VIDEO_TOOLBOX,
};
/**
* Represents a decoded frame holding pixel data. This can represent either
* a hardware texture from a hardware decoder or an array of pixel data that can
* be copied to a texture.
*
* This also has a conversion function that can be used to convert to an
* easier to use pixel format.
*
* @ingroup player
*/
class SHAKA_EXPORT Frame final {
public:
Frame();
Frame(const Frame&) = delete;
Frame(Frame&&);
~Frame();
Frame& operator=(const Frame&) = delete;
Frame& operator=(Frame&&);
/** @return Whether this contains valid frame data. */
bool valid() const;
/** @return The pixel format of the frame. */
PixelFormat pixel_format() const;
/** @return The width of the frame in pixels. */
uint32_t width() const;
/** @return The height of the frame in pixels. */
uint32_t height() const;
/**
* Gets the raw frame data for this frame. The exact format of the data
* depends on the pixel format. See PixelFormat for the specific formats.
*
* In general, this returns a 4-element array of pointers to planar data.
* Each pointer represents a separate plane. For packed and hardware formats,
* data[0] will contain the data.
*
* For non-hardware formats, each plane contains pixel data. Each pixel is
* represented by some number of bits going from left to right. The
* @a linesize function specifies how many bytes there are in each row of
* the image.
*/
const uint8_t* const* data() const;
/**
* Gets an array containing the line sizes. Each element holds the line size
* value for the associated plane in @a data. The value represents the number
* of bytes in a row of the image.
*/
const int* linesize() const;
/**
* Tries to convert the frame data to the given pixel format. If the
* conversion fails, nothing is changed. If the conversion succeeds, any
* old data pointers are invalid.
*
* @param format The pixel format to convert to.
* @return True on success; false on error.
*/
bool ConvertTo(PixelFormat format);
private:
friend class media::FrameDrawer;
Frame(AVFrame* frame);
class Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_FRAME_H_
<file_sep>/shaka/tools/embed_v8_snapshot.py
#!/usr/bin/python
# Copyright 2017 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Generates a .cc file that embeds the V8 snapshot.
This defines the following function
void shaka::SetupV8Snapshots();
"""
import argparse
import sys
import embed_utils
def _SetupStartupData(writer, var_name):
"""Writes the code to setup a StartupData variable."""
writer.Write(
'%s_startup_data.data = reinterpret_cast<const char*>(%s_uncompressed);',
var_name, var_name)
writer.Write('%s_startup_data.raw_size = %s_uncompressed_size;', var_name,
var_name)
def _GenerateFile(output):
"""Generates a C++ file which embeds the snapshot files."""
with open('snapshot_blob.bin', 'rb') as f:
snapshot_data = f.read()
with open('natives_blob.bin', 'rb') as f:
natives_data = f.read()
writer = embed_utils.CompressedCodeWriter(output)
writer.Write('#include <v8.h>')
writer.Write()
writer.Write('#include "src/util/utils.h"')
writer.Write()
with writer.Namespace('shaka'):
with writer.Namespace():
writer.CompressedVariable('snapshot', snapshot_data)
writer.Write('v8::StartupData snapshot_startup_data;')
writer.Write()
writer.CompressedVariable('natives', natives_data)
writer.Write('v8::StartupData natives_startup_data;')
writer.Write()
writer.Write('void SetupV8Snapshots();')
writer.Write()
with writer.Block('void SetupV8Snapshots()'):
writer.Decompress('snapshot')
_SetupStartupData(writer, 'snapshot')
writer.Write('v8::V8::SetSnapshotDataBlob(&snapshot_startup_data);')
writer.Write()
writer.Decompress('natives')
_SetupStartupData(writer, 'natives')
writer.Write('v8::V8::SetNativesDataBlob(&natives_startup_data);')
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', dest='output',
help='The filename to output to.')
ns = parser.parse_args(args)
with open(ns.output, 'w') as output:
_GenerateFile(output)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
<file_sep>/shaka/src/js/navigator.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_NAVIGATOR_H_
#define SHAKA_EMBEDDED_JS_NAVIGATOR_H_
#include <string>
#include <vector>
#include "shaka/version.h"
#include "src/mapping/backing_object.h"
#include "src/mapping/backing_object_factory.h"
#include "src/mapping/promise.h"
#include "src/js/eme/media_key_system_configuration.h"
// #define PLATFORM // Defined by BUILD.gn
#define APP_NAME "Netscape"
#define APP_CODE_NAME "Mozilla"
#define APP_VERSION "5.0"
#define PRODUCT "Gecko"
#define PRODUCT_SUB "20030107"
#define VENDOR "Shaka-Player-Embedded"
#define VENDOR_SUB SHAKA_VERSION_STR
#define USER_AGENT \
APP_CODE_NAME "/" APP_VERSION " (" PLATFORM ") " VENDOR "/" VENDOR_SUB
namespace shaka {
namespace js {
class Navigator : public BackingObject {
DECLARE_TYPE_INFO(Navigator);
public:
Navigator();
const std::string app_name = APP_NAME;
const std::string app_code_name = APP_CODE_NAME;
const std::string app_version = APP_VERSION;
const std::string platform = PLATFORM;
const std::string product = PRODUCT;
const std::string product_sub = PRODUCT_SUB;
const std::string vendor = VENDOR;
const std::string vendor_sub = VENDOR_SUB;
const std::string user_agent = USER_AGENT;
Promise RequestMediaKeySystemAccess(
std::string key_system,
std::vector<eme::MediaKeySystemConfiguration> configs);
};
class NavigatorFactory : public BackingObjectFactory<Navigator> {
public:
NavigatorFactory();
~NavigatorFactory() override;
};
} // namespace js
} // namespace shaka
#endif // SHAKA_EMBEDDED_JS_NAVIGATOR_H_
<file_sep>/shaka/src/util/buffer_reader.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_UTIL_BUFFER_READER_H_
#define SHAKA_EMBEDDED_UTIL_BUFFER_READER_H_
#include <stddef.h>
#include <stdint.h>
namespace shaka {
namespace util {
enum Endianness {
kBigEndian,
kLittleEndian,
};
/**
* A simple utility class to read bytes from a buffer. This does not own the
* data and is not thread safe.
*/
class BufferReader {
public:
BufferReader();
BufferReader(const uint8_t* data, size_t data_size);
bool empty() const {
return size_ == 0;
}
/** @return The number of bytes left to read. */
size_t BytesRemaining() const {
return size_;
}
/** Resets the buffer that this type will read from. */
void SetBuffer(const uint8_t* data, size_t data_size);
/**
* Reads up to |dest_size| bytes and copies them into |dest|.
* @param dest The buffer to copy the data to.
* @param dest_size The number of bytes in |dest|.
* @return The number of bytes read.
*/
size_t Read(uint8_t* dest, size_t dest_size);
/**
* Skips the given number of bytes.
* @return The number of bytes skipped.
*/
size_t Skip(size_t count);
/**
* Reads a 8-bit integer from the buffer. If the reader is empty, this
* returns 0.
*/
uint8_t ReadUint8() {
return static_cast<uint8_t>(ReadInteger(1, kBigEndian));
}
/**
* Reads a 32-bit integer from the buffer. If there aren't enough bytes, this
* will fill remaining bytes with 0s. For example, in big-endian, if this
* can only read two bytes {0x12, 0x34}, this will return 0x12340000.
*/
uint32_t ReadUint32(Endianness endianness = kBigEndian) {
return static_cast<uint32_t>(ReadInteger(4, endianness));
}
private:
uint64_t ReadInteger(size_t size, Endianness endianness);
const uint8_t* data_;
size_t size_;
};
} // namespace util
} // namespace shaka
#endif // SHAKA_EMBEDDED_UTIL_BUFFER_READER_H_
<file_sep>/shaka/src/js/mse/source_buffer.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_MSE_SOURCE_BUFFER_H_
#define SHAKA_EMBEDDED_JS_MSE_SOURCE_BUFFER_H_
#include "src/core/member.h"
#include "src/js/events/event_target.h"
#include "src/mapping/byte_buffer.h"
#include "src/mapping/enum.h"
#include "src/mapping/exception_or.h"
#include "src/media/types.h"
namespace shaka {
namespace js {
namespace mse {
class MediaSource;
class TimeRanges;
enum class AppendMode {
SEGMENTS,
SEQUENCE,
};
class SourceBuffer : public events::EventTarget {
DECLARE_TYPE_INFO(SourceBuffer);
public:
SourceBuffer(RefPtr<MediaSource> media_source, media::SourceType type);
void Trace(memory::HeapTracer* tracer) const override;
ExceptionOr<void> AppendBuffer(ByteBuffer data);
void Abort();
ExceptionOr<void> Remove(double start, double end);
/** Called when the MediaSource gets detached. */
void CloseMediaSource();
ExceptionOr<RefPtr<TimeRanges>> GetBuffered() const;
double TimestampOffset() const;
ExceptionOr<void> SetTimestampOffset(double offset);
double AppendWindowStart() const;
ExceptionOr<void> SetAppendWindowStart(double window_start);
double AppendWindowEnd() const;
ExceptionOr<void> SetAppendWindowEnd(double window_end);
AppendMode mode;
bool updating;
Listener on_update_start;
Listener on_update;
Listener on_update_end;
Listener on_error;
Listener on_abort;
private:
/** Called when an append operation completes. */
void OnAppendComplete(media::Status status);
double timestamp_offset_;
double append_window_start_;
double append_window_end_;
Member<MediaSource> media_source_;
media::SourceType type_;
ByteBuffer append_buffer_;
};
class SourceBufferFactory
: public BackingObjectFactory<SourceBuffer, events::EventTarget> {
public:
SourceBufferFactory();
};
} // namespace mse
} // namespace js
} // namespace shaka
DEFINE_ENUM_MAPPING(shaka::js::mse, AppendMode) {
AddMapping(Enum::SEGMENTS, "segments");
AddMapping(Enum::SEQUENCE, "sequence");
}
#endif // SHAKA_EMBEDDED_JS_MSE_SOURCE_BUFFER_H_
<file_sep>/shaka/src/util/macros.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_UTIL_MACROS_H_
#define SHAKA_EMBEDDED_UTIL_MACROS_H_
#include <glog/logging.h>
#include <iostream>
#include <string>
#define NON_COPYABLE_TYPE(Type) \
Type(const Type&) = delete; \
Type& operator=(const Type&) = delete
#define NON_MOVABLE_TYPE(Type) \
Type(Type&&) = delete; \
Type& operator=(Type&&) = delete
#define NON_COPYABLE_OR_MOVABLE_TYPE(Type) \
NON_COPYABLE_TYPE(Type); \
NON_MOVABLE_TYPE(Type)
#define LOG_ONCE(severity) LOG_FIRST_N(severity, 1)
#ifdef __GNUC__
# define PRINTF_FORMAT(format_arg, dots_arg) \
__attribute__((format(printf, format_arg, dots_arg)))
# define NO_SANITIZE(name) __attribute__((no_sanitize(name)))
# define FALL_THROUGH_INTENDED [[clang::fallthrough]] // NOLINT
# define BEGIN_ALLOW_COMPLEX_STATICS \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wexit-time-destructors\"") \
_Pragma("clang diagnostic ignored \"-Wglobal-constructors\"")
# define END_ALLOW_COMPLEX_STATICS _Pragma("clang diagnostic pop")
#else
# define PRINTF_FORMAT(format, dots)
# define NO_SANITIZE(name)
# define FALL_THROUGH_INTENDED
# define BEGIN_ALLOW_COMPLEX_STATICS
# define END_ALLOW_COMPLEX_STATICS
#endif
#ifdef __GNUC__
# define MUST_USE_RESULT __attribute__((warn_unused_result))
#elif defined(_MSC_VER) && _MSC_VER >= 1700
# include <sal.h>
# define MUST_USE_RESULT _Check_return_
#else
# define MUST_USE_RESULT
#endif
// Type is the name of the generated type.
// DEFINE_ENUM is a macro that will define the enum; it will be called twice
// given either ENUM_IMPL or CASE_IMPL.
// ENUM_IMPL and CASE_IMPL are macros that are passed as arguments to
// DEFINE_ENUM.
#define DEFINE_ENUM_AND_TO_STRING_GENERIC_(Type, DEFINE_ENUM, ENUM_IMPL, \
CASE_IMPL) \
enum class Type { DEFINE_ENUM(ENUM_IMPL) }; \
inline std::string to_string(Type e) noexcept { \
using Enum = Type; \
switch (e) { \
DEFINE_ENUM(CASE_IMPL) \
default: \
LOG(FATAL) << "Unknown enum value " << static_cast<int>(e); \
} \
} \
inline std::ostream& operator<<(std::ostream& os, Type e) { \
return os << to_string(e); \
}
#define DEFINE_ENUM_IMPL_(name) name,
#define DEFINE_CASE_IMPL_(name) case Enum::name: return #name;
/**
* Defines an enum type and a to_string method. This should be given the name
* of the type to define and a macro that defines the enum. The macro will be
* given another macro that should be called repeatedly with the enum to define.
*
* Example:
* \code
* #define OUR_DEFINE_ENUM(DEFINE) \
* DEFINE(EnumValue) \
* DEFINE(OtherValue)
* \endcode
*/
#define DEFINE_ENUM_AND_TO_STRING(Type, DEFINE_ENUM) \
DEFINE_ENUM_AND_TO_STRING_GENERIC_(Type, DEFINE_ENUM, DEFINE_ENUM_IMPL_, \
DEFINE_CASE_IMPL_)
#define DEFINE_ENUM_IMPL_2_(name, str) name,
#define DEFINE_CASE_IMPL_2_(name, str) case Enum::name: return str;
/**
* @see DEFINE_ENUM_AND_TO_STRING
* This is the same except that the macro given to DEFINE_ENUM should be called
* with two arguments: the enum name and the string value.
*
* Example:
* \code
* #define OUR_DEFINE_ENUM(DEFINE) \
* DEFINE(EnumValue, "enum") \
* DEFINE(OtherValue, "other")
* \endcode
*/
#define DEFINE_ENUM_AND_TO_STRING_2(Type, DEFINE_ENUM) \
DEFINE_ENUM_AND_TO_STRING_GENERIC_(Type, DEFINE_ENUM, DEFINE_ENUM_IMPL_2_, \
DEFINE_CASE_IMPL_2_)
#endif // SHAKA_EMBEDDED_UTIL_MACROS_H_
<file_sep>/shaka/src/util/dynamic_buffer.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_UTIL_DYNAMIC_BUFFER_H_
#define SHAKA_EMBEDDED_UTIL_DYNAMIC_BUFFER_H_
#include <list>
#include <memory>
#include <string>
namespace shaka {
namespace util {
/**
* Represents a buffer of bytes that can be appended to without unnecessary
* copies. This does so by storing an array of the sub-buffers it stores. This
* means that you cannot get a singular data pointer. There are helper methods
* that can copy this to a contiguous buffer (e.g. std::string).
*/
class DynamicBuffer {
public:
DynamicBuffer();
~DynamicBuffer();
DynamicBuffer(const DynamicBuffer&) = delete;
DynamicBuffer(DynamicBuffer&&);
DynamicBuffer& operator=(const DynamicBuffer&) = delete;
DynamicBuffer& operator=(DynamicBuffer&&);
/** @return The total size of the buffer, in bytes. */
size_t Size() const;
/** Clears the contents of the buffer. */
void Clear() {
buffers_.clear();
}
/** Appends to the buffer by copying the given data. */
void AppendCopy(const void* buffer, size_t size);
/** @return A new string that contains the data in the buffer. */
std::string CreateString() const;
/** Copies the contents of this buffer to the given buffer. */
void CopyDataTo(uint8_t* dest, size_t size) const;
private:
struct SubBuffer {
SubBuffer(uint8_t* buffer, size_t size);
~SubBuffer();
std::unique_ptr<uint8_t[]> buffer;
size_t size;
};
std::list<SubBuffer> buffers_;
};
} // namespace util
} // namespace shaka
#endif // SHAKA_EMBEDDED_UTIL_DYNAMIC_BUFFER_H_
<file_sep>/shaka/src/mapping/v8/js_engine.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
// Derived from:
// https://chromium.googlesource.com/v8/v8/+/branch-heads/4.8/samples/hello-world.cc
#include "src/mapping/js_engine.h"
#include <libplatform/libplatform.h>
#include <cstring>
namespace shaka {
#ifdef V8_EMBEDDED_SNAPSHOT
// Defined in generated code by //shaka/tools/embed_v8_snapshot.py
void SetupV8Snapshots();
#endif
namespace {
void OnPromiseReject(v8::PromiseRejectMessage message) {
JsEngine::Instance()->OnPromiseReject(message);
}
void InitializeV8IfNeeded() {
static v8::Platform* platform = nullptr;
if (platform)
return;
v8::V8::InitializeICU();
#ifdef V8_EMBEDDED_SNAPSHOT
SetupV8Snapshots();
#endif
platform = v8::platform::CreateDefaultPlatform();
v8::V8::InitializePlatform(platform);
v8::V8::Initialize();
}
} // namespace
// \cond Doxygen_Skip
JsEngine::JsEngine() : isolate_(CreateIsolate()), context_(CreateContext()) {}
JsEngine::~JsEngine() {
context_.Reset();
isolate_->Dispose();
}
v8::Local<v8::Object> JsEngine::global_handle() {
return context_.Get(isolate_)->Global();
}
v8::Local<v8::Value> JsEngine::global_value() {
return context_.Get(isolate_)->Global();
}
void JsEngine::OnPromiseReject(v8::PromiseRejectMessage message) {
// When a Promise gets rejected, we immediately get a
// kPromiseRejectWithNoHandler event. Then, once JavaScript adds a rejection
// handler, we will get a kPromiseHandlerAddedAfterReject event.
if (message.GetEvent() == v8::PromiseRejectEvent::kPromiseRejectWithNoHandler)
promise_handler_.AddPromise(message.GetPromise(), message.GetValue());
else
promise_handler_.RemovePromise(message.GetPromise());
}
void JsEngine::AddDestructor(void* object,
std::function<void(void*)> destruct) {
destructors_.emplace(object, destruct);
}
JsEngine::SetupContext::SetupContext()
: locker(Instance()->isolate_),
handles(Instance()->isolate_),
isolate_scope(Instance()->isolate_),
context_scope(Instance()->context_.Get(Instance()->isolate_)) {}
JsEngine::SetupContext::~SetupContext() {}
void* JsEngine::ArrayBufferAllocator::Allocate(size_t length) {
void* data = AllocateUninitialized(length);
return !data ? data : std::memset(data, 0, length);
}
void* JsEngine::ArrayBufferAllocator::AllocateUninitialized(size_t length) {
return std::malloc(length); // NOLINT
}
void JsEngine::ArrayBufferAllocator::Free(void* data, size_t /* length */) {
auto* destructors = &Instance()->destructors_;
if (destructors->count(data) > 0) {
destructors->at(data)(data);
destructors->erase(data);
}
std::free(data); // NOLINT
}
v8::Isolate* JsEngine::CreateIsolate() {
InitializeV8IfNeeded();
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator = &allocator_;
v8::Isolate* isolate = v8::Isolate::New(create_params);
CHECK(isolate);
isolate->SetCaptureStackTraceForUncaughtExceptions(true);
isolate->SetPromiseRejectCallback(&::shaka::OnPromiseReject);
return isolate;
}
v8::Global<v8::Context> JsEngine::CreateContext() {
v8::Locker locker(isolate_);
v8::HandleScope handles(isolate_);
v8::Local<v8::Context> context = v8::Context::New(isolate_);
return v8::Global<v8::Context>(isolate_, context);
}
// \endcond Doxygen_Skip
} // namespace shaka
<file_sep>/shaka/src/js/eme/media_key_system_configuration.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_EME_MEDIA_KEY_SYSTEM_CONFIGURATION_H_
#define SHAKA_EMBEDDED_JS_EME_MEDIA_KEY_SYSTEM_CONFIGURATION_H_
#include <string>
#include <vector>
#include "shaka/eme/configuration.h"
#include "src/mapping/enum.h"
#include "src/mapping/struct.h"
namespace shaka {
namespace js {
namespace eme {
// Alias the names in shaka::eme to shaka::js::eme for convenience.
using namespace shaka::eme; // NOLINT
struct MediaKeySystemMediaCapability : public Struct {
static std::string name() {
return "MediaKeySystemMediaCapability";
}
ADD_DICT_FIELD(std::string, contentType);
ADD_DICT_FIELD(std::string, robustness);
};
struct MediaKeySystemConfiguration : public Struct {
static std::string name() {
return "MediaKeySystemConfiguration";
}
MediaKeySystemConfiguration();
MediaKeySystemConfiguration(const MediaKeySystemConfiguration&);
MediaKeySystemConfiguration(MediaKeySystemConfiguration&&);
~MediaKeySystemConfiguration() override;
ADD_DICT_FIELD(std::string, label);
ADD_DICT_FIELD(std::vector<MediaKeyInitDataType>, initDataTypes);
ADD_DICT_FIELD(std::vector<MediaKeySystemMediaCapability>, audioCapabilities);
ADD_DICT_FIELD(std::vector<MediaKeySystemMediaCapability>, videoCapabilities);
ADD_DICT_FIELD(MediaKeysRequirement, distinctiveIdentifier);
ADD_DICT_FIELD(MediaKeysRequirement, persistentState);
ADD_DICT_FIELD(std::vector<MediaKeySessionType>, sessionTypes);
};
inline MediaKeySystemConfiguration::MediaKeySystemConfiguration() {}
inline MediaKeySystemConfiguration::~MediaKeySystemConfiguration() {}
inline MediaKeySystemConfiguration::MediaKeySystemConfiguration(
const MediaKeySystemConfiguration&) = default;
inline MediaKeySystemConfiguration::MediaKeySystemConfiguration(
MediaKeySystemConfiguration&&) = default;
} // namespace eme
} // namespace js
} // namespace shaka
// Enums defined in <shaka/eme/configuration.h>
DEFINE_ENUM_MAPPING(shaka::eme, MediaKeysRequirement) {
AddMapping(Enum::Required, "required");
AddMapping(Enum::Optional, "optional");
AddMapping(Enum::NotAllowed, "not-allowed");
}
DEFINE_ENUM_MAPPING(shaka::eme, MediaKeySessionType) {
AddMapping(Enum::Temporary, "temporary");
AddMapping(Enum::PersistentLicense, "persistent-license");
}
DEFINE_ENUM_MAPPING(shaka::eme, MediaKeyInitDataType) {
AddMapping(Enum::Cenc, "cenc");
AddMapping(Enum::KeyIds, "keyids");
AddMapping(Enum::WebM, "webm");
}
DEFINE_ENUM_MAPPING(shaka::eme, MediaKeyMessageType) {
AddMapping(Enum::LicenseRequest, "license-request");
AddMapping(Enum::LicenseRenewal, "license-renewal");
AddMapping(Enum::LicenseRelease, "license-release");
AddMapping(Enum::IndividualizationRequest, "individualization-request");
}
DEFINE_ENUM_MAPPING(shaka::eme, MediaKeyStatus) {
AddMapping(Enum::Usable, "usable");
AddMapping(Enum::Expired, "expired");
AddMapping(Enum::Released, "released");
AddMapping(Enum::OutputRestricted, "output-restricted");
AddMapping(Enum::OutputDownscaled, "output-downscaled");
AddMapping(Enum::StatusPending, "status-pending");
AddMapping(Enum::InternalError, "internal-error");
}
#endif // SHAKA_EMBEDDED_JS_EME_MEDIA_KEY_SYSTEM_CONFIGURATION_H_
<file_sep>/shaka/src/media/ffmpeg_decoded_frame.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_FFMPEG_DECODED_FRAME_H_
#define SHAKA_EMBEDDED_MEDIA_FFMPEG_DECODED_FRAME_H_
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
}
#include <memory>
#include "src/media/base_frame.h"
#include "src/util/macros.h"
namespace shaka {
namespace media {
/** This defines a single decoded media frame. */
class FFmpegDecodedFrame final : public BaseFrame {
public:
~FFmpegDecodedFrame() override;
static FFmpegDecodedFrame* CreateFrame(AVFrame* frame, double time,
double duration);
NON_COPYABLE_OR_MOVABLE_TYPE(FFmpegDecodedFrame);
FrameType frame_type() const override;
size_t EstimateSize() const override;
/** @return The width of the frame in pixels, if this is video. */
int width() const {
return frame_->width;
}
/** @return The height of the frame in pixels, if this is video. */
int height() const {
return frame_->height;
}
/** @return The pixel format of the frame, if this is video. */
AVPixelFormat pixel_format() const {
return static_cast<AVPixelFormat>(frame_->format);
}
/** @return The sample format of the frame, if this is audio. */
AVSampleFormat sample_format() const {
return static_cast<AVSampleFormat>(frame_->format);
}
AVFrame* raw_frame() const {
return frame_;
}
/**
* Gets the raw frame data for this frame. The exact format of the data and
* the size of the data depends on the pixel/sample format.
*
* For hardware-accelerated formats, the data() contains pointers to some
* internal structures to track hardware buffers.
*
* For audio, each element contains an audio channel. Each channel contains
* the samples for that channel in rendering order. The size of the buffer is
* specified in linesize().
*
* For video, it depends on packed vs planar formats. In either case each
* element contains pixel data. It is stored as an array of pixels, left to
* right, top to bottom. linesize() specifies the length of a row of pixels,
* in bytes. The number of rows depends on the pixel format.
*
* For packed video formats, there is only one element that contains all the
* pixel data. The number of rows is equal to the height in pixels.
*
* For planar video formats, each element specifies a plane. For example,
* planar YUV will have three planes: Y, U, and V. The number of rows depends
* on the pixel format.
*/
uint8_t** data() const;
/**
* Gets an array of line sizes for the frame. The exact interpretation and
* number of elements depends on the pixel/sample format. Each element of
* this is associated with an element in data().
*
* @see data()
*/
int* linesize() const;
private:
FFmpegDecodedFrame(AVFrame* frame, double pts, double dts, double duration);
AVFrame* frame_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_FFMPEG_DECODED_FRAME_H_
<file_sep>/shaka/src/media/frame_drawer.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_MEDIA_FRAME_DRAWER_H_
#define SHAKA_EMBEDDED_MEDIA_MEDIA_FRAME_DRAWER_H_
#include <memory>
#include "shaka/frame.h"
#include "src/util/macros.h"
namespace shaka {
namespace media {
class BaseFrame;
/**
* Defines an interface to drawing frames. This takes a decoded frame and
* outputs a hardware texture. This is an abstraction between SDL2 textures
* and native drawing. This also handles converting software frames to a
* texture as needed.
*/
class FrameDrawer {
public:
FrameDrawer();
virtual ~FrameDrawer();
NON_COPYABLE_OR_MOVABLE_TYPE(FrameDrawer);
virtual Frame DrawFrame(const BaseFrame* frame);
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_MEDIA_FRAME_DRAWER_H_
<file_sep>/shaka/src/media/pipeline_manager.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_PIPELINE_MANAGER_H_
#define SHAKA_EMBEDDED_MEDIA_PIPELINE_MANAGER_H_
#include <atomic>
#include <thread>
#include "src/debug/mutex.h"
#include "src/media/types.h"
#include "src/util/clock.h"
namespace shaka {
namespace media {
/**
* Tracks the current playhead time and tracks the pipeline status. This
* handles playback rate, pause/play, and tracking current time. The caller
* is in charge of tracking the amount of content that is buffered and whether
* playback is actually possible.
*
* This type is thread safe; however if calls are made to this from multiple
* threads at once, it is unspecified what order the changes will happen
* including the order of the calls to |on_status_changed|. The callback is
* invoked without the lock held, which allows for calls back into this object;
* but this means that another thread could make a state change before the
* callback is completed. This also means that the callback can be invoked
* multiple times concurrently.
*/
class PipelineManager {
public:
PipelineManager(std::function<void(PipelineStatus)> on_status_changed,
std::function<void()> on_seek, const util::Clock* clock);
virtual ~PipelineManager();
/** Tells the manager that we have gotten all the initialization data. */
virtual void DoneInitializing();
/** @return The current pipeline status. */
virtual PipelineStatus GetPipelineStatus() const;
/** @return The current video duration. */
virtual double GetDuration() const;
/** Sets the video duration. */
virtual void SetDuration(double duration);
/** @return The current video time, in seconds. */
virtual double GetCurrentTime() const;
/** Seeks to the given video time. */
virtual void SetCurrentTime(double time);
/** @return The current playback rate. */
virtual double GetPlaybackRate() const;
/** Sets the current playback rate. */
virtual void SetPlaybackRate(double rate);
/** Starts playing the video. */
virtual void Play();
/** Pauses the video. */
virtual void Pause();
/** Called when the video stalls due to lack of content. */
virtual void Stalled();
/** Called when the video has enough content to play forward. */
virtual void CanPlay();
/**
* Called when the video should end. Note that the current time is always
* clamped to duration, so this only raises the event.
*/
virtual void OnEnded();
/** Called when an error occurs and the pipeline should stop forever. */
virtual void OnError();
private:
/** @return The video time for the given wall-clock time. */
double GetTimeFor(uint64_t wall_time) const;
/**
* Introduces a time sync point. This avoids rounding errors by reducing the
* number of times we change the stored current time. What we do is store
* the video time at a sync point with the wall-clock time. Then, when we
* later need the current video time, we add the change in wall-clock time
* to the previous video time.
*
* This method stores the current video time and the wall-clock time.
*/
void SyncPoint();
mutable SharedMutex mutex_;
const std::function<void(PipelineStatus)> on_status_changed_;
const std::function<void()> on_seek_;
const util::Clock* const clock_;
PipelineStatus status_;
/** The media time at the last sync point. */
double prev_media_time_;
/** The wall-clock time at the last sync point. */
uint64_t prev_wall_time_;
double playback_rate_;
double duration_;
bool autoplay_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_PIPELINE_MANAGER_H_
<file_sep>/shaka/test/src/test/media_files_other.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/test/media_files.h"
#include <gflags/gflags.h>
#include <glog/logging.h>
#include "src/util/file_system.h"
#include "src/util/macros.h"
namespace shaka {
BEGIN_ALLOW_COMPLEX_STATICS
DEFINE_string(media_directory, "",
"The directory that holds the test media files.");
END_ALLOW_COMPLEX_STATICS
/** An existing media file to signal the media directory. */
constexpr const char* kSignalFile = "clear_low.mp4";
/**
* The path to the media directory, relative to a build directory using
* --config-name.
*/
constexpr const char* kRelativePath = "../../shaka/test/media";
void InitMediaFiles(const char* arg0) {
util::FileSystem fs;
if (FLAGS_media_directory.empty()) {
// Look for it in kRelativePath relative to where the executable is.
const std::string test_dir = util::FileSystem::PathJoin(
util::FileSystem::DirName(arg0), kRelativePath);
if (fs.FileExists(util::FileSystem::PathJoin(test_dir, kSignalFile))) {
FLAGS_media_directory = test_dir;
} else {
LOG(FATAL) << "Unable to find the test media directory. Pass "
"--media_directory to give an explicit path.";
}
} else if (!fs.FileExists(util::FileSystem::PathJoin(FLAGS_media_directory,
kSignalFile))) {
LOG(FATAL) << "Invalid value for --media_directory. It should point to "
"\"shaka/test/media\" in the source directory.";
}
}
std::vector<uint8_t> GetMediaFile(const std::string& file_name) {
const std::string path =
util::FileSystem::PathJoin(FLAGS_media_directory, file_name);
util::FileSystem fs;
std::vector<uint8_t> ret;
CHECK(fs.ReadFile(path, &ret));
return ret;
}
} // namespace shaka
<file_sep>/shaka/src/eme/clearkey_implementation.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_EME_CLEARKEY_FACTORY_H_
#define SHAKA_EMBEDDED_EME_CLEARKEY_FACTORY_H_
#include <list>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include "shaka/eme/implementation.h"
#include "shaka/eme/implementation_helper.h"
#define AES_BLOCK_SIZE 16u
namespace shaka {
namespace media {
class MediaProcessorIntegration;
class MediaProcessorDecryptIntegration;
} // namespace media
namespace eme {
class ClearKeyImplementation final : public Implementation {
public:
explicit ClearKeyImplementation(ImplementationHelper* helper);
~ClearKeyImplementation() override;
void Destroy() override;
bool GetExpiration(const std::string& session_id,
int64_t* expiration) const override;
bool GetKeyStatuses(const std::string& session_id,
std::vector<KeyStatusInfo>* statuses) const override;
void SetServerCertificate(EmePromise promise, Data cert) override;
void CreateSessionAndGenerateRequest(
EmePromise promise,
std::function<void(const std::string&)> set_session_id,
MediaKeySessionType session_type, MediaKeyInitDataType init_data_type,
Data data) override;
void Load(const std::string& session_id, EmePromise promise) override;
void Update(const std::string& session_id, EmePromise promise,
Data data) override;
void Close(const std::string& session_id, EmePromise promise) override;
void Remove(const std::string& session_id, EmePromise promise) override;
DecryptStatus Decrypt(EncryptionScheme scheme, EncryptionPattern pattern,
uint32_t block_offset, const uint8_t* key_id,
size_t key_id_size, const uint8_t* iv, size_t iv_size,
const uint8_t* data, size_t data_size,
uint8_t* dest) const override;
private:
struct Session {
struct Key {
Key(std::vector<uint8_t> key_id, std::vector<uint8_t> key);
~Key();
// TODO: Consider storing keys in OpenSSL key objects instead.
std::vector<uint8_t> key_id;
std::vector<uint8_t> key; // This contains the raw AES key.
};
Session();
~Session();
Session(Session&&);
Session(const Session&) = delete;
Session& operator=(Session&&);
Session& operator=(const Session&) = delete;
std::list<Key> keys;
bool callable = false;
};
friend class ClearKeyImplementationTest;
friend class media::MediaProcessorIntegration;
friend class media::MediaProcessorDecryptIntegration;
void LoadKeyForTesting(std::vector<uint8_t> key_id, std::vector<uint8_t> key);
mutable std::mutex mutex_;
std::unordered_map<std::string, Session> sessions_;
ImplementationHelper* helper_;
uint32_t cur_session_id_;
};
} // namespace eme
} // namespace shaka
#endif // SHAKA_EMBEDDED_EME_CLEARKEY_FACTORY_H_
<file_sep>/shaka/src/core/task_runner.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_CORE_TASK_RUNNER_H_
#define SHAKA_EMBEDDED_CORE_TASK_RUNNER_H_
#include <glog/logging.h>
#include <atomic>
#include <functional>
#include <list>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include "src/core/ref_ptr.h"
#include "src/debug/mutex.h"
#include "src/debug/thread.h"
#include "src/debug/thread_event.h"
#include "src/memory/heap_tracer.h"
#include "src/util/utils.h"
namespace shaka {
enum class TaskPriority {
Timer,
Internal,
Events,
Immediate,
};
// The minimum delay (in milliseconds) that a timer can be set to.
constexpr const uint8_t kMinTimerDelay = 4;
namespace impl {
template <typename Func>
using RetOf = typename std::result_of<Func()>::type;
/** Defines a base class for a pending task. */
class PendingTaskBase : public memory::Traceable {
public:
PendingTaskBase(TaskPriority priority, uint64_t delay_ms, int id, bool loop);
~PendingTaskBase() override;
/** Performs the task. */
virtual void Call() = 0;
uint64_t start_ms;
const uint64_t delay_ms;
const TaskPriority priority;
const int id;
const bool loop;
// Using an atomic ensures that writes from another thread are flushed to
// the other threads immediately.
std::atomic<bool> should_remove;
private:
PendingTaskBase(const PendingTaskBase&) = delete;
PendingTaskBase(PendingTaskBase&&) = delete;
PendingTaskBase& operator=(const PendingTaskBase&) = delete;
PendingTaskBase& operator=(PendingTaskBase&&) = delete;
};
/**
* The implementation of a pending task. This stores a copy of the object that
* will be called. This will also trace the object so it remains alive. For
* example, this ensures that a BackingObject remains alive until an event is
* raised.
*/
template <typename Func>
class PendingTask : public PendingTaskBase {
public:
static_assert(std::is_base_of<memory::Traceable,
typename std::decay<Func>::type>::value,
"Traceable callback object must be Traceable");
using Ret = typename std::result_of<Func()>::type;
PendingTask(Func&& callback, const std::string& name, TaskPriority priority,
uint64_t delay_ms, int id, bool loop)
: PendingTaskBase(priority, delay_ms, id, loop),
callback(std::forward<Func>(callback)),
event(new ThreadEvent<Ret>(name)) {}
void Call() override {
// If this were C++17, we could use if-constexpr:
//
// if constexpr (std::is_same<Ret, void>::value) {
// callback();
// event->SignalAllIfNotSet();
// } else {
// event->SignalAllIfNotSet(callback());
// }
SetHelper<Func, Ret>::Set(&callback, &event);
}
void Trace(memory::HeapTracer* tracer) const override {
tracer->Trace(&callback);
}
typename std::decay<Func>::type callback;
std::shared_ptr<ThreadEvent<Ret>> event;
private:
template <typename F, typename R>
struct SetHelper {
static void Set(typename std::decay<F>::type* callback,
std::shared_ptr<ThreadEvent<R>>* event) {
(*event)->SignalAllIfNotSet((*callback)());
}
};
template <typename F>
struct SetHelper<F, void> {
static void Set(typename std::decay<F>::type* callback,
std::shared_ptr<ThreadEvent<void>>* event) {
(*callback)();
(*event)->SignalAllIfNotSet();
}
};
};
template <typename Func>
class PlainCallbackTaskImpl : public memory::Traceable {
public:
explicit PlainCallbackTaskImpl(Func&& callback)
: callback_(std::forward<Func>(callback)) {}
void Trace(memory::HeapTracer*) const override {}
typename std::result_of<Func()>::type operator()() {
return callback_();
}
private:
typename std::decay<Func>::type callback_;
};
template <typename This, typename Member>
class MemberCallbackTaskImpl : public memory::Traceable {
public:
using return_type =
decltype((std::declval<This*>()->*std::declval<Member>())());
MemberCallbackTaskImpl(RefPtr<This> that, Member member)
: that_(that), member_(member) {}
void Trace(memory::HeapTracer* tracer) const override {
tracer->Trace(&that_);
}
return_type operator()() {
return (that_->*member_)();
}
private:
::shaka::Member<This> that_;
Member member_;
};
} // namespace impl
/**
* Creates a task that is backed by a simple C++ callback function. This should
* be used when simply calling another function that doesn't need to be traced.
* This will NOT keep things alive (except for the callback itself), so this
* should not be used for JavaScript objects.
*/
template <typename Func>
impl::PlainCallbackTaskImpl<Func> PlainCallbackTask(Func&& callback) {
// Use a function so we can use argument deduction to deduce |Func|; using the
// constructor directly would require passing the type argument explicitly.
return impl::PlainCallbackTaskImpl<Func>(std::forward<Func>(callback));
}
/**
* Creates a task that traces the given object and then calls the given member
* function on it.
*/
template <typename That, typename Member>
impl::MemberCallbackTaskImpl<That, Member> MemberCallbackTask(That* that,
Member member) {
return impl::MemberCallbackTaskImpl<That, Member>(that, member);
}
/**
* Schedules and manages tasks to be run on a worker thread. This manages a
* background thread to run the tasks. It is safe to call all these methods
* from any thread.
*
* This also tracks object lifetimes to make sure BackingObjects are not freed
* after a callback has been scheduled.
*/
class TaskRunner : public memory::Traceable {
public:
using RunLoop = std::function<void()>;
TaskRunner(std::function<void(RunLoop)> wrapper, bool is_worker);
~TaskRunner() override;
/** @return Whether the background thread is running. */
bool is_running() const {
return running_;
}
/** @return Whether there are pending tasks. */
bool HasPendingWork() const;
/** @return Whether the calling code is running on the worker thread. */
bool BelongsToCurrentThread() const;
/**
* Stops the worker thread. Can only be called when running. Will stop any
* pending tasks and will block until the worker thread is stopped.
*/
void Stop();
/** Blocks the calling thread until the worker has no more work to do. */
void WaitUntilFinished();
void Trace(memory::HeapTracer* tracer) const override;
/**
* Registers an internal task to be called on the worker thread. This
* callback will be given a higher priority than timers.
*
* @see AddTimer
*
* @param priority The priority of the task. Higher priority tasks will run
* before lower priority tasks even if the higher task is registered later.
* @param name The name of the new task, used for debugging.
* @param callback The Traceable callback object.
* @return The task ID and a future that will hold the results.
*/
template <typename Func>
std::shared_ptr<ThreadEvent<impl::RetOf<Func>>> AddInternalTask(
TaskPriority priority, const std::string& name, Func&& callback) {
DCHECK(priority != TaskPriority::Timer) << "Use AddTimer for timers";
std::unique_lock<Mutex> lock(mutex_);
const int id = ++next_id_;
auto pending_task = new impl::PendingTask<Func>(
std::forward<Func>(callback), name, priority, 0, id, /* loop */ false);
tasks_.emplace_back(pending_task);
pending_task->event->SetProvider(&worker_);
return pending_task->event;
}
/**
* Calls the given callback after the given delay on the worker thread. The
* given callback must also be a Traceable object. The callback will be
* traced to keep any JavaScript objects alive. So the |Func| type must
* inherit from Traceable and must define a call operator.
*
* @param delay_ms The time to wait until the callback is called (in
* milliseconds).
* @param callback The Traceable callback object.
* @return The task ID.
*/
template <typename Func>
int AddTimer(uint64_t delay_ms, Func&& callback) {
std::unique_lock<Mutex> lock(mutex_);
if (delay_ms < kMinTimerDelay)
delay_ms = kMinTimerDelay;
const int id = ++next_id_;
tasks_.emplace_back(new impl::PendingTask<Func>(
std::forward<Func>(callback), "", TaskPriority::Timer, delay_ms, id,
/* loop */ false));
return id;
}
/**
* Calls the given callback every |delay_ms| milliseconds on the worker
* thread.
*
* @see AddTimer
*
* @param delay_ms The time to wait until the callback is called (in
* milliseconds).
* @param callback The Traceable callback object.
* @return The task ID.
*/
template <typename Func>
int AddRepeatedTimer(uint64_t delay_ms, Func&& callback) {
std::unique_lock<Mutex> lock(mutex_);
if (delay_ms < kMinTimerDelay)
delay_ms = kMinTimerDelay;
const int id = ++next_id_;
tasks_.emplace_back(new impl::PendingTask<Func>(
std::forward<Func>(callback), "", TaskPriority::Timer, delay_ms, id,
/* loop */ true));
return id;
}
/** Cancels a pending timer with the given ID. */
void CancelTimer(int id);
private:
TaskRunner(const TaskRunner&) = delete;
TaskRunner(TaskRunner&&) = delete;
TaskRunner& operator=(const TaskRunner&) = delete;
TaskRunner& operator=(TaskRunner&&) = delete;
/**
* Called from the worker thread. Should loop until |running_| is false,
* waiting for work to do.
*/
void Run(std::function<void(RunLoop)> wrapper);
/**
* Called when there is no work to be done. This should yield to other
* threads and/or wait until more work is scheduled.
*/
void OnIdle();
/**
* Pops a task from the queue and handles it.
* @return True if there were any task in the queue, false otherwise.
*/
bool HandleTask();
// TODO: Consider a different data structure.
std::list<std::unique_ptr<impl::PendingTaskBase>> tasks_;
mutable Mutex mutex_;
ThreadEvent<void> waiting_;
std::atomic<bool> running_;
int next_id_;
bool is_worker_;
Thread worker_;
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_CORE_TASK_RUNNER_H_
<file_sep>/shaka/src/mapping/js_wrappers.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MAPPING_JS_WRAPPERS_H_
#define SHAKA_EMBEDDED_MAPPING_JS_WRAPPERS_H_
#include <glog/logging.h>
#include <string>
#include <vector>
#include "src/util/macros.h"
#if defined(USING_V8)
# include <v8.h>
# include "src/mapping/v8/v8_utils.h"
#elif defined(USING_JSC)
# include <JavaScriptCore/JavaScriptCore.h>
# include "src/mapping/jsc/jsc_utils.h"
# include "src/util/cfref.h"
#endif
namespace shaka {
class BackingObject;
namespace util {
#ifdef USING_JSC
template <>
struct RefTypeTraits<JSStringRef> {
static constexpr const bool AcquireWithRaw = true;
static JSStringRef Duplicate(JSStringRef arg) {
if (arg)
JSStringRetain(arg);
return arg;
}
static void Release(JSStringRef arg) {
if (arg)
JSStringRelease(arg);
}
};
template <>
struct RefTypeTraits<JSValueRef> {
static constexpr const bool AcquireWithRaw = true;
static JSValueRef Duplicate(JSValueRef arg) {
if (arg)
JSValueProtect(GetContext(), arg);
return arg;
}
static void Release(JSValueRef arg) {
if (arg)
JSValueUnprotect(GetContext(), arg);
}
};
template <>
struct RefTypeTraits<JSObjectRef> : RefTypeTraits<JSValueRef> {
static JSObjectRef Duplicate(JSObjectRef arg) {
if (arg)
JSValueProtect(GetContext(), arg);
return arg;
}
};
#endif
} // namespace util
/**
* This defines several types that are used to represent JavaScript values.
*
* Handle<T> represents a handle to a JavaScript value.
* LocalVar<T> represents a local variable that holds a JavaScript value.
* ReturnVal<T> is a JavaScript value that is returned from a C++ function.
* This is NOT a Handle<T>.
*
* For compatibility, you should not pass a ReturnVal<T> as an argument. Store
* it in a LocalVar<T> first before passing. Also, different types should be
* incompatible with each other (i.e. a JsString is not a JsValue).
*/
#if defined(USING_V8)
template <typename T>
using Handle = v8::Local<T>;
template <typename T>
using LocalVar = v8::Local<T>;
template <typename T>
using ReturnVal = v8::Local<T>;
template <typename T>
struct Global {
Global() {}
template <typename U = T>
explicit Global(v8::Local<U> val) : val_(GetIsolate(), val) {}
template <typename U = T>
operator v8::Local<U>() const {
return val_.Get(GetIsolate());
}
operator bool() const {
return !val_.IsEmpty();
}
template <typename U = T>
Global& operator=(v8::Local<U> other) {
val_.Reset(GetIsolate(), other);
return *this;
}
Global& operator=(std::nullptr_t) {
val_.Reset();
return *this;
}
private:
v8::Global<T> val_;
};
using JsValue = v8::Value;
using JsObject = v8::Object;
using JsString = v8::String;
using JsFunction = v8::Function;
using JsPromise = v8::Promise;
using JsMap = v8::Map;
/**
* Defines the arguments to a JavaScript function. This includes the positional
* arguments passed in as well as |this|. This also includes a special field
* for setting the return value of the function.
*/
using CallbackArguments = v8::FunctionCallbackInfo<v8::Value>;
#elif defined(USING_JSC)
template <typename T>
using Handle = util::CFRef<T>;
template <typename T>
using LocalVar = Handle<T>;
template <typename T>
using ReturnVal = Handle<T>;
template <typename T>
using Global = Handle<T>;
using JsValue = JSValueRef;
using JsObject = JSObjectRef;
using JsString = JSStringRef;
using JsFunction = JSObjectRef;
using JsPromise = JSObjectRef;
using JsMap = JSObjectRef;
class CallbackArguments {
public:
CallbackArguments(const JSValueRef* args, size_t count, JSObjectRef callee,
JSObjectRef thisv, JSValueRef* except);
~CallbackArguments();
size_t length() const {
return count_;
}
JSObjectRef callee() const {
return callee_;
}
JSObjectRef thisv() const {
return this_;
}
ReturnVal<JSValueRef> ret() const {
return ret_;
}
ReturnVal<JsValue> operator[](size_t i) const;
void SetReturn(Handle<JsValue> ret) const;
void SetException(Handle<JsValue> except) const;
private:
// These need to be modifiable within const methods since in V8
// we can modify the return value when the arguments are const.
mutable JSValueRef* except_;
mutable Handle<JsValue> ret_;
const JSObjectRef callee_;
const JSObjectRef this_;
const JSValueRef* args_;
const size_t count_;
};
#endif
// enum class JSValueType
#define DEFINE_ENUM_(DEFINE) \
DEFINE(Undefined) \
DEFINE(Null) \
DEFINE(Boolean) \
DEFINE(Number) \
DEFINE(String) \
DEFINE(Symbol) \
DEFINE(Function) \
DEFINE(Array) \
DEFINE(Promise) \
\
/* \
* These represents native objects that wrap the given primitive value (e.g. \
* |new Number(2)|). \
*/ \
DEFINE(BooleanObject) \
DEFINE(NumberObject) \
DEFINE(StringObject) \
\
DEFINE(ArrayBuffer) \
DEFINE(Int8Array) \
DEFINE(Uint8Array) \
DEFINE(Uint8ClampedArray) \
DEFINE(Int16Array) \
DEFINE(Uint16Array) \
DEFINE(Int32Array) \
DEFINE(Uint32Array) \
DEFINE(Float32Array) \
DEFINE(Float64Array) \
DEFINE(DataView) \
\
/* \
* This is only used for objects that don't fall into any of the above \
* categories. Use IsObject() to check if it is any kind of object. \
*/ \
DEFINE(OtherObject) \
\
DEFINE(Unknown)
DEFINE_ENUM_AND_TO_STRING(JSValueType, DEFINE_ENUM_);
#undef DEFINE_ENUM_
/** @return The number of arguments that were given. */
inline size_t ArgumentCount(const CallbackArguments& arguments) {
#if defined(USING_V8)
return arguments.Length();
#elif defined(USING_JSC)
return arguments.length();
#endif
}
/**
* Get the properties of the current object. This will only return the
* properties on 'this' and not on the prototype.
*
* @param object The object of interest.
* @return The member names found in the given object.
*/
std::vector<std::string> GetMemberNames(Handle<JsObject> object);
/** @return The given member of the given object. */
ReturnVal<JsValue> GetMemberRaw(Handle<JsObject> object,
const std::string& name);
/** @return The member at the given index of the given object. */
ReturnVal<JsValue> GetArrayIndexRaw(Handle<JsObject> object, size_t index);
/** Sets the given member on the given object. */
void SetMemberRaw(Handle<JsObject> object, const std::string& name,
Handle<JsValue> value);
/** Sets the member at the given index of the given object. */
void SetArrayIndexRaw(Handle<JsObject> object, size_t i, Handle<JsValue> value);
/** Adds a generic property on the given object. */
void SetGenericPropertyRaw(Handle<JsObject> object, const std::string& name,
Handle<JsFunction> getter,
Handle<JsFunction> setter);
/**
* Calls the given function as a constructor and gives the resulting object
* or the exception that was thrown.
* @param ctor The constructor to call.
* @param argc The number of arguments to pass in.
* @param argv The array of arguments to pass in.
* @param result_or_except [OUT] Will contain the resulting object or the
* exception that was thrown.
* @return True if the constructor returned an object, false if it threw an
* exception.
*/
bool InvokeConstructor(Handle<JsFunction> ctor, int argc,
LocalVar<JsValue>* argv,
LocalVar<JsValue>* result_or_except);
/**
* Calls the given function and gives the resulting return value or the
* exception that was thrown.
* @param method The method to call.
* @param that The value that should be |this| in the call.
* @param argc The number of arguments to pass in.
* @param argv The array of arguments to pass in.
* @param result_or_except [OUT] Will contain the resulting object or the
* exception that was thrown.
* @return True if the function returned an object, false if it threw an
* exception.
*/
bool InvokeMethod(Handle<JsFunction> method, Handle<JsObject> that, int argc,
LocalVar<JsValue>* argv, LocalVar<JsValue>* result_or_except);
/** @return The given value converted to a string. */
std::string ConvertToString(Handle<JsValue> value);
/** @return A new JavaScript object that wraps the given pointer. */
ReturnVal<JsValue> WrapPointer(void* ptr);
/**
* @return The pointer the given value wraps, or nullptr if not a wrapped
* pointer.
*/
void* MaybeUnwrapPointer(Handle<JsValue> value);
/**
* @return The internal pointer for the given value, or nullptr if it is not
* a backing object.
*/
BackingObject* GetInternalPointer(Handle<JsValue> value);
/**
* Gets whether the given object derives from the given type name. This exists
* so RefPtr<T> can check this without needing the BackingObject header.
*/
bool IsDerivedFrom(BackingObject* ptr, const std::string& name);
/**
* Reads a JavaScript file from the given path and executes it in the current
* isolate.
*
* @param path The file path to the JavaScript file.
*/
bool RunScript(const std::string& path);
/**
* Executes the given JavaScript code in the current isolate.
*
* @param path The file path to the JavaScript file. This is only used for
* logging.
* @param data The contents of the file. It must only contain ASCII and must
* live for the duration of the current isolate.
* @param data_size The number of bytes in |data|.
*/
bool RunScript(const std::string& path, const uint8_t* data, size_t data_size);
/**
* Parses the given string as JSON and returns the given value.
* @param json The input string.
* @return The resulting JavaScrpt value, or nullptr on error.
*/
ReturnVal<JsValue> ParseJsonString(const std::string& json);
/** @return A new string object containing the given UTF-8 string. */
ReturnVal<JsString> JsStringFromUtf8(const std::string& str);
/** @return The JavaScript value |undefined|. */
ReturnVal<JsValue> JsUndefined();
/** @return The JavaScript value |null|. */
ReturnVal<JsValue> JsNull();
/** @return A new JavaScript array object. */
ReturnVal<JsObject> CreateArray(size_t length);
/** @return A new plain JavaScript object. */
ReturnVal<JsObject> CreateObject();
/** @return A new JavaScript Map object. */
ReturnVal<JsMap> CreateMap();
/**
* Sets the value of the given key in the given map. This is not the same as
* SetMemberRaw.
*/
void SetMapValue(Handle<JsMap> map, Handle<JsValue> key, Handle<JsValue> value);
/** @return Whether the given value is |null| or |undefined|. */
bool IsNullOrUndefined(Handle<JsValue> value);
/**
* @return Whether the given value is an object. Unlike typeof, this will
* return false for |null|.
*/
bool IsObject(Handle<JsValue> value);
/**
* @return Whether the given object is an instance of a built-in type. This
* includes both JavaScript-defined types like ArrayBuffer and types defined
* by BackingObjects.
*/
bool IsBuiltInObject(Handle<JsObject> object);
/** @return The type of value contained. */
JSValueType GetValueType(Handle<JsValue> value);
///@{
/**
* Converts the given value to a different type. This only performs debug
* assertions that the type is correct, the caller should check the type
* beforehand (e.g. by using GetValueType).
*/
template <typename Dest>
ReturnVal<Dest> UnsafeJsCast(Handle<JsValue> source) {
#ifdef USING_V8
return source.As<Dest>();
#else
static_assert(std::is_same<Dest, JsValue>::value,
"Should use other specializations");
return source;
#endif
}
#ifdef USING_JSC
template <>
inline ReturnVal<JsObject> UnsafeJsCast<JsObject>(Handle<JsValue> source) {
DCHECK(IsObject(source));
return JSValueToObject(GetContext(), source, nullptr);
}
#endif
///@}
///@{
/** Converts the given value, object, or string into a value type. */
template <typename T>
ReturnVal<JsValue> RawToJsValue(Handle<T> source) {
return source;
}
#if defined(USING_JSC)
template <>
inline ReturnVal<JsValue> RawToJsValue<JsString>(Handle<JsString> source) {
return JSValueMakeString(GetContext(), source);
}
#endif
///@}
inline size_t ArrayLength(Handle<JsObject> value) {
#if defined(USING_V8)
DCHECK_EQ(GetValueType(value), JSValueType::Array);
return value.As<v8::Array>()->Length();
#elif defined(USING_JSC)
auto* ctx = GetContext();
LocalVar<JsValue> length(GetMemberRaw(value, "length"));
CHECK(length && JSValueIsNumber(ctx, length));
return static_cast<size_t>(JSValueToNumber(ctx, length, nullptr));
#endif
}
/**
* @return The primitive number from the given JavaScript number. This must
* be a primitive number or a number object.
*/
double NumberFromValue(Handle<JsValue> value);
/**
* @return The primitive boolean from the given JavaScript boolean. This must
* be a primitive boolean or a boolean object.
*/
bool BooleanFromValue(Handle<JsValue> value);
} // namespace shaka
#endif // SHAKA_EMBEDDED_MAPPING_JS_WRAPPERS_H_
<file_sep>/Makefile.in
# Copyright 2017 Google LLC
#
# Licensed under the Apache License, Version 2.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.
CONFIG_NAME={{CONFIG_NAME}}
SOURCE_ROOT={{SOURCE_ROOT}}
TARGET_OS={{TARGET_OS}}
ifeq ($(CONFIG_NAME),)
BIN_DIR='.'
else
BIN_DIR='$(SOURCE_ROOT)/out/$(CONFIG_NAME)'
endif
.PHONY: all
all: shaka-player
.PHONY: install
install:
@echo 'Installing is not supported yet'; exit 1
.PHONY: clean
clean:
@python '$(SOURCE_ROOT)/build.py' --config-name '$(CONFIG_NAME)' --clean
.PHONY: distclean
distclean: clean
ifeq ($(CONFIG_NAME),)
rm -rf gen obj args.gn build.ninja build.ninja.d toolchain.ninja \
shaka-player.compiled.js Makefile
else
rm -rf '$(SOURCE_ROOT)/out/$(CONFIG_NAME)'
rm Makefile
endif
# TODO: These should be changed to work with iOS/Android targets.
.PHONY: run
run: shaka-player
'$(BIN_DIR)/demo' $(ARGS)
.PHONY: check
check:
@python '$(SOURCE_ROOT)/shaka/tools/presubmit.py' --config-name \
'$(CONFIG_NAME)' $(ARGS)
.PHONY: test
test: shaka-player
@python '$(SOURCE_ROOT)/test.py' --config-name '$(CONFIG_NAME)' $(ARGS)
.PHONY: shaka-player
shaka-player:
@python '$(SOURCE_ROOT)/build.py' --config-name '$(CONFIG_NAME)'
.PHONY: docs
docs: shaka-player
@python '$(SOURCE_ROOT)/gen_docs.py' --config-name '$(CONFIG_NAME)'
<file_sep>/shaka/src/js/eme/media_keys.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_EME_MEDIA_KEYS_H_
#define SHAKA_EMBEDDED_JS_EME_MEDIA_KEYS_H_
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include "shaka/eme/configuration.h"
#include "shaka/eme/implementation.h"
#include "shaka/eme/implementation_factory.h"
#include "shaka/optional.h"
#include "src/core/member.h"
#include "src/core/ref_ptr.h"
#include "src/js/eme/implementation_helper_impl.h"
#include "src/js/eme/media_key_system_configuration.h"
#include "src/mapping/backing_object.h"
#include "src/mapping/backing_object_factory.h"
#include "src/mapping/byte_buffer.h"
#include "src/mapping/exception_or.h"
#include "src/mapping/promise.h"
namespace shaka {
namespace js {
namespace eme {
class MediaKeySession;
class MediaKeys : public BackingObject {
DECLARE_TYPE_INFO(MediaKeys);
public:
MediaKeys(ImplementationFactory* factory, const std::string& key_system,
const MediaKeySystemConfiguration& config);
void Trace(memory::HeapTracer* tracer) const override;
bool valid() const;
ExceptionOr<RefPtr<MediaKeySession>> CreateSession(
optional<MediaKeySessionType> session_type);
Promise SetServerCertificate(ByteBuffer cert);
RefPtr<MediaKeySession> GetSession(const std::string& session_id);
Implementation* GetCdm() const {
return implementation_;
}
private:
mutable std::mutex mutex_;
// TODO: These should be weak pointers.
std::vector<Member<MediaKeySession>> sessions_;
ImplementationHelperImpl helper_;
ImplementationFactory* factory_;
Implementation* implementation_;
};
class MediaKeysFactory : public BackingObjectFactory<MediaKeys> {
public:
MediaKeysFactory();
};
} // namespace eme
} // namespace js
} // namespace shaka
#endif // SHAKA_EMBEDDED_JS_EME_MEDIA_KEYS_H_
<file_sep>/shaka/src/js/events/media_encrypted_event.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_EVENTS_MEDIA_ENCRYPTED_EVENT_H_
#define SHAKA_EMBEDDED_JS_EVENTS_MEDIA_ENCRYPTED_EVENT_H_
#include <memory>
#include <string>
#include <utility>
#include "shaka/optional.h"
#include "src/js/eme/media_key_system_configuration.h"
#include "src/js/events/event.h"
#include "src/mapping/backing_object_factory.h"
#include "src/mapping/byte_buffer.h"
#include "src/mapping/struct.h"
namespace shaka {
namespace js {
namespace events {
struct MediaEncryptedEventInit : Struct {
static std::string name() { return "MediaEncryptedEventInit"; }
ADD_DICT_FIELD(eme::MediaKeyInitDataType, initDataType);
ADD_DICT_FIELD(ByteBuffer, initData);
};
/**
* See: https://w3c.github.io/encrypted-media/#dom-mediaencryptedevent
*/
class MediaEncryptedEvent final : public Event {
DECLARE_TYPE_INFO(MediaEncryptedEvent);
public:
MediaEncryptedEvent(EventType event_type,
eme::MediaKeyInitDataType init_data_type,
ByteBuffer init_data);
static MediaEncryptedEvent* Create(
const std::string& event_type,
optional<MediaEncryptedEventInit> init_data) {
if (init_data.has_value()) {
return new MediaEncryptedEvent(event_type, init_data->initDataType,
std::move(init_data->initData));
} else {
return new MediaEncryptedEvent(
event_type, eme::MediaKeyInitDataType::Cenc, ByteBuffer());
}
}
void Trace(memory::HeapTracer* tracer) const override;
const eme::MediaKeyInitDataType init_data_type;
const ByteBuffer init_data;
private:
MediaEncryptedEvent(const std::string& event_type,
eme::MediaKeyInitDataType init_data_type,
ByteBuffer init_data);
};
class MediaEncryptedEventFactory final
: public BackingObjectFactory<MediaEncryptedEvent, Event> {
public:
MediaEncryptedEventFactory();
};
} // namespace events
} // namespace js
} // namespace shaka
#endif // SHAKA_EMBEDDED_JS_EVENTS_MEDIA_ENCRYPTED_EVENT_H_
<file_sep>/shaka/tools/webidl/webidl/parser.py
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Defines a lex parser for IDL files.
This uses PLY for the basis:
http://www.dabeaz.com/ply/
This parses WebIDL syntax:
https://heycam.github.io/webidl/#idl-grammar
"""
# pylint: disable=g-doc-args
# pylint: disable=g-doc-return-or-yield
# pylint: disable=g-docstring-missing-newline
# pylint: disable=g-no-space-after-docstring-summary
# pylint: disable=g-short-docstring-punctuation
# pylint: disable=invalid-name
# pylint: disable=line-too-long
from __future__ import print_function
import functools
import sys
from ply import lex
from ply import yacc
from webidl import lexer
from webidl import types
__all__ = [
'Features', 'Options', 'IdlSyntaxError', 'IdlParser', 'ParseFile',
]
if sys.version_info[0] == 2:
_number_types = (float, int, long)
else:
_number_types = (float, int)
# Don't use an enum here so an app can use string literals if they want.
class Features(object):
"""Defines possible features."""
# Dictionaries can appear; this is assumed if any dictionary-* features are
# present.
DICTIONARY = 'dictionary'
# Dictionary members can be marked as 'required'.
DICTIONARY_REQUIRED = 'dictionary-required'
# Dictionary members can have a default value given.
DICTIONARY_DEFAULT = 'dictionary-default'
class Options(object):
"""Defines options for what is allowed in the code.
This is used to indicate what features are allowed to be included in the IDL
code. This allows specifying what features are supported by your code
instead of checking for invalid fields/types after parsing is done. This also
will raise a SyntaxError at the unsupported locations to make debugging
easier.
If the Options object is given, then only those features are supported. For
example, this indicates that dictionaries are supported with default field
values:
Options('dictionary-default')
Options(Features.DICTIONARY_DEFAULT)
"""
# If any of the features given have a prefix of item[0], it results in the
# feature item[1] being added.
_ASSUMED_PREFIXES = [
('dictionary-', 'dictionary'),
]
def __init__(self, *args):
possible_features = Options._all_features()
missing = set(args) - possible_features
if missing:
raise ValueError('Unknown feature(s) given: ' + ','.join(missing))
self.features = set(args)
for prefix, feature in Options._ASSUMED_PREFIXES:
if any(item.startswith(prefix) for item in self.features):
self.features.add(feature)
@classmethod
def all(cls):
return cls(*Options._all_features())
@staticmethod
def _all_features():
return {v for k, v in Features.__dict__.items() if k[0] != '_'}
def has_feature(self, feature):
"""Returns whether the given feature is supported."""
if feature not in Options._all_features():
raise ValueError('Unknown feature given: ' + feature)
return feature in self.features
class IdlSyntaxError(SyntaxError):
"""Defines a SyntaxError that may contain multiple errors."""
def __init__(self, errors):
assert errors, 'Must provide at least one error'
super(IdlSyntaxError, self).__init__(*errors[0].args)
self.inner_errors = errors
def _rule(func):
"""A decorator for defining rules."""
assert func.__doc__
assert func.__name__.startswith('p_')
name = func.__name__[2:]
if name.endswith('_error'):
name = name[:-6]
assert func.__doc__.startswith(name + ' :')
@functools.wraps(func)
def wrapper(self, p):
p[0] = func(self, p)
return wrapper
class IdlParser(object):
"""Defines an IDL parser that uses PLY to parse it.
Each member that starts with p_ is a parse rule. The docstring describes the
rule. The |p| argument is the tokens that were read. p[1] is the first
element that was patched. For example:
Indexer : IDENTIFIER '.' IDENTIFIER
| IDENTIFIER '[' Exp ']'
For the above rule, p[1] is the first token, so in either case, it will be the
IDENTIFIER. p[2] will either be a string '.' or a string '[' depending on
which version was matched. For tokens (e.g. '.' or IDENTIFIER), the value in
|p| will be the string value (the |value| field from the token).
The return value can be anything. When that rule result is given to another
rule, that value is passed as-is. In the example above, if the Exp rule
returned a tuple, then that tuple would be in p[3] to the Indexer rule.
The naming style is that all terminals (i.e. things returned from the lexer)
are given names in ALL_CAPS; non-terminals (i.e. rules defined here) use
CamelCase.
"""
def __init__(self, lexer_=None, options=None):
self.errors = []
self.options = options or Options.all()
self.lexer = lexer_ or lexer.IdlLexer()
self.tokens = self.lexer.tokens
self.yacc = yacc.yacc(
module=self, tabmodule=None, optimize=0, debug=0, write_tables=0)
def parse(self, name, contents):
"""Parses the given IDL code into a Results object."""
try:
self.errors = []
self.lexer.set_contents(name, contents)
ret = self.yacc.parse(lexer=self.lexer, tracking=True)
except SyntaxError as e:
# Place this error first since we can't continue parsing with it; but
# keep any errors we saw already.
self.errors = [e] + self.errors
if self.errors:
raise IdlSyntaxError(self.errors)
return types.Results(types=ret)
# Common rules and helpers ---------------------------------------------------
# For some reason, even though this rule is first, the decorators are
# confusing PLY and makes it think this isn't the start.
start = 'Definitions'
@_rule
def p_Definitions(self, p):
r"""Definitions : Definition Definitions
| Empty"""
if len(p) > 2:
return [p[1]] + p[2]
else:
return []
@_rule
def p_Empty(self, _):
r"""Empty :"""
return None
@_rule
def p_MaybeDoc(self, p):
r"""MaybeDoc : DOCSTRING
| Empty"""
return p[1]
def p_error(self, t):
"""Called when an error occurs."""
if t:
line = t.lineno
pos = t.lexpos
prev = self.yacc.symstack[-1]
if t.type == 'DOCSTRING':
msg = ('This treats doc-strings (/** */) special and are only allowed '
'before definitions or members')
elif isinstance(prev, lex.LexToken):
msg = 'Unexpected "%s" after "%s"' % (
self._token_to_str(t), self._token_to_str(prev))
else:
msg = 'Unexpected "%s"' % t.value
else:
prev = self.lexer.last
line = prev.lineno
pos = prev.lexpos
msg = 'Unexpected end of file after "%s"' % prev.value
self._add_error(msg, line, pos)
# Top-level rules ------------------------------------------------------------
@_rule
def p_Definition(self, p):
r"""Definition : Dictionary"""
# TODO: Add remaining definition types (e.g. 'interface', 'mixin', etc.)
return p[1]
@_rule
def p_Dictionary(self, p):
r"""Dictionary : MaybeDoc DICTIONARY IDENTIFIER '{' DictionaryMembers '}' ';'"""
# TODO: Add support for inheritance.
self._check_options(p, 2, Features.DICTIONARY)
debug = self._get_debug(p, 2)
docDebug = self._get_debug(p, 1) if p[1] else None
return types.Dictionary(
name=p[3], attributes=p[5], doc=p[1], debug=debug, docDebug=docDebug)
@_rule
def p_Dictionary_error(self, p):
r"""Dictionary : MaybeDoc DICTIONARY IDENTIFIER '{' error '}' ';'"""
self._check_options(p, 2, Features.DICTIONARY)
return types.Dictionary(
name=p[3], attributes=[], doc=p[1], debug=None, docDebug=None)
@_rule
def p_DictionaryMembers(self, p):
r"""DictionaryMembers : DictionaryMember DictionaryMembers
| Empty"""
if len(p) == 3:
return [p[1]] + p[2]
else:
return []
@_rule
def p_DictionaryMember(self, p):
r"""DictionaryMember : MaybeDoc ExtendedAttributeList DictionaryMemberRest"""
# TODO: Add support for extended attributes.
docDebug = self._get_debug(p, 1) if p[1] else None
return p[3]._replace(doc=p[1], docDebug=docDebug)
@_rule
def p_DictionaryMemberRest(self, p):
r"""DictionaryMemberRest : REQUIRED TypeWithExtendedAttributes IDENTIFIER Default ';'
| Type IDENTIFIER Default ';'"""
debug = self._get_debug(p, 1)
if len(p) > 5:
self._check_options(p, 1, Features.DICTIONARY_REQUIRED)
if p[4] is not None:
self._check_options(p, 4, Features.DICTIONARY_DEFAULT)
return types.Attribute(
name=p[3], type=p[2], default=p[4], is_required=True, doc=None,
debug=debug, docDebug=None)
else:
if p[3] is not None:
self._check_options(p, 3, Features.DICTIONARY_DEFAULT)
return types.Attribute(
name=p[2], type=p[1], default=p[3], is_required=False, doc=None,
debug=debug, docDebug=None)
# Types ----------------------------------------------------------------------
@_rule
def p_TypeWithExtendedAttributes(self, p):
r"""TypeWithExtendedAttributes : ExtendedAttributeList Type"""
# TODO: Add extended attribute support.
return p[2]
@_rule
def p_Type(self, p):
r"""Type : SingleType
| UnionType Null"""
if len(p) == 2:
return p[1]
else:
return p[1]._replace(nullable=p[2])
@_rule
def p_SingleType(self, p):
r"""SingleType : NonAnyType
| ANY"""
if p[1] != 'any':
return p[1]
else:
return types.IdlType(name='any', nullable=False, element_type=None)
@_rule
def p_UnionType(self, p):
r"""UnionType : '(' ')'"""
# TODO: Add union type support.
raise SyntaxError('Union types not supported')
@_rule
def p_NonAnyType(self, p):
r"""NonAnyType : PrimitiveType Null
| StringType Null
| IDENTIFIER Null
| PROMISE '<' ReturnType '>'
| SEQUENCE '<' TypeWithExtendedAttributes '>' Null
| FROZENARRAY '<' TypeWithExtendedAttributes '>' Null"""
# TODO: Add support for record<string, T>.
# Unlike the official grammar definition, this doesn't include entries like
# "Object Null"; these will be handled by the generic "IDENTIFIER Null".
if len(p) == 3:
if isinstance(p[1], types.IdlType):
return p[1]._replace(nullable=p[2])
else:
return types.IdlType(name=p[1], nullable=p[2], element_type=None)
elif len(p) == 5:
return types.IdlType(name='Promise', nullable=False, element_type=p[3])
else:
assert len(p) == 6
return types.IdlType(name=p[1], nullable=p[5], element_type=p[3])
@_rule
def p_ReturnType(self, p):
r"""ReturnType : Type
| VOID"""
if p[1] != 'void':
return p[1]
else:
return types.IdlType(name='void', nullable=False, element_type=None)
@_rule
def p_PrimitiveType(self, p):
r"""PrimitiveType : UNSIGNED LONG LONG
| UNSIGNED LONG
| UNSIGNED SHORT
| LONG LONG
| LONG
| SHORT
| UNRESTRICTED FLOAT
| UNRESTRICTED DOUBLE
| FLOAT
| DOUBLE
| BOOLEAN
| BYTE
| OCTET"""
return types.IdlType(
name=' '.join(p[1:]), nullable=False, element_type=None)
@_rule
def p_StringType(self, p):
r"""StringType : BYTESTRING
| DOMSTRING
| USVSTRING"""
return types.IdlType(name=p[1], nullable=False, element_type=None)
@_rule
def p_Null(self, p):
r"""Null : '?'
| Empty"""
return p[1] == '?'
# Extended attributes --------------------------------------------------------
@_rule
def p_ExtendedAttributeList(self, p):
r"""ExtendedAttributeList :"""
# TODO: Add support for extended attributes.
# Constants ------------------------------------------------------------------
@_rule
def p_Default(self, p):
r"""Default : '=' DefaultValue
| Empty"""
if len(p) > 2:
return p[2]
else:
return None
@_rule
def p_DefaultValue(self, p):
r"""DefaultValue : ConstValue
| STRING_LITERAL
| '[' ']'"""
if len(p) == 2:
# STRING_LITERAL values are converted by the lexer; ConstValue also
# returns the converted value.
return p[1]
else:
return []
@_rule
def p_ConstValue(self, p):
r"""ConstValue : TRUE
| FALSE
| FLOAT_LITERAL
| NAN
| INFINITY
| '-' INFINITY
| INTEGER_LITERAL
| NULL"""
if len(p) == 3:
return float('-inf')
elif isinstance(p[1], _number_types):
# FLOAT_LITERAL and INTEGER_LITERAL values are converted by the lexer.
return p[1]
else:
map_ = {
'true': True,
'false': False,
'NaN': float('nan'),
'Infinity': float('inf'),
'null': types.IdlNull,
}
return map_[p[1]]
# Helpers functions ----------------------------------------------------------
def _add_error(self, message, line, offset):
"""Adds a new error to the error list."""
line_text = self.lexer.get_line(offset)
col = self.lexer.get_col(offset)
self.errors.append(SyntaxError(
message, (self.lexer.file_name, line, col, line_text)))
def _check_options(self, p, idx, feature):
"""Checks that the given feature is allowed, and adds an error otherwise."""
if self.options.has_feature(feature):
return
self._add_error('Feature "%s" is not allowed by options' % feature,
p.lineno(idx), p.lexpos(idx))
def _get_debug(self, p, idx):
"""Gets a DebugInfo for the given token."""
offset = p.lexpos(idx)
return types.DebugInfo(lineno=p.lineno(idx), col=self.lexer.get_col(offset),
line=self.lexer.get_line(offset))
def _token_to_str(self, t):
"""Gets a string representation of a token for errors."""
special_tokens = {
'STRING_LITERAL', 'DOCSTRING', 'FLOAT_LITERAL', 'INTEGER_LITERAL',
}
if t.type in special_tokens:
return t.type
else:
return t.value
def ParseFile(name, contents, options=None):
"""Parses the given IDL file."""
parser = IdlParser(options=options)
return parser.parse(name, contents)
<file_sep>/shaka/src/js/dom/node.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/dom/node.h"
#include "src/js/dom/document.h"
#include "src/js/dom/element.h"
#include "src/js/js_error.h"
#include "src/memory/heap_tracer.h"
namespace shaka {
namespace js {
namespace dom {
Node::Node(NodeType type, RefPtr<Document> document)
: owner_document_(document), node_type_(type) {
DCHECK(!document.empty() || type == DOCUMENT_NODE);
}
// \cond Doxygen_Skip
Node::~Node() {}
// \endcond Doxygen_Skip
void Node::Trace(memory::HeapTracer* tracer) const {
events::EventTarget::Trace(tracer);
for (auto& child : children_)
tracer->Trace(&child);
tracer->Trace(&owner_document_);
tracer->Trace(&parent_);
}
bool Node::IsShortLived() const {
return true;
}
RefPtr<Document> Node::document() const {
return owner_document_;
}
RefPtr<Node> Node::parent_node() const {
return parent_;
}
std::vector<RefPtr<Node>> Node::child_nodes() const {
return std::vector<RefPtr<Node>>(children_.begin(), children_.end());
}
RefPtr<Node> Node::first_child() const {
return children_.empty() ? nullptr : children_.front();
}
RefPtr<Node> Node::last_child() const {
return children_.empty() ? nullptr : children_.back();
}
RefPtr<Node> Node::AppendChild(RefPtr<Node> new_child) {
CHECK(is_element() || node_type_ == DOCUMENT_NODE);
CHECK(new_child);
CHECK(!new_child->parent_node());
new_child->parent_ = this;
children_.emplace_back(new_child);
return new_child;
}
RefPtr<Node> Node::RemoveChild(RefPtr<Node> to_remove) {
CHECK(is_element() || node_type_ == DOCUMENT_NODE);
CHECK(to_remove);
CHECK_EQ(to_remove->parent_node(), this);
to_remove->parent_ = nullptr;
util::RemoveElement(&children_, to_remove);
return to_remove;
}
NodeFactory::NodeFactory() {
AddConstant("ELEMENT_NODE", Node::ELEMENT_NODE);
AddConstant("ATTRIBUTE_NODE", Node::ATTRIBUTE_NODE);
AddConstant("TEXT_NODE", Node::TEXT_NODE);
AddConstant("CDATA_SECTION_NODE", Node::CDATA_SECTION_NODE);
AddConstant("ENTITY_REFERENCE_NODE", Node::ENTITY_REFERENCE_NODE);
AddConstant("ENTITY_NODE", Node::ENTITY_NODE);
AddConstant("PROCESSING_INSTRUCTION_NODE", Node::PROCESSING_INSTRUCTION_NODE);
AddConstant("COMMENT_NODE", Node::COMMENT_NODE);
AddConstant("DOCUMENT_NODE", Node::DOCUMENT_NODE);
AddConstant("DOCUMENT_TYPE_NODE", Node::DOCUMENT_TYPE_NODE);
AddConstant("DOCUMENT_FRAGMENT_NODE", Node::DOCUMENT_FRAGMENT_NODE);
AddConstant("NOTATION_NODE", Node::NOTATION_NODE);
AddConstant("NOTATION_NODE", Node::NOTATION_NODE);
AddConstant("DOCUMENT_POSITION_DISCONNECTED",
Node::DOCUMENT_POSITION_DISCONNECTED);
AddConstant("DOCUMENT_POSITION_PRECEDING", Node::DOCUMENT_POSITION_PRECEDING);
AddConstant("DOCUMENT_POSITION_FOLLOWING", Node::DOCUMENT_POSITION_FOLLOWING);
AddConstant("DOCUMENT_POSITION_CONTAINS", Node::DOCUMENT_POSITION_CONTAINS);
AddConstant("DOCUMENT_POSITION_CONTAINED_BY",
Node::DOCUMENT_POSITION_CONTAINED_BY);
AddConstant("DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC",
Node::DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC);
AddGenericProperty("ownerDocument", &Node::document);
AddGenericProperty("nodeType", &Node::node_type);
AddGenericProperty("nodeName", &Node::node_name);
AddGenericProperty("parentNode", &Node::parent_node);
AddGenericProperty("childNodes", &Node::child_nodes);
AddGenericProperty("firstChild", &Node::first_child);
AddGenericProperty("lastChild", &Node::last_child);
AddGenericProperty("nodeValue", &Node::NodeValue);
AddGenericProperty("textContent", &Node::TextContent);
AddMemberFunction("appendChild", &Node::AppendChild);
AddMemberFunction("removeChild", &Node::RemoveChild);
NotImplemented("parentElement");
NotImplemented("previousSibling");
NotImplemented("nextSibling");
NotImplemented("hasChildNodes");
NotImplemented("getRootNode");
NotImplemented("normalize");
NotImplemented("contains");
NotImplemented("insertBefore");
NotImplemented("replaceChild");
NotImplemented("isConnected");
NotImplemented("baseURI");
NotImplemented("cloneNode");
NotImplemented("compareDocumentPosition");
NotImplemented("lookupPrefix");
NotImplemented("isDefaultNamespace");
NotImplemented("isEqualNode");
NotImplemented("isSameNode");
}
} // namespace dom
} // namespace js
} // namespace shaka
<file_sep>/shaka/src/public/data.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "shaka/eme/data.h"
#include <glog/logging.h>
#include "src/core/ref_ptr.h"
#include "src/js/eme/media_key_session.h"
#include "src/mapping/byte_buffer.h"
#include "src/memory/object_tracker.h"
#include "src/util/macros.h"
namespace shaka {
namespace eme {
class Data::Impl {
public:
explicit Impl(ByteBuffer buffer) {
// We need to register the object before we can store it in the RefPtr<T>.
auto* temp = new ByteBuffer(std::move(buffer));
memory::ObjectTracker::Instance()->RegisterObject(temp);
this->buffer.reset(temp);
}
~Impl() {}
NON_COPYABLE_OR_MOVABLE_TYPE(Impl);
RefPtr<ByteBuffer> buffer;
};
Data::Data(Data&& other) = default;
Data::~Data() {}
Data& Data::operator=(Data&& other) = default;
const uint8_t* Data::data() const {
return impl_->buffer->data();
}
size_t Data::size() const {
return impl_->buffer->size();
}
Data::Data(ByteBuffer* buffer) : impl_(new Impl(std::move(*buffer))) {}
} // namespace eme
} // namespace shaka
<file_sep>/shaka/src/media/frame_converter.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/frame_converter.h"
extern "C" {
#include <libavutil/hwcontext.h>
}
namespace shaka {
namespace media {
namespace {
bool IsHardwarePixelFormat(AVPixelFormat format) {
switch (format) {
case AV_PIX_FMT_VIDEOTOOLBOX:
case AV_PIX_FMT_VAAPI:
case AV_PIX_FMT_VDPAU:
case AV_PIX_FMT_QSV:
case AV_PIX_FMT_MMAL:
case AV_PIX_FMT_D3D11VA_VLD:
case AV_PIX_FMT_CUDA:
case AV_PIX_FMT_XVMC:
case AV_PIX_FMT_MEDIACODEC:
case AV_PIX_FMT_D3D11:
case AV_PIX_FMT_OPENCL:
return true;
default:
return false;
}
}
} // namespace
FrameConverter::FrameConverter() : cpu_frame_(nullptr) {}
FrameConverter::~FrameConverter() {
if (cpu_frame_)
av_frame_free(&cpu_frame_);
#ifdef HAS_SWSCALE
sws_freeContext(sws_ctx_);
av_freep(&convert_frame_data_[0]);
#endif
}
bool FrameConverter::ConvertFrame(const AVFrame* frame, uint8_t* const** data,
const int** linesize,
AVPixelFormat desired_pixel_format) {
if (IsHardwarePixelFormat(static_cast<AVPixelFormat>(frame->format))) {
if (!cpu_frame_) {
cpu_frame_ = av_frame_alloc();
if (!cpu_frame_) {
LOG(ERROR) << "Error allocating frame for conversion";
return false;
}
}
av_frame_unref(cpu_frame_);
const int copy_code = av_hwframe_transfer_data(cpu_frame_, frame, 0);
if (copy_code < 0) {
LOG(ERROR) << "Error transferring frame data to CPU: " << copy_code;
return false;
}
frame = cpu_frame_;
}
if (frame->format == desired_pixel_format) {
*data = frame->data;
*linesize = frame->linesize;
return true;
}
#ifdef HAS_SWSCALE
if (frame->width != convert_frame_width_ ||
frame->height != convert_frame_height_ ||
desired_pixel_format != convert_pixel_format_) {
av_freep(&convert_frame_data_[0]);
if (av_image_alloc(convert_frame_data_, convert_frame_linesize_,
frame->width, frame->height, desired_pixel_format,
16) < 0) {
LOG(ERROR) << "Error allocating frame for conversion";
return false;
}
convert_frame_width_ = frame->width;
convert_frame_height_ = frame->height;
convert_pixel_format_ = desired_pixel_format;
}
sws_ctx_ = sws_getCachedContext(
sws_ctx_, frame->width, frame->height,
static_cast<AVPixelFormat>(frame->format), frame->width, frame->height,
desired_pixel_format, 0, nullptr, nullptr, nullptr);
if (!sws_ctx_) {
LOG(ERROR) << "Error allocating conversion context";
return false;
}
sws_scale(sws_ctx_, frame->data, frame->linesize, 0, frame->height,
convert_frame_data_, convert_frame_linesize_);
*data = convert_frame_data_;
*linesize = convert_frame_linesize_;
return true;
#else
LOG_ONCE(INFO) << "Not built to convert pixel formats";
return false;
#endif
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/media/decoder_thread.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_DECODER_THREAD_H_
#define SHAKA_EMBEDDED_MEDIA_DECODER_THREAD_H_
#include <atomic>
#include <functional>
#include "src/debug/thread.h"
#include "src/media/types.h"
#include "src/util/macros.h"
namespace shaka {
namespace eme {
class Implementation;
} // namespace eme
namespace media {
class MediaProcessor;
class PipelineManager;
class Stream;
/**
* Handles the thread that decodes input content. This handles synchronizing
* the threads and connecting the decoder part of MediaProcessor to the Stream.
*/
class DecoderThread {
public:
/**
* @param get_time A callback to get the current playhead time. This will be
* called from the background thread.
* @param seek_done A callback for when a frame has been decoded after a seek.
* @param on_waiting_for_key A callback for when the decoder is waiting for
* an encryption key.
* @param on_error A callback for when there is a decoder error.
* @param processor The processor that will process the media.
* @param pipeline The pipeline that is used to determine the range of media.
* @param stream The stream to pull frames from.
*/
DecoderThread(std::function<double()> get_time,
std::function<void()> seek_done,
std::function<void()> on_waiting_for_key,
std::function<void(Status)> on_error,
MediaProcessor* processor,
PipelineManager* pipeline,
Stream* stream);
~DecoderThread();
NON_COPYABLE_OR_MOVABLE_TYPE(DecoderThread);
/** Stops the background thread and joins it. */
void Stop();
/**
* Called when the video seeks. This should reset any internal data and start
* over decoding.
*/
void OnSeek();
void SetCdm(eme::Implementation* cdm);
private:
void ThreadMain();
MediaProcessor* processor_;
PipelineManager* pipeline_;
Stream* stream_;
std::function<double()> get_time_;
std::function<void()> seek_done_;
std::function<void()> on_waiting_for_key_;
std::function<void(Status)> on_error_;
std::atomic<eme::Implementation*> cdm_;
std::atomic<bool> shutdown_;
std::atomic<bool> is_seeking_;
std::atomic<bool> did_flush_;
std::atomic<double> last_frame_time_;
bool raised_waiting_event_ = false;
Thread thread_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_DECODER_THREAD_H_
<file_sep>/shaka/src/core/task_runner.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/core/task_runner.h"
#include <glog/logging.h>
#include <chrono>
#include <limits>
#include "src/mapping/js_wrappers.h"
#include "src/util/clock.h"
namespace shaka {
namespace impl {
PendingTaskBase::PendingTaskBase(TaskPriority priority, uint64_t delay_ms,
int id, bool loop)
: start_ms(util::Clock::Instance.GetMonotonicTime()),
delay_ms(delay_ms),
priority(priority),
id(id),
loop(loop),
should_remove(false) {}
PendingTaskBase::~PendingTaskBase() {}
} // namespace impl
TaskRunner::TaskRunner(std::function<void(RunLoop)> wrapper, bool is_worker)
: mutex_(is_worker ? "TaskRunner worker" : "TaskRunner main"),
waiting_("TaskRunner wait until finished"),
running_(true),
next_id_(0),
is_worker_(is_worker),
worker_(is_worker ? "JS Worker" : "JS Main Thread",
std::bind(&TaskRunner::Run, this, std::move(wrapper))) {
waiting_.SetProvider(&worker_);
}
TaskRunner::~TaskRunner() {
Stop();
}
bool TaskRunner::HasPendingWork() const {
std::unique_lock<Mutex> lock(mutex_);
for (auto& task : tasks_) {
if (!task->loop)
return true;
}
return false;
}
bool TaskRunner::BelongsToCurrentThread() const {
return running_ && std::this_thread::get_id() == worker_.get_id();
}
void TaskRunner::Stop() {
bool join = false;
{
std::unique_lock<Mutex> lock(mutex_);
if (running_) {
running_ = false;
join = true;
waiting_.SignalAllIfNotSet();
}
}
if (join) {
worker_.join();
}
}
void TaskRunner::WaitUntilFinished() {
if (running_ && HasPendingWork()) {
std::unique_lock<Mutex> lock(mutex_);
waiting_.ResetAndWaitWhileUnlocked(lock);
}
}
void TaskRunner::Trace(memory::HeapTracer* tracer) const {
std::unique_lock<Mutex> lock(mutex_);
for (auto& task : tasks_) {
DCHECK(task);
task->Trace(tracer);
}
}
void TaskRunner::CancelTimer(int id) {
std::unique_lock<Mutex> lock(mutex_);
for (auto& task : tasks_) {
if (task->id == id) {
task->should_remove = true;
return;
}
}
}
void TaskRunner::Run(std::function<void(RunLoop)> wrapper) {
wrapper([this]() {
while (running_) {
// Handle a task. This will only handle one task, then loop.
if (HandleTask())
continue;
if (!HasPendingWork()) {
waiting_.SignalAllIfNotSet();
}
// We don't have any work to do, wait for a while.
OnIdle();
}
// If we stop early, delete any pending tasks. This must be done on the
// worker thread so we can delete JavaScript objects.
tasks_.clear();
waiting_.SignalAllIfNotSet();
});
}
void TaskRunner::OnIdle() {
// TODO: Since we have no work, we will never add work ourselves. Consider
// using signalling rather than polling.
util::Clock::Instance.SleepSeconds(0.001);
}
bool TaskRunner::HandleTask() {
// We need to be careful here because:
// 1) We may be called from another thread to change tasks.
// 2) The callback may change tasks (including its own).
const uint64_t now = util::Clock::Instance.GetMonotonicTime();
impl::PendingTaskBase* task = nullptr;
{
// Find the earliest timer we can finish. If there are multiple with the
// same time, pick the one registered earlier (lower ID).
std::unique_lock<Mutex> lock(mutex_);
uint64_t min_time = std::numeric_limits<uint64_t>::max();
TaskPriority max_priority = TaskPriority::Timer;
for (auto it = tasks_.begin(); it != tasks_.end();) {
if ((*it)->should_remove) {
it = tasks_.erase(it);
} else {
if ((*it)->priority > max_priority) {
max_priority = (*it)->priority;
task = it->get();
} else if (max_priority == TaskPriority::Timer) {
const uint64_t it_time = (*it)->start_ms + (*it)->delay_ms;
if (it_time < now && it_time < min_time) {
min_time = it_time;
task = it->get();
}
}
++it;
}
}
}
if (!task)
return false;
#ifdef USING_V8
if (!is_worker_) {
// V8 attaches v8::Local<T> instances to the most recent v8::HandleScope
// instance. By having a scope here, the task can create local handles and
// they will be freed after the task finishes.
v8::HandleScope handles(GetIsolate());
task->Call();
} else {
task->Call();
}
#else
// Other JavaScript engines use ref-counting for local handles.
task->Call();
(void)is_worker_;
#endif
if (task->loop) {
task->start_ms = now;
} else {
task->should_remove = true;
// Will be removed in the next iteration.
}
return true;
}
} // namespace shaka
<file_sep>/shaka/tools/gen_config_h.py
#!/usr/bin/python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Generates the shaka config.h file."""
import argparse
import os
import sys
def _GenConfig(parsed_args, out):
print >>out, '// Copyright 2018 Google Inc. All rights reserved.'
if parsed_args.sdl_utils:
print >>out, '#define SHAKA_SDL_UTILS 1'
else:
print >>out, '#undef SHAKA_SDL_UTILS'
def main(argv):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', required=True,
help='The path to the file to generate.')
parser.add_argument('--sdl-utils', action='store_true',
help='Include SDL utils in the library.')
parsed_args = parser.parse_args(argv)
output_dir = os.path.dirname(parsed_args.output)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(parsed_args.output, 'w') as f:
_GenConfig(parsed_args, f)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
<file_sep>/shaka/src/mapping/convert_js.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MAPPING_CONVERT_JS_H_
#define SHAKA_EMBEDDED_MAPPING_CONVERT_JS_H_
#include <cmath>
#include <limits>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
#include "shaka/optional.h"
#include "shaka/variant.h"
#include "src/mapping/backing_object.h"
#include "src/mapping/generic_converter.h"
#include "src/mapping/js_wrappers.h"
#include "src/util/templates.h"
namespace shaka {
namespace impl {
// Types used to identify a category of types. These allow a specialization of
// ConvertHelper to be used on a set of types (for example, numbers).
struct _number_identifier {};
struct _generic_converter_identifier {};
/**
* A template type that defines two conversion functions to convert between C++
* and JavaScript. This should be instantiated with a single type argument for
* the type being converted (without cv-qualifiers or references). The second
* template argument is deduced based on the first. It is used to select
* which specialization to use.
*
* It is fine to add more specializations after this, so long as it appears
* before it is being used. If the specialization is for a specific type
* (e.g. MyType), or it is for a templated type (e.g. std::vector<T>), you
* can just add a new specialization:
*
* \code
* template <> struct ConvertHelper<MyType, void> { ... };
* // -or-
* template <typename T> struct ConvertHelper<std::vector<T>, void> { ... };
* \endcode
*
* If the specialization is for a "category" of types (e.g. numbers, where the
* type would be T), then you need to add a new identifier above and a new
* selector to the conditions here.
*/
template <typename T, typename = typename std::conditional<
util::is_number<T>::value, _number_identifier,
typename std::conditional<
std::is_base_of<GenericConverter, T>::value,
_generic_converter_identifier, void>::type>::type>
struct ConvertHelper;
template <typename Number>
struct ConvertHelper<Number, _number_identifier> {
static bool FromJsValue(Handle<JsValue> source, Number* dest) {
// Number types.
const JSValueType type = GetValueType(source);
if (type != JSValueType::Number && type != JSValueType::NumberObject) {
return false;
}
const double value = NumberFromValue(source);
if (std::numeric_limits<Number>::has_infinity &&
std::abs(value) == std::numeric_limits<Number>::infinity()) {
// OK.
} else if (value < std::numeric_limits<Number>::lowest() ||
value > std::numeric_limits<Number>::max()) {
return false;
}
// JavaScript numbers will be intentionally truncated if stored as native
// integers.
*dest = static_cast<Number>(value);
return true;
}
static ReturnVal<JsValue> ToJsValue(Number source) {
#if defined(USING_V8)
return v8::Number::New(GetIsolate(), source);
#elif defined(USING_JSC)
return JSValueMakeNumber(GetContext(), source);
#endif
}
};
template <typename T>
struct ConvertHelper<T, _generic_converter_identifier> {
static bool FromJsValue(Handle<JsValue> source, T* dest) {
return dest->TryConvert(source);
}
static ReturnVal<JsValue> ToJsValue(const T& source) {
return source.ToJsValue();
}
};
template <typename T>
struct ConvertHelper<shaka::optional<T>, void> {
static bool FromJsValue(Handle<JsValue> source, shaka::optional<T>* dest) {
if (IsNullOrUndefined(source)) {
dest->reset();
return true;
}
T temp;
if (!ConvertHelper<T>::FromJsValue(source, &temp))
return false;
*dest = std::move(temp);
return true;
}
static ReturnVal<JsValue> ToJsValue(const shaka::optional<T>& source) {
if (source.has_value()) {
return ConvertHelper<T>::ToJsValue(source.value());
} else {
return JsNull();
}
}
};
template <typename... Types>
struct ConvertHelper<shaka::variant<Types...>> {
private:
template <size_t I, typename = void>
struct Helper {
using T = variant_alternative_t<I, shaka::variant<Types...>>;
static bool FromJsValue(Handle<JsValue> source,
shaka::variant<Types...>* dest) {
T temp;
if (ConvertHelper<T>::FromJsValue(source, &temp)) {
dest->template emplace<I>(std::move(temp));
return true;
}
return Helper<I + 1>::FromJsValue(source, dest);
}
static ReturnVal<JsValue> ToJsValue(
const shaka::variant<Types...>& source) {
if (source.index() == I)
return ConvertHelper<T>::ToJsValue(get<I>(source));
else
return Helper<I + 1>::ToJsValue(source);
}
};
template <typename Dummy>
struct Helper<sizeof...(Types) - 1, Dummy> {
static constexpr const size_t I = sizeof...(Types) - 1;
using T = variant_alternative_t<I, shaka::variant<Types...>>;
static bool FromJsValue(Handle<JsValue> source,
shaka::variant<Types...>* dest) {
T temp;
if (ConvertHelper<T>::FromJsValue(source, &temp)) {
dest->template emplace<I>(std::move(temp));
return true;
}
return false;
}
static ReturnVal<JsValue> ToJsValue(
const shaka::variant<Types...>& source) {
CHECK_EQ(source.index(), I);
return ConvertHelper<T>::ToJsValue(get<I>(source));
}
};
public:
static bool FromJsValue(Handle<JsValue> source,
shaka::variant<Types...>* dest) {
return Helper<0>::FromJsValue(source, dest);
}
static ReturnVal<JsValue> ToJsValue(const shaka::variant<Types...>& source) {
return Helper<0>::ToJsValue(source);
}
};
template <typename T>
struct ConvertHelper<std::vector<T>, void> {
static bool FromJsValue(Handle<JsValue> source, std::vector<T>* dest) {
if (GetValueType(source) != JSValueType::Array)
return false;
LocalVar<JsObject> array(UnsafeJsCast<JsObject>(source));
const size_t length = ArrayLength(array);
// Store the data in a temp array since this should not modify |*dest| on
// failure.
std::vector<T> temp(length);
DCHECK_EQ(length, temp.size());
for (size_t i = 0; i < length; i++) {
LocalVar<JsValue> item(GetArrayIndexRaw(array, i));
if (!ConvertHelper<T>::FromJsValue(item, &temp[i]))
return false;
}
swap(temp, *dest);
return true;
}
static ReturnVal<JsValue> ToJsValue(const std::vector<T>& source) {
LocalVar<JsObject> ret(CreateArray(source.size()));
for (size_t i = 0; i < source.size(); i++) {
LocalVar<JsValue> item(ConvertHelper<T>::ToJsValue(source[i]));
SetArrayIndexRaw(ret, i, item);
}
return RawToJsValue(ret);
}
};
template <typename Key, typename Value>
struct ConvertHelper<std::unordered_map<Key, Value>, void> {
static ReturnVal<JsValue> ToJsValue(
const std::unordered_map<Key, Value>& source) {
LocalVar<JsMap> ret(CreateMap());
for (auto& pair : source) {
LocalVar<JsValue> key(ConvertHelper<Key>::ToJsValue(pair.first));
LocalVar<JsValue> value(ConvertHelper<Value>::ToJsValue(pair.second));
SetMapValue(ret, key, value);
}
return RawToJsValue(ret);
}
};
template <typename T>
struct ConvertHelper<T*, void> {
static_assert(std::is_base_of<BackingObject, T>::value,
"Don't accept raw pointers as arguments, use RefPtr<T>.");
static ReturnVal<JsValue> ToJsValue(T* source) {
// We cannot implicitly convert a T* to a RefPtr<T> because the compiler
// cannot deduce the type parameter. This allows us to pass raw pointers
// (e.g. |this|).
if (!source)
return JsNull();
else
return source->JsThis();
}
};
template <>
struct ConvertHelper<std::string, void> {
static bool FromJsValue(Handle<JsValue> source, std::string* dest) {
const JSValueType type = GetValueType(source);
if (type != JSValueType::String && type != JSValueType::StringObject)
return false;
*dest = ConvertToString(source);
return true;
}
static ReturnVal<JsValue> ToJsValue(const std::string& source) {
LocalVar<JsString> str(JsStringFromUtf8(source));
return RawToJsValue(str);
}
};
// Note this is only hit for the |bool| type, NOT for things that can be
// implicitly cast to bool, like pointers.
template <>
struct ConvertHelper<bool, void> {
static bool FromJsValue(Handle<JsValue> source, bool* dest) {
const JSValueType type = GetValueType(source);
if (type != JSValueType::Boolean && type != JSValueType::BooleanObject)
return false;
*dest = BooleanFromValue(source);
return true;
}
static ReturnVal<JsValue> ToJsValue(bool source) {
#if defined(USING_V8)
return v8::Boolean::New(GetIsolate(), source);
#elif defined(USING_JSC)
return JSValueMakeBoolean(GetContext(), source);
#endif
}
};
} // namespace impl
/**
* Tries to convert the given JavaScript value to the given type.
* @param source The JavaScript object to convert.
* @param dest [OUT] Where to put the converted value, not changed if there is
* an error.
* @return True on success, false on error.
*/
template <typename T>
bool FromJsValue(Handle<JsValue> source, T* dest) {
using BaseT = typename std::decay<T>::type;
return impl::ConvertHelper<BaseT>::FromJsValue(source, dest);
}
/**
* Converts the given C++ object to a JavaScript value.
* @param source The C++ object to convert.
* @returns A new JavaScript value.
*/
template <typename T>
ReturnVal<JsValue> ToJsValue(T&& source) {
using BaseT = typename std::decay<T>::type;
return impl::ConvertHelper<BaseT>::ToJsValue(std::forward<T>(source));
}
} // namespace shaka
#endif // SHAKA_EMBEDDED_MAPPING_CONVERT_JS_H_
<file_sep>/shaka/test/src/util/shared_lock_unittest.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/util/shared_lock.h"
#include <gtest/gtest.h>
#include <algorithm>
#include <atomic>
#include <condition_variable>
#include <mutex>
#include "src/test/test_utils.h"
namespace shaka {
namespace util {
namespace {
template <typename T>
std::vector<std::thread> make_n_threads(size_t count, T cb) {
std::vector<std::thread> ret;
ret.reserve(count);
while (count-- > 0) {
ret.emplace_back(cb);
}
return ret;
}
void join_all(std::vector<std::thread>* threads) {
for (auto& t : *threads)
t.join();
}
} // namespace
TEST(SharedLock, CanBeUsedWithUniqueLock) {
shared_mutex mutex;
{
std::unique_lock<shared_mutex> l(mutex);
EXPECT_EQ(1, 1);
}
}
TEST(SharedLock, CanTryLock) {
shared_mutex mutex;
std::unique_lock<shared_mutex> l(mutex);
std::thread t([&]() { EXPECT_FALSE(mutex.try_lock()); });
t.join();
}
TEST(SharedLock, CanTryLockShared) {
shared_mutex mutex;
std::unique_lock<shared_mutex> l(mutex);
std::thread t([&]() {
// Since we hold the exclusive lock, this will fail.
EXPECT_FALSE(mutex.try_lock_shared());
});
t.join();
}
TEST(SharedLock, IsExclusiveLock) {
shared_mutex mutex;
std::atomic_flag flag = ATOMIC_FLAG_INIT;
std::thread a([&]() {
std::unique_lock<shared_mutex> l(mutex);
EXPECT_FALSE(flag.test_and_set());
usleep(1000);
flag.clear();
});
std::thread b([&]() {
usleep(100);
std::unique_lock<shared_mutex> l(mutex);
EXPECT_FALSE(flag.test_and_set());
usleep(1000);
flag.clear();
});
a.join();
b.join();
}
TEST(SharedLock, AllowsMultipleReaders) {
shared_mutex mutex;
std::atomic<int> readers{0};
std::atomic<int> max_readers{0};
constexpr const int kThreadCount = 5;
std::vector<std::thread> threads = make_n_threads(kThreadCount, [&]() {
shared_lock<shared_mutex> l(mutex);
const int count = ++readers;
// Atomically set the max value. Each step will try to update the value; if
// the value has changed since the read, |last_max| will be updated and the
// loop will step again.
int last_max = max_readers;
while (
!max_readers.compare_exchange_weak(last_max, std::max(last_max, count)))
;
WaitUntilOrTimeout([&]() { return max_readers >= kThreadCount; });
--readers;
});
join_all(&threads);
EXPECT_EQ(0, readers);
EXPECT_EQ(kThreadCount, max_readers);
}
TEST(SharedLock, ReaderBlocksWriters) {
shared_mutex mutex;
std::atomic<int> reader_count{0};
std::atomic<bool> waiting_for_write{false};
std::vector<std::thread> readers = make_n_threads(3, [&]() {
shared_lock<shared_mutex> l(mutex);
reader_count++;
EXPECT_TRUE(
WaitUntilOrTimeout([&]() -> bool { return waiting_for_write; }));
usleep(1000);
reader_count--;
});
std::thread writer([&]() {
ASSERT_TRUE(WaitUntilOrTimeout([&]() { return reader_count > 0; }));
ASSERT_FALSE(mutex.try_lock());
waiting_for_write = true;
std::unique_lock<shared_mutex> l(mutex);
EXPECT_EQ(0, reader_count);
usleep(1000);
});
join_all(&readers);
writer.join();
}
} // namespace util
} // namespace shaka
<file_sep>/shaka/tools/abi_test.py
#!/usr/bin/python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Runs tests to verify we don't break ABI between versions.
This runs a build for the current change and checks out a given commit and
compares the two to see if there are reverse-incompatible ABI changes. This
performs a git checkout to perform the test, but the previous state is restored
at the end of the test.
"""
from __future__ import print_function
import argparse
import logging
import os
import shutil
import subprocess
import sys
import tempfile
TOOLS_DIR = os.path.dirname(os.path.realpath(__file__))
ROOT_DIR = os.path.join(TOOLS_DIR, '..', '..')
def _GetCheckout():
"""Gets the current git branch, or the current commit if detached."""
branch = subprocess.check_output(['git', '-C', ROOT_DIR, 'rev-parse',
'--abbrev-ref', '--verify', 'HEAD']).strip()
if branch != 'HEAD':
return branch
return subprocess.check_output(
['git', '-C', ROOT_DIR, 'rev-parse', 'HEAD']).strip()
def _IsGitDirty():
"""Returns whether the working directory is dirty."""
return subprocess.call(['git', '-C', ROOT_DIR, 'diff', '--exit-code']) != 0
def _DoBuild(config_name, parsed_args):
"""Configures and builds the project."""
logging.info('Creating release build at %s...',
subprocess.check_output(
['git', '-C', ROOT_DIR, 'rev-parse', 'HEAD'])[:6])
args = ['--config-name', config_name, '--release', '--no-makefile']
if parsed_args.ccache:
args += ['--ccache-if-possible']
if subprocess.call([os.path.join(ROOT_DIR, 'configure')] + args) != 0:
return 1
return subprocess.call(
[os.path.join(ROOT_DIR, 'build.py'), '--config-name', config_name])
def _GetSymbols(config_name):
"""Returns a set of public symbols from the library."""
lib_path = os.path.join(
ROOT_DIR, 'out', config_name, 'libshaka-player-embedded.so')
log = subprocess.check_output(
['nm', '-Dg', '--defined-only', '--format=posix', lib_path])
symbols = set()
for line in log.strip().split('\n'):
symbol, type_, _, _ = line.split(' ')
# Ignore weak symbols as they are defined outside the library.
if type_ not in {'W', 'w', 'V', 'v', 'U'}:
symbols.add(symbol)
return symbols
def RunAbiTest(config_name, parsed_args):
"""Runs the ABI tests."""
if _DoBuild(config_name, parsed_args) != 0:
return 1
symbols = _GetSymbols(config_name)
# Checkout the other reference and do another build.
logging.info('Checking out %s to compare against...', parsed_args.ref)
if subprocess.call(['git', '-C', ROOT_DIR, 'checkout', parsed_args.ref]) != 0:
return 1
if _DoBuild(config_name, parsed_args) != 0:
return 1
old_symbols = _GetSymbols(config_name)
if not old_symbols.issubset(symbols):
logging.error('Change breaks ABI compatibility.')
logging.error('The following symbols are missing:')
for s in old_symbols - symbols:
logging.error(' %s', s)
return 1
logging.info('ABI check passed')
return 0
def main(args):
parser = argparse.ArgumentParser(
description=__doc__, usage='%(prog)s [options]',
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--ref', default='HEAD^',
help='Compare HEAD against the given ref.')
parser.add_argument(
'--ccache-if-possible', dest='ccache', action='store_true',
help='Use ccache to speed up builds if found on PATH.')
parser.add_argument(
'--ios', action='store_true',
help='Runs the ABI test for the iOS framework (only works on Mac).')
parsed_args = parser.parse_args(args)
if parsed_args.ios:
parser.error('--ios is currently unsupported')
if _IsGitDirty():
logging.error(
'Git repo is dirty; can only run tests on clean working directory')
return 1
prev_ref = _GetCheckout()
temp_dir = tempfile.mkdtemp(dir=os.path.join(ROOT_DIR, 'out'))
try:
return RunAbiTest(os.path.basename(temp_dir), parsed_args)
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
logging.info('Restoring previous git checkout')
subprocess.check_call(['git', '-C', ROOT_DIR, 'checkout', '-f', prev_ref])
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
sys.exit(main(sys.argv[1:]))
<file_sep>/shaka/test/src/media/media_utils_unittest.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/media_utils.h"
#include <gtest/gtest.h>
namespace shaka {
namespace media {
namespace {
void BadMimeTest(const std::string& source) {
std::string type;
std::string subtype;
std::unordered_map<std::string, std::string> params;
EXPECT_FALSE(ParseMimeType(source, &type, &subtype, ¶ms));
}
void GoodMimeTest(const std::string& source) {
std::string type;
std::string subtype;
std::unordered_map<std::string, std::string> params;
EXPECT_TRUE(ParseMimeType(source, &type, &subtype, ¶ms));
}
} // namespace
TEST(MediaUtilsTest, ParseMimeType) {
std::string type;
std::string subtype;
std::unordered_map<std::string, std::string> params;
ASSERT_TRUE(ParseMimeType("video/mp4", &type, &subtype, ¶ms));
EXPECT_EQ("video", type);
EXPECT_EQ("mp4", subtype);
EXPECT_EQ(0u, params.size());
ASSERT_TRUE(ParseMimeType("audio/mp2t; codecs = \"foo bar\"", &type, &subtype,
¶ms));
EXPECT_EQ("audio", type);
EXPECT_EQ("mp2t", subtype);
ASSERT_EQ(1u, params.size());
EXPECT_EQ("foo bar", params["codecs"]);
ASSERT_TRUE(ParseMimeType("text/vtt; encoding=UTF-8; codecs=stpp", &type,
&subtype, ¶ms));
EXPECT_EQ("text", type);
EXPECT_EQ("vtt", subtype);
ASSERT_EQ(2u, params.size());
EXPECT_EQ("UTF-8", params["encoding"]);
EXPECT_EQ("stpp", params["codecs"]);
GoodMimeTest("audio/video ");
GoodMimeTest(" audio/video");
GoodMimeTest("audio/video; codecs=");
GoodMimeTest("audio/video; codecs=\"\"");
GoodMimeTest("audio/video; codecs=\"foo/bar=r\"");
GoodMimeTest("audio/video; codecs=\"\" ; k=v");
BadMimeTest(""); // Empty.
BadMimeTest("video"); // No subtype.
BadMimeTest("/mp4"); // Empty type.
BadMimeTest("video?/mp4"); // Type has special chars.
BadMimeTest("vi deo/mp4"); // Type has special chars.
BadMimeTest("video/"); // Empty subtype.
BadMimeTest("video/audio?"); // Subtype has special chars.
BadMimeTest("video/au dio"); // Subtype has special chars.
BadMimeTest("video/audio/other"); // Subtype has special chars.
BadMimeTest("video/audio;"); // No parameter name
BadMimeTest("video/audio; "); // No parameter name
BadMimeTest("video/audio;key"); // No equals sign.
BadMimeTest("video/audio;key=value;"); // No parameter name
BadMimeTest("video/audio;k/y=value"); // Key has special chars.
BadMimeTest("video/audio;k y=value"); // Key has special chars.
BadMimeTest("video/audio;key=va/lue"); // Value has special chars.
BadMimeTest("video/audio;key=va=lue"); // Value has special chars.
BadMimeTest("video/audio;key=\""); // No end of quoted string.
BadMimeTest("video/audio;key=\"\" foo"); // Chars after end of quoted string.
BadMimeTest("video/audio;key=\"\"foo; k=v");
}
TEST(MediaUtilsTest, IntersectionOfBufferedRanges) {
EXPECT_EQ(BufferedRanges(),
IntersectionOfBufferedRanges(std::vector<BufferedRanges>()));
{
const BufferedRanges empty_range;
EXPECT_EQ(empty_range,
IntersectionOfBufferedRanges(std::vector<BufferedRanges>()));
EXPECT_EQ(empty_range, IntersectionOfBufferedRanges({empty_range}));
EXPECT_EQ(empty_range,
IntersectionOfBufferedRanges({empty_range, empty_range}));
}
{
const BufferedRanges range = {{1, 4}, {7, 10}};
EXPECT_EQ(range, IntersectionOfBufferedRanges({range}));
}
{
const BufferedRanges range = {{1, 4}, {7, 10}};
EXPECT_EQ(range, IntersectionOfBufferedRanges({range, range}));
}
{
const BufferedRanges range1 = {{1, 4}, {7, 10}};
const BufferedRanges range2 = {{1, 4}};
EXPECT_EQ(range2, IntersectionOfBufferedRanges({range1, range2}));
}
{
const BufferedRanges range1 = {{7, 10}};
const BufferedRanges range2 = {{1, 4}, {7, 10}};
EXPECT_EQ(range1, IntersectionOfBufferedRanges({range1, range2}));
}
{
const BufferedRanges range1 = {{1, 4}, {7, 10}};
const BufferedRanges range2 = {{2, 3}};
EXPECT_EQ(range2, IntersectionOfBufferedRanges({range1, range2}));
}
{
const BufferedRanges range1 = {{1, 4}};
const BufferedRanges range2 = {{6, 10}};
EXPECT_EQ(BufferedRanges(), IntersectionOfBufferedRanges({range1, range2}));
}
{
const BufferedRanges range1 = {{1, 4}, {7, 10}};
const BufferedRanges range2 = {{3, 6}};
const BufferedRanges expected = {{3, 4}};
EXPECT_EQ(expected, IntersectionOfBufferedRanges({range1, range2}));
}
{
const BufferedRanges range1 = {{1, 4}, {7, 10}};
const BufferedRanges range2 = {{2, 8}};
const BufferedRanges expected = {{2, 4}, {7, 8}};
EXPECT_EQ(expected, IntersectionOfBufferedRanges({range1, range2}));
EXPECT_EQ(expected, IntersectionOfBufferedRanges({range2, range1}));
}
{
const BufferedRanges range1 = {{2, 8}};
const BufferedRanges range2 = {{0, 6}, {7, 9}};
const BufferedRanges range3 = {{3, 4}, {5, 6}, {7, 9}};
const BufferedRanges expected = {{3, 4}, {5, 6}, {7, 8}};
EXPECT_EQ(expected, IntersectionOfBufferedRanges({range1, range2, range3}));
EXPECT_EQ(expected, IntersectionOfBufferedRanges({range2, range1, range3}));
EXPECT_EQ(expected, IntersectionOfBufferedRanges({range3, range1, range3}));
}
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/js/events/media_key_message_event.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_EVENTS_MEDIA_KEY_MESSAGE_EVENT_H_
#define SHAKA_EMBEDDED_JS_EVENTS_MEDIA_KEY_MESSAGE_EVENT_H_
#include <memory>
#include <string>
#include <utility>
#include "shaka/optional.h"
#include "src/js/eme/media_key_system_configuration.h"
#include "src/js/events/event.h"
#include "src/mapping/backing_object_factory.h"
#include "src/mapping/byte_buffer.h"
#include "src/mapping/struct.h"
namespace shaka {
namespace js {
namespace events {
struct MediaKeyMessageEventInit : Struct {
static std::string name() {
return "MediaKeyMessageEventInit";
}
ADD_DICT_FIELD(eme::MediaKeyMessageType, messageType);
ADD_DICT_FIELD(ByteBuffer, message);
};
/**
* See: https://w3c.github.io/encrypted-media/#dom-mediakeymessageevent
*/
class MediaKeyMessageEvent final : public Event {
DECLARE_TYPE_INFO(MediaKeyMessageEvent);
public:
MediaKeyMessageEvent(EventType event_type,
eme::MediaKeyMessageType message_type,
ByteBuffer message);
static MediaKeyMessageEvent* Create(
const std::string& event_type,
optional<MediaKeyMessageEventInit> init_data) {
if (init_data.has_value()) {
return new MediaKeyMessageEvent(event_type, init_data->messageType,
std::move(init_data->message));
} else {
return new MediaKeyMessageEvent(
event_type, eme::MediaKeyMessageType::LicenseRequest, ByteBuffer());
}
}
void Trace(memory::HeapTracer* tracer) const override;
const eme::MediaKeyMessageType message_type;
const ByteBuffer message;
private:
MediaKeyMessageEvent(const std::string& event_type,
eme::MediaKeyMessageType message_type,
ByteBuffer message);
};
class MediaKeyMessageEventFactory final
: public BackingObjectFactory<MediaKeyMessageEvent, Event> {
public:
MediaKeyMessageEventFactory();
};
} // namespace events
} // namespace js
} // namespace shaka
#endif // SHAKA_EMBEDDED_JS_EVENTS_MEDIA_KEY_MESSAGE_EVENT_H_
<file_sep>/shaka/src/media/frame_buffer.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/frame_buffer.h"
#include <glog/logging.h>
#include <algorithm>
#include <cmath>
#include <iterator>
#include <unordered_set>
#include <utility>
namespace shaka {
namespace media {
namespace {
// These exist to reduce the number of if checks for ordering. This is done
// by using a single if at the beginning of the method and using a function
// pointer to one of these methods.
template <bool OrderByDts = true>
double GetTime(const std::unique_ptr<const BaseFrame>& a) {
return a->dts;
}
template <>
double GetTime<false>(const std::unique_ptr<const BaseFrame>& a) {
return a->pts;
}
#ifndef NDEBUG
template <bool OrderByDts>
bool FrameLessThan(const std::unique_ptr<const BaseFrame>& a,
const std::unique_ptr<const BaseFrame>& b) {
return GetTime<OrderByDts>(a) < GetTime<OrderByDts>(b);
}
#endif
template <bool OrderByDts>
bool FrameExtendsPast(const std::unique_ptr<const BaseFrame>& a,
const std::unique_ptr<const BaseFrame>& b) {
return GetTime<OrderByDts>(a) + a->duration + FrameBuffer::kMaxGapSize >=
GetTime<OrderByDts>(b);
}
template <typename Iter>
void UpdatePtsRanges(Iter range) {
DCHECK(!range->frames.empty());
range->start_pts = HUGE_VAL;
range->end_pts = -HUGE_VAL;
for (auto& frame : range->frames) {
range->start_pts = std::min(range->start_pts, frame->pts);
range->end_pts = std::max(range->end_pts, frame->pts + frame->duration);
}
}
/**
* Returns an iterator to the first element in |list| that is greater than or
* equal to |frame|.
*
* This performs a linear search through |list| to find the element. This will
* perform a forward or reverse search depending on which would (likely) be
* better.
*
* If we are inserting a frame at the end, this is O(1) time (usual case),
* otherwise this is O(n).
*
* This returns a non-const iterator because a standard library bug in
* libstdc++ 4.8 makes std::list::insert require non-const iterators.
* See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57158
*/
template <bool OrderByDts>
std::list<std::unique_ptr<const BaseFrame>>::iterator FrameLowerBound(
const std::list<std::unique_ptr<const BaseFrame>>& list, double time) {
auto& mutable_list =
const_cast<std::list<std::unique_ptr<const BaseFrame>>&>(list); // NOLINT
if (list.empty())
return mutable_list.end();
if (time - GetTime<OrderByDts>(list.front()) <
GetTime<OrderByDts>(list.back()) - time) {
// Closer to the front, find the first element that is not less than |time|.
auto notLessThan = [&time](const std::unique_ptr<const BaseFrame>& other) {
return GetTime<OrderByDts>(other) >= time;
};
return std::find_if(mutable_list.begin(), mutable_list.end(), notLessThan);
}
// Closer to the end, first use a reverse search to find the first (in
// reverse order) that is less than |time|.
auto isLessThan = [&time](const std::unique_ptr<const BaseFrame>& other) {
return GetTime<OrderByDts>(other) < time;
};
auto rit =
std::find_if(mutable_list.rbegin(), mutable_list.rend(), isLessThan);
// |*rit| is equal to the first element (going backwards) that is less than
// |frame|. We want to return |rit - 1| as a forward iterator, namely the
// first element that is not less than |frame|. The |base()| of a reverse
// iterator is the same element as |*(rit - 1)|, so return that.
// See: http://en.cppreference.com/w/cpp/iterator/reverse_iterator/base
return rit.base();
}
} // namespace
FrameBuffer::FrameBuffer(bool order_by_dts)
: mutex_("FrameBuffer"), order_by_dts_(order_by_dts) {}
FrameBuffer::~FrameBuffer() {}
size_t FrameBuffer::EstimateSize() const {
std::unique_lock<Mutex> lock(mutex_);
size_t size = 0;
for (auto& range : buffered_ranges_) {
for (auto& frame : range.frames)
size += frame->EstimateSize();
}
return size;
}
void FrameBuffer::AppendFrame(std::unique_ptr<const BaseFrame> frame) {
std::unique_lock<Mutex> lock(mutex_);
DCHECK(frame);
auto extendsPast =
order_by_dts_ ? &FrameExtendsPast<true> : &FrameExtendsPast<false>;
auto lowerBound =
order_by_dts_ ? &FrameLowerBound<true> : &FrameLowerBound<false>;
auto getTime = order_by_dts_ ? &GetTime<true> : &GetTime<false>;
// Find the first buffered range that ends after |frame|.
auto range_it = std::find_if(buffered_ranges_.begin(), buffered_ranges_.end(),
[&](const Range& range) {
return extendsPast(range.frames.back(), frame);
});
if (range_it == buffered_ranges_.end()) {
// |frame| was after every existing range, create a new one.
buffered_ranges_.emplace_back();
buffered_ranges_.back().start_pts = frame->pts;
buffered_ranges_.back().end_pts = frame->pts + frame->duration;
buffered_ranges_.back().frames.emplace_back(std::move(frame));
} else if (!extendsPast(frame, range_it->frames.front())) {
// |frame| is before this range, so it starts a new range before this one.
auto it = buffered_ranges_.emplace(range_it);
it->start_pts = frame->pts;
it->end_pts = frame->pts + frame->duration;
it->frames.emplace_back(std::move(frame));
} else {
// |frame| is inside the current range.
auto frame_it = lowerBound(range_it->frames, getTime(frame));
range_it->start_pts = std::min(range_it->start_pts, frame->pts);
range_it->end_pts =
std::max(range_it->end_pts, frame->pts + frame->duration);
if (frame_it != range_it->frames.end() &&
getTime(*frame_it) == getTime(frame)) {
used_frames_.WaitToDeleteFrames({frame_it->get()});
swap(*frame_it, frame);
} else {
range_it->frames.insert(frame_it, std::move(frame));
}
}
// If the frame closed a gap, then merge the buffered ranges.
DCHECK_NE(0u, buffered_ranges_.size());
for (auto it = std::next(buffered_ranges_.begin());
it != buffered_ranges_.end();) {
auto prev = std::prev(it);
if (extendsPast(prev->frames.back(), it->frames.front())) {
// Move all elements from |it->frames| to the end of |prev->frames|.
// Since both lists are sorted and |prev < it|, this will remain sorted.
prev->frames.splice(prev->frames.end(), it->frames);
prev->start_pts = std::min(prev->start_pts, it->start_pts);
prev->end_pts = std::max(prev->end_pts, it->end_pts);
it = buffered_ranges_.erase(it);
} else {
it++;
}
}
AssertRangesSorted();
}
BufferedRanges FrameBuffer::GetBufferedRanges() const {
std::unique_lock<Mutex> lock(mutex_);
AssertRangesSorted();
BufferedRanges ret;
ret.reserve(buffered_ranges_.size());
for (const Range& range : buffered_ranges_) {
ret.emplace_back(range.start_pts, range.end_pts);
}
return ret;
}
int FrameBuffer::FramesBetween(double start_time, double end_time) const {
std::unique_lock<Mutex> lock(mutex_);
AssertRangesSorted();
auto getTime = order_by_dts_ ? &GetTime<true> : &GetTime<false>;
auto lowerBound =
order_by_dts_ ? &FrameLowerBound<true> : &FrameLowerBound<false>;
// Find the first buffered range that includes or is after |start_time|.
auto range_it =
std::find_if(buffered_ranges_.begin(), buffered_ranges_.end(),
[&](const Range& range) {
return getTime(range.frames.back()) >= start_time;
});
int num_frames = 0;
for (; range_it != buffered_ranges_.end(); range_it++) {
// |start| points to the frame that starts at or greater than
// |start_time|.
auto start = lowerBound(range_it->frames, start_time);
auto end = lowerBound(range_it->frames, end_time);
DCHECK(start != range_it->frames.end());
num_frames += std::distance(start, end);
if (getTime(*start) == start_time && start != end)
num_frames--;
if (end != range_it->frames.end())
break;
}
return num_frames;
}
LockedFrameList::Guard FrameBuffer::GetFrameNear(double time) const {
std::unique_lock<Mutex> lock(mutex_);
return used_frames_.GuardFrame(GetFrameNear(time, /* allow_before */ true));
}
LockedFrameList::Guard FrameBuffer::GetFrameAfter(double time) const {
std::unique_lock<Mutex> lock(mutex_);
return used_frames_.GuardFrame(GetFrameNear(time, /* allow_before */ false));
}
LockedFrameList::Guard FrameBuffer::GetKeyFrameBefore(double time) const {
std::unique_lock<Mutex> lock(mutex_);
AssertRangesSorted();
auto getTime = order_by_dts_ ? &GetTime<true> : &GetTime<false>;
auto lowerBound =
order_by_dts_ ? &FrameLowerBound<true> : &FrameLowerBound<false>;
// Find the first buffered range that includes or is after |time|.
auto range_it = std::find_if(
buffered_ranges_.begin(), buffered_ranges_.end(),
[&](const Range& range) { return getTime(range.frames.back()) >= time; });
if (range_it != buffered_ranges_.end()) {
// |it| points to the frame that starts at or greater than |time|.
auto it = lowerBound(range_it->frames, time);
DCHECK(it != range_it->frames.end());
if (getTime(*it) > time) {
if (it == range_it->frames.begin())
return LockedFrameList::Guard();
it--;
}
for (; it != range_it->frames.begin(); it--) {
if ((*it)->is_key_frame)
return used_frames_.GuardFrame(it->get());
}
CHECK((*it)->is_key_frame);
return used_frames_.GuardFrame(it->get());
}
return LockedFrameList::Guard();
}
void FrameBuffer::Remove(double start, double end) {
// Note that remove always uses PTS, even when sorting using DTS. This is
// intended to work like the MSE definition.
std::unique_lock<Mutex> lock(mutex_);
bool is_removing = false;
for (auto it = buffered_ranges_.begin(); it != buffered_ranges_.end();) {
// These represent the range of frames within this buffer to delete.
auto frame_del_start = is_removing ? it->frames.begin() : it->frames.end();
auto frame_del_end = it->frames.end();
std::unordered_set<const BaseFrame*> frames_to_remove;
for (auto frame = it->frames.begin(); frame != it->frames.end(); frame++) {
if (!is_removing) {
// Only start deleting frames whose start time is in the range.
if ((*frame)->pts >= start && (*frame)->pts < end) {
is_removing = true;
frame_del_start = frame;
frames_to_remove.insert(frame->get());
}
} else if ((*frame)->pts >= end && (*frame)->is_key_frame) {
// The MSE spec says to remove up to the next key frame.
frame_del_end = frame;
is_removing = false;
break;
} else {
frames_to_remove.insert(frame->get());
}
}
// We don't release |mutex_| while waiting. Any threads using frames should
// not make calls into this FrameBuffer (though they can to other buffers).
used_frames_.WaitToDeleteFrames(frames_to_remove);
if (frame_del_start != it->frames.begin() &&
frame_del_start != it->frames.end() &&
frame_del_end != it->frames.end()) {
// We deleted a partial range, so we need to split the buffered range.
auto new_it = buffered_ranges_.emplace(it); // new_it + 1 == it
// Move the elements before |frame_del_start| from |it->frames| to
// |new_it->frames|.
new_it->frames.splice(new_it->frames.end(), it->frames,
it->frames.begin(), frame_del_start);
it->frames.erase(it->frames.begin(), frame_del_end);
UpdatePtsRanges(it);
UpdatePtsRanges(new_it);
it++; // list::emplace() doesn't invalidate any iterators.
} else {
it->frames.erase(frame_del_start, frame_del_end);
if (it->frames.empty()) {
it = buffered_ranges_.erase(it);
} else {
UpdatePtsRanges(it);
it++;
}
}
}
AssertRangesSorted();
}
const BaseFrame* FrameBuffer::GetFrameNear(double time,
bool allow_before) const {
AssertRangesSorted();
auto getTime = order_by_dts_ ? &GetTime<true> : &GetTime<false>;
auto lowerBound =
order_by_dts_ ? &FrameLowerBound<true> : &FrameLowerBound<false>;
// Find the first buffered range that includes or is after |time|.
auto it = std::find_if(
buffered_ranges_.begin(), buffered_ranges_.end(),
[&](const Range& range) { return getTime(range.frames.back()) >= time; });
if (it != buffered_ranges_.end()) {
// |frame_it| points to the frame that starts at or greater than |time|.
auto frame_it = lowerBound(it->frames, time);
DCHECK(frame_it != it->frames.end());
// Find the frame after |time|.
auto next_it = it->frames.end();
bool has_next = true;
if (getTime(*frame_it) > time)
next_it = frame_it;
else if (std::next(frame_it) != it->frames.end())
next_it = std::next(frame_it);
else if (std::next(it) != buffered_ranges_.end())
next_it = std::next(it)->frames.begin();
else
has_next = false;
// Find the frame before |time|. This is only for GetFrameNear, so allow
// returning frame that equals |time|.
if (allow_before) {
auto prev_it = it->frames.end();
bool has_prev = true;
if (getTime(*frame_it) <= time)
prev_it = frame_it;
else if (frame_it != it->frames.begin())
prev_it = std::prev(frame_it);
else if (it != buffered_ranges_.begin())
prev_it = std::prev(std::prev(it)->frames.end());
else
has_prev = false;
if (has_prev) {
const double prev_dt = time - getTime(*prev_it) - (*prev_it)->duration;
if (!has_next || getTime(*next_it) - time > prev_dt)
return prev_it->get();
}
}
return has_next ? next_it->get() : nullptr;
}
if (allow_before && !buffered_ranges_.empty())
return buffered_ranges_.back().frames.back().get();
return nullptr;
}
void FrameBuffer::AssertRangesSorted() const {
#ifndef NDEBUG
auto frame_less_than =
order_by_dts_ ? &FrameLessThan<true> : &FrameLessThan<false>;
auto range_is_valid = [&](const FrameBuffer::Range& range) {
// A buffered range must:
// - Be non-empty.
// - Start with a key frame.
// - Have sorted frames.
CHECK(!range.frames.empty());
CHECK(range.frames.front()->is_key_frame);
CHECK_LE(range.start_pts, range.end_pts);
CHECK(std::is_sorted(range.frames.begin(), range.frames.end(),
frame_less_than));
return true;
};
auto range_less_than = [&](const FrameBuffer::Range& first,
const FrameBuffer::Range& second) {
// Some versions of the standard library will perform debug checks that will
// call this with the same argument. Don't assert in this case.
if (&first == &second)
return false;
// The ranges must not overlap.
if (first.start_pts < second.start_pts) {
CHECK_LT(first.end_pts, second.start_pts);
return true;
}
CHECK_GT(first.start_pts, second.end_pts);
return false;
};
CHECK(std::all_of(buffered_ranges_.begin(), buffered_ranges_.end(),
range_is_valid));
CHECK(std::is_sorted(buffered_ranges_.begin(), buffered_ranges_.end(),
range_less_than));
#endif
}
FrameBuffer::Range::Range() : start_pts(HUGE_VAL), end_pts(-HUGE_VAL) {}
FrameBuffer::Range::~Range() {}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/core/js_manager_impl.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/core/js_manager_impl.h"
#include "src/mapping/convert_js.h"
#include "src/mapping/js_engine.h"
#include "src/util/file_system.h"
namespace shaka {
using std::placeholders::_1;
JsManagerImpl::JsManagerImpl(const JsManager::StartupOptions& options)
: startup_options_(options),
event_loop_(std::bind(&JsManagerImpl::EventThreadWrapper, this, _1),
/* is_worker */ false) {}
JsManagerImpl::~JsManagerImpl() {
Stop();
}
void JsManagerImpl::Trace(memory::HeapTracer* tracer) const {
tracer->Trace(&event_loop_);
}
std::string JsManagerImpl::GetPathForStaticFile(const std::string& file) const {
return util::FileSystem::GetPathForStaticFile(
startup_options_.static_data_dir,
startup_options_.is_static_relative_to_bundle, file);
}
std::string JsManagerImpl::GetPathForDynamicFile(
const std::string& file) const {
return util::FileSystem::GetPathForDynamicFile(
startup_options_.dynamic_data_dir, file);
}
void JsManagerImpl::WaitUntilFinished() {
if (event_loop_.is_running() && event_loop_.HasPendingWork()) {
event_loop_.WaitUntilFinished();
}
}
std::shared_ptr<ThreadEvent<bool>> JsManagerImpl::RunScript(
const std::string& path) {
// Script must be executed on the event thread.
CHECK(event_loop_.is_running());
auto callback = std::bind(
static_cast<bool (*)(const std::string&)>(&shaka::RunScript), path);
return event_loop_.AddInternalTask(TaskPriority::Immediate, "RunScript",
PlainCallbackTask(callback));
}
std::shared_ptr<ThreadEvent<bool>> JsManagerImpl::RunScript(
const std::string& path, const uint8_t* data, size_t data_size) {
// Script must be executed on the event thread.
CHECK(event_loop_.is_running());
auto* run_script =
static_cast<bool (*)(const std::string&, const uint8_t*, size_t)>(
&shaka::RunScript);
auto callback = std::bind(run_script, path, data, data_size);
return event_loop_.AddInternalTask(TaskPriority::Immediate, "RunScript",
PlainCallbackTask(callback));
}
void JsManagerImpl::EventThreadWrapper(TaskRunner::RunLoop run_loop) {
JsEngine engine;
{
JsEngine::SetupContext setup;
#ifdef USING_V8
engine.isolate()->SetEmbedderHeapTracer(&v8_heap_tracer_);
#endif
Environment env;
env.Install();
run_loop();
network_thread_.Stop();
tracker_.Dispose();
}
}
} // namespace shaka
<file_sep>/shaka/src/mapping/any.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/mapping/any.h"
#include <cmath>
#include "src/memory/heap_tracer.h"
namespace shaka {
Any::Any() : value_(JsUndefined()), is_number_(false) {}
Any::Any(std::nullptr_t) : value_(JsNull()), is_number_(false) {}
Any::~Any() {}
Any::Any(const Any&) = default;
Any::Any(Any&&) = default;
Any& Any::operator=(const Any&) = default;
Any& Any::operator=(Any&&) = default;
bool Any::IsTruthy() const {
switch (GetValueType(value_.handle())) {
case JSValueType::Undefined:
case JSValueType::Null:
return false;
case JSValueType::String:
return !ConvertToString(value_.handle()).empty();
case JSValueType::Boolean:
return BooleanFromValue(value_.handle());
case JSValueType::Number: {
const double val = NumberFromValue(value_.handle());
return !std::isnan(val) && val != 0;
}
default:
return true;
}
}
bool Any::TryConvert(Handle<JsValue> value) {
value_ = value;
is_number_ = GetValueType(value_.handle()) == JSValueType::Number;
return true;
}
ReturnVal<JsValue> Any::ToJsValue() const {
return value_.value();
}
void Any::Trace(memory::HeapTracer* tracer) const {
// V8 doesn't seem to support tracing numbers. Other primitives are okay to
// trace, so only ignore if this is a number.
if (!is_number_)
tracer->Trace(&value_);
}
} // namespace shaka
<file_sep>/shaka/test/tests/_test_fixture.js
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
/**
* @private {string}
* Defines the "path" for the current test group.
*/
var curTestName = '';
/**
* This is defined by the environment to mark an expectation failure for the
* current test. This does not stop the test.
*
* @param {string} message The error message to print.
* @param {string} file The file name where the error occurred.
* @param {number} line The line number where the error occurred.
*/
// function fail_(message, file, line) {}
/**
* This is defined by the environment to define the test. This should be given
* the "full" test name, so the test() function will handle group names.
*
* @param {string} name The name of the test.
* @param {function()} callback The function that defines the test.
*/
// function test_(name, callback) {}
/**
* Returns an object containing the call stack info for the caller of the caller
* of this function.
* @return {{file: string, line: number}}
*/
function getCodeLocation_() {
try {
throw new Error('XXX');
} catch (e) {
let stack = ((e || {}).stack || '').split('\n');
if (stack[0].endsWith('XXX'))
stack.shift();
// V8 format with function name.
const line = stack[2] || '';
let m = /at [^(]+\(([^:]+):(\d+):\d+\)$/.exec(line);
if (!m) {
// V8 format without function name.
m = /at ([^(:]+):(\d+):\d+$/.exec(line);
}
if (m) {
return {file: m[1], line: Number(m[2])};
} else {
console.log(line);
return {file: 'unknown', line: 0};
}
}
}
/**
* Expects that the given value is "truthy".
* @param {*} val The value to check.
*/
function expectTrue(val) {
if (!val) {
const stack = getCodeLocation_();
fail_('Expected: ' + val + '\n To be: truthy', stack.file, stack.line);
}
}
/**
* Expects that the given value is "falsy".
* @param {*} val The value to check.
*/
function expectFalse(val) {
if (val) {
const stack = getCodeLocation_();
fail_('Expected: ' + val + '\n To be: falsy', stack.file, stack.line);
}
}
/**
* Expects that the given value is equal to the given expected value. This does
* value comparisons and compares objects recursively.
*
* @param {*} actual The actual value to test.
* @param {*} expected The expected value we want.
*/
function expectEq(actual, expected) {
if (jasmine.matchersUtil.equals(actual, expected)) {
return;
}
const stack = getCodeLocation_();
fail_(' Expected: ' + actual + '\n' +
'To be equal to: ' + expected, stack.file, stack.line);
}
/**
* Expects that the given value is exactly equal to the given expected value
* using the JavaScript ===.
*
* @param {*} actual The actual value to test.
* @param {*} expected The expected value we want.
*/
function expectSame(actual, expected) {
if (actual === expected) {
return;
}
const stack = getCodeLocation_();
fail_(' Expected: ' + actual + '\n' +
'To be the same as: ' + expected, stack.file, stack.line);
}
/**
* Expects that the given value is not exactly equal to the given expected value
* using the JavaScript ===.
*
* @param {*} actual The actual value to test.
* @param {*} expected The expected value we want.
*/
function expectNotSame(actual, expected) {
if (actual !== expected) {
return;
}
const stack = getCodeLocation_();
fail_(' Expected: ' + actual + '\n' +
'To not be the same as: ' + expected, stack.file, stack.line);
}
/**
* Expects that the given value is an instance of the given type. If the
* expected type is a primitive type (e.g. Number), then the primitive type will
* also be accepted.
*
* @param {*} actual The actual value to test.
* @param {*} expectedType The type that the value should be.
*/
function expectInstanceOf(actual, expectedType) {
const type = typeof actual;
if ((expectedType == Number && type === 'number') ||
(expectedType == String && type === 'string') ||
(expectedType == Boolean && type === 'boolean')) {
return;
}
if (!(actual instanceof expectedType)) {
const stack = getCodeLocation_();
fail_(' Expected: ' + actual + '\n' +
'To be an instance of: ' + expectedType.name, stack.file, stack.line);
}
}
/**
* Expects that the given value is not an instance of the given type. If the
* expected type is a primitive type (e.g. Number), then the primitive type will
* also be accepted.
*
* @param {*} actual The actual value to test.
* @param {*} expectedType The type that the value should be.
*/
function expectNotInstanceOf(actual, expectedType) {
const type = typeof actual;
if ((expectedType == Number && type !== 'number') ||
(expectedType == String && type !== 'string') ||
(expectedType == Boolean && type !== 'boolean')) {
return;
}
if (actual instanceof expectedType) {
const stack = getCodeLocation_();
fail_(' Expected: ' + actual + '\n' +
'To not be an instance of: ' + expectedType.name, stack.file,
stack.line);
}
}
/**
* Expects that the given spy has been called at least one time.
*
* @param {*} spy The spy to check.
*/
function expectToHaveBeenCalled(spy) {
if (spy.calls.any()) {
return;
}
const stack = getCodeLocation_();
fail_('Expected: ' + spy.and.identity() + '\n' +
' To: Have been called', stack.file, stack.line);
}
/**
* Expects that the given spy has not been called at all.
*
* @param {*} spy The spy to check.
*/
function expectNotToHaveBeenCalled(spy) {
if (!spy.calls.any()) {
return;
}
const stack = getCodeLocation_();
fail_('Expected: ' + spy.and.identity() + '\n' +
' To: Not have been called', stack.file, stack.line);
}
/**
* Expects that the given spy has been called the given number of times.
*
* @param {*} spy The spy to check.
* @param {number} times The number of times it should have been called.
*/
function expectToHaveBeenCalledTimes(spy, times) {
if (spy.calls.count() == times) {
return;
}
const stack = getCodeLocation_();
fail_(' Expected: ' + spy.and.identity() + '\n' +
'To have been called times: ' + times, stack.file, stack.line);
}
/**
* Expects that the given spy has been called at least once with the given
* arguments.
*
* @param {*} spy The spy to check.
* @param {...*} args The arguments to check for.
*/
function expectToHaveBeenCalledWith(spy) {
let args = Array.prototype.slice.call(arguments, 1);
if (jasmine.matchersUtil.contains(spy.calls.allArgs(), args)) {
return;
}
const stack = getCodeLocation_();
fail_(' Expected: ' + spy.and.identity() + '\n' +
'To have been called with: [' + args.join(', ') + ']', stack.file,
stack.line);
}
/**
* Expects that the given function to throw an exception.
*
* @param {function()} callback The function that should throw.
*/
function expectToThrow(callback) {
try {
callback();
const stack = getCodeLocation_();
fail_('Expected function to throw', stack.file, stack.line);
} catch (e) {}
}
/**
* Fails the current test with the given message.
*
* @param {string} message The failure message.
*/
function fail(message) {
const stack = getCodeLocation_();
fail_('Failure: ' + message, stack.file, stack.line);
}
/**
* Creates a group of tests. The callback should define the tests that will
* be inside this group. You can call testGroup again in the callback to create
* groups of groups.
*
* @param {string} name The name of the group.
* @param {function()} callback The function that defines the group.
*/
function testGroup(name, callback) {
let old = curTestName;
if (curTestName) {
curTestName += '.' + name;
} else {
curTestName = name
}
callback();
curTestName = old;
}
/**
* Defines a new test. This function will be called when the test is run.
*
* @param {string} name The name of the test.
* @param {function()} callback The function that defines the test.
*/
function test(name, callback) {
if (curTestName) {
name = curTestName + '.' + name;
}
test_(name, callback);
}
/**
* Defines a disabled test.
*
* @param {string} name The name of the test.
* @param {function()} callback The function that defines the test.
*/
function xtest(name, callback) {}
<file_sep>/shaka/src/media/pipeline_monitor.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/pipeline_monitor.h"
#include <utility>
#include "src/media/frame_buffer.h"
namespace shaka {
namespace media {
namespace {
/** The number of seconds of content needed to be able to play forward. */
constexpr const double kNeedForPlay = 0.3;
/** The number of seconds difference to assume we are at the end. */
constexpr const double kEpsilon = 0.1;
bool IsBufferedUntil(const BufferedRanges& ranges, double start_time,
double end_time, double duration) {
for (auto& range : ranges) {
if (range.start <= start_time + FrameBuffer::kMaxGapSize &&
(range.end >= end_time || end_time + kEpsilon >= duration)) {
return true;
}
}
return false;
}
bool CanPlay(const BufferedRanges& ranges, double time, double duration) {
return IsBufferedUntil(ranges, time, time + kNeedForPlay, duration);
}
} // namespace
PipelineMonitor::PipelineMonitor(
std::function<BufferedRanges()> get_buffered,
std::function<BufferedRanges()> get_decoded,
std::function<void(MediaReadyState)> ready_state_changed,
const util::Clock* clock, PipelineManager* pipeline)
: get_buffered_(std::move(get_buffered)),
get_decoded_(std::move(get_decoded)),
ready_state_changed_(std::move(ready_state_changed)),
clock_(clock),
pipeline_(pipeline),
shutdown_(false),
ready_state_(HAVE_NOTHING),
thread_("PipelineMonitor",
std::bind(&PipelineMonitor::ThreadMain, this)) {}
PipelineMonitor::~PipelineMonitor() {
CHECK(!thread_.joinable()) << "Need to call Stop() before destroying";
}
void PipelineMonitor::Stop() {
shutdown_.store(true, std::memory_order_release);
thread_.join();
}
void PipelineMonitor::ThreadMain() {
while (!shutdown_.load(std::memory_order_acquire)) {
const BufferedRanges buffered = get_buffered_();
const BufferedRanges decoded = get_decoded_();
const double time = pipeline_->GetCurrentTime();
const double duration = pipeline_->GetDuration();
const bool can_play = CanPlay(buffered, time, duration);
if (time >= duration) {
pipeline_->OnEnded();
} else if (can_play && IsBufferedUntil(decoded, time, time, duration)) {
// Don't move playhead until we have decoded at the current time. This
// ensures we stop for decryption errors and that we don't blindly move
// forward without the correct frames.
pipeline_->CanPlay();
} else {
pipeline_->Stalled();
}
if (pipeline_->GetPipelineStatus() == PipelineStatus::Initializing) {
ChangeReadyState(HAVE_NOTHING);
} else if (can_play) {
ChangeReadyState(HAVE_FUTURE_DATA);
} else if (IsBufferedUntil(buffered, time, time, duration)) {
ChangeReadyState(HAVE_CURRENT_DATA);
} else {
ChangeReadyState(HAVE_METADATA);
}
clock_->SleepSeconds(0.01);
}
}
void PipelineMonitor::ChangeReadyState(MediaReadyState new_state) {
if (ready_state_ != new_state) {
ready_state_ = new_state;
ready_state_changed_(new_state);
}
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/js/vtt_cue.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/vtt_cue.h"
#include <cmath>
namespace shaka {
namespace js {
VTTCue::VTTCue(double start_time, double end_time, const std::string& text)
: shaka::VTTCue(start_time, end_time, text) {}
VTTCue::VTTCue(const shaka::VTTCue& pub) : shaka::VTTCue(pub) {}
VTTCue::~VTTCue() {}
variant<double, AutoKeyword> VTTCue::PositionJs() const {
const double ret = position();
if (std::isnan(ret))
return AutoKeyword::Auto;
return ret;
}
void VTTCue::SetPositionJs(variant<double, AutoKeyword> value) {
if (holds_alternative<double>(value))
SetPosition(get<double>(value));
else
SetPosition(NAN);
}
variant<double, AutoKeyword> VTTCue::LineJs() const {
const double ret = line();
if (std::isnan(ret))
return AutoKeyword::Auto;
return ret;
}
void VTTCue::SetLineJs(variant<double, AutoKeyword> value) {
if (holds_alternative<double>(value))
SetLine(get<double>(value));
else
SetLine(NAN);
}
VTTCueFactory::VTTCueFactory() {
// TextTrackCue
AddGenericProperty<VTTCue>("id", &VTTCue::id, &VTTCue::SetId);
AddGenericProperty<VTTCue>("startTime", &VTTCue::startTime,
&VTTCue::SetStartTime);
AddGenericProperty<VTTCue>("endTime", &VTTCue::endTime, &VTTCue::SetEndTime);
AddGenericProperty<VTTCue>("pauseOnExit", &VTTCue::pauseOnExit,
&VTTCue::SetPauseOnExit);
// VTTCue
AddGenericProperty<VTTCue>("vertical", &VTTCue::vertical,
&VTTCue::SetVertical);
AddGenericProperty<VTTCue>("snapToLines", &VTTCue::snapToLines,
&VTTCue::SetSnapToLines);
AddGenericProperty<VTTCue>("line", &VTTCue::LineJs, &VTTCue::SetLineJs);
AddGenericProperty<VTTCue>("lineAlign", &VTTCue::lineAlign,
&VTTCue::SetLineAlign);
AddGenericProperty<VTTCue>("position", &VTTCue::PositionJs,
&VTTCue::SetPositionJs);
AddGenericProperty<VTTCue>("positionAlign", &VTTCue::positionAlign,
&VTTCue::SetPositionAlign);
AddGenericProperty<VTTCue>("size", &VTTCue::size, &VTTCue::SetSize);
AddGenericProperty<VTTCue>("align", &VTTCue::align, &VTTCue::SetAlign);
AddGenericProperty<VTTCue>("text", &VTTCue::text, &VTTCue::SetText);
}
} // namespace js
} // namespace shaka
<file_sep>/shaka/src/js/console.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/console.h"
#include <algorithm> // std::min and std::sort
#include <cstdio>
#include <vector>
#include "src/js/js_error.h"
namespace shaka {
namespace js {
namespace {
// Limit the number of children we are willing to print. This will limit the
// number of elements printed from arrays and the number of members printed
// from objects.
constexpr const size_t kMaxChildren = 20;
std::string ConvertToPrettyString(Handle<JsValue> value, bool allow_long);
std::string to_string(Console::LogLevel level) {
switch (level) {
case Console::kError:
return "Error";
case Console::kWarn:
return "Warn";
case Console::kInfo:
return "Info";
case Console::kLog:
return "Log";
case Console::kDebug:
return "Debug";
}
}
std::string ConvertStringToPrettyString(const std::string& string) {
std::string buffer;
buffer.push_back('"');
for (const char c : string) {
// Using https://en.wikipedia.org/wiki/Escape_sequences_in_C to determine
// characters need to be escaped.
switch (c) {
// Alert
case '\a':
buffer += R"(\a)";
break;
// Backspace
case '\b':
buffer += R"(\b)";
break;
// Newline
case '\n':
buffer += R"(\n)";
break;
// Carriage Return
case '\r':
buffer += R"(\r)";
break;
// Horizontal Tab
case '\t':
buffer += R"(\t)";
break;
// Backslash
case '\\':
buffer += R"(\\)";
break;
// Single Quotation Mark
case '\'':
buffer += R"(\')";
break;
// Double Quotation Mark
case '"':
buffer += R"(\")";
break;
// Question Mark
case '\?':
buffer += R"(\?)";
break;
default:
buffer.push_back(c);
break;
}
}
buffer.push_back('"');
return buffer;
}
std::string ConvertArrayToLongPrettyString(Handle<JsValue> value) {
const LocalVar<JsObject> array = UnsafeJsCast<JsObject>(value);
const size_t array_length = ArrayLength(array);
const size_t min_length = std::min(kMaxChildren, array_length);
// TODO: Use a string buffer to build strings to avoid having to create
// strings just to concatenate them.
std::string array_as_string = "[";
for (size_t i = 0; i < min_length; i++) {
const LocalVar<JsValue> index_value = GetArrayIndexRaw(array, i);
array_as_string += i ? ", " : "";
array_as_string += ConvertToPrettyString(index_value, false);
}
// If there are more elements than we want to print, tell the user by
// appending a tail.
if (array_length > min_length) {
array_as_string += ", ...";
}
array_as_string += "]";
return array_as_string;
}
std::string ConvertObjectToLongPrettyString(Handle<JsObject> object) {
// Get the member names in sorted order so that it will be easier to
// see which member are different between to objects when viewing the
// output.
std::vector<std::string> member_names = GetMemberNames(object);
std::sort(member_names.begin(), member_names.end());
const size_t min_length = std::min(kMaxChildren, member_names.size());
std::string object_as_string = "{";
for (size_t i = 0; i < min_length; i++) {
const std::string& member_name = member_names[i];
const LocalVar<JsValue> member_value = GetMemberRaw(object, member_name);
object_as_string += i ? ", " : "";
object_as_string += member_name;
object_as_string += ":";
object_as_string += ConvertToPrettyString(member_value, false);
}
// If there are more members than we want to print, tell the user by
// appending a tail.
if (member_names.size() > min_length) {
object_as_string += ", ...";
}
object_as_string += "}";
return object_as_string;
}
std::string ConvertToPrettyString(Handle<JsValue> value, bool allow_long) {
const JSValueType type = GetValueType(value);
switch (type) {
case JSValueType::Undefined:
case JSValueType::Null:
case JSValueType::Boolean:
case JSValueType::Number:
return ConvertToString(value);
case JSValueType::Function:
return "function() {...}";
case JSValueType::String: {
const std::string string = ConvertToString(value);
return ConvertStringToPrettyString(string);
}
case JSValueType::Array:
return allow_long ? ConvertArrayToLongPrettyString(value) : "[...]";
case JSValueType::Symbol:
return "Symbol(" + ConvertToString(value) + ")";
case JSValueType::BooleanObject:
return "Boolean(" + ConvertToString(value) + ")";
case JSValueType::NumberObject:
return "Number(" + ConvertToString(value) + ")";
case JSValueType::StringObject:
return "String(" + ConvertStringToPrettyString(ConvertToString(value)) +
")";
default:
if (!IsObject(value))
return ConvertToString(value);
LocalVar<JsObject> object = UnsafeJsCast<JsObject>(value);
if (IsBuiltInObject(object))
return ConvertToString(value);
return allow_long ? ConvertObjectToLongPrettyString(object) : "{...}";
}
}
} // namespace
Console::Console() {}
// \cond Doxygen_Skip
Console::~Console() {}
// \endcond Doxygen_Skip
void Console::Assert(Any cond, const CallbackArguments& arguments) const {
if (!cond.IsTruthy()) {
LogReal(kError, arguments, "Assertion failed: ", 1);
std::printf("%s\n", JsError::GetJsStack().c_str());
}
}
void Console::Error(const CallbackArguments& arguments) const {
LogReal(kError, arguments);
}
void Console::Warn(const CallbackArguments& arguments) const {
LogReal(kWarn, arguments);
}
void Console::Info(const CallbackArguments& arguments) const {
LogReal(kInfo, arguments);
}
void Console::Log(const CallbackArguments& arguments) const {
LogReal(kLog, arguments);
}
void Console::Debug(const CallbackArguments& arguments) const {
LogReal(kDebug, arguments);
}
std::string Console::ConvertToPrettyString(Handle<JsValue> value) {
return shaka::js::ConvertToPrettyString(value, true);
}
void Console::LogReal(LogLevel level, const CallbackArguments& arguments,
const char* prefix, size_t skip_count) const {
// TODO: Consider using glog for logging.
std::printf("[%s]: ", to_string(level).c_str());
if (prefix)
std::printf("%s", prefix);
const size_t length = ArgumentCount(arguments);
for (size_t i = skip_count; i < length; ++i) {
if (i > skip_count)
std::printf("\t");
std::printf("%s", ConvertToPrettyString(arguments[i]).c_str());
}
std::printf("\n");
}
ConsoleFactory::ConsoleFactory() {
AddMemberFunction("assert", &Console::Assert);
AddMemberFunction("error", &Console::Error);
AddMemberFunction("warn", &Console::Warn);
AddMemberFunction("info", &Console::Info);
AddMemberFunction("log", &Console::Log);
AddMemberFunction("debug", &Console::Debug);
}
} // namespace js
} // namespace shaka
<file_sep>/shaka/test/src/media/pipeline_monitor_unittest.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/pipeline_monitor.h"
#include <math.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "src/media/pipeline_manager.h"
#include "src/util/clock.h"
namespace shaka {
namespace media {
namespace {
using testing::_;
using testing::AtLeast;
using testing::InSequence;
using testing::MockFunction;
using testing::NiceMock;
using testing::Return;
using testing::Sequence;
using testing::StrictMock;
class MockClock : public util::Clock {
public:
MOCK_CONST_METHOD0(GetMonotonicTime, uint64_t());
MOCK_CONST_METHOD1(SleepSeconds, void(double));
};
class MockPipelineManager : public PipelineManager {
public:
MockPipelineManager(const util::Clock* clock)
: PipelineManager({}, {}, clock) {}
MOCK_METHOD0(DoneInitializing, void());
MOCK_CONST_METHOD0(GetPipelineStatus, PipelineStatus());
MOCK_CONST_METHOD0(GetDuration, double());
MOCK_METHOD1(SetDuration, void(double));
MOCK_CONST_METHOD0(GetCurrentTime, double());
MOCK_METHOD1(SetCurrentTime, void(double));
MOCK_CONST_METHOD0(GetPlaybackRate, double());
MOCK_METHOD1(SetPlaybackRate, void(double));
MOCK_METHOD0(Play, void());
MOCK_METHOD0(Pause, void());
MOCK_METHOD0(Stalled, void());
MOCK_METHOD0(CanPlay, void());
MOCK_METHOD0(OnEnded, void());
};
#define CALLBACK(var) std::bind(&decltype(var)::Call, &var)
#define CALLBACK1(var) \
std::bind(&decltype(var)::Call, &var, std::placeholders::_1)
} // namespace
TEST(PipelineMonitorTest, ChangesReadyState) {
NiceMock<MockClock> clock;
NiceMock<MockPipelineManager> pipeline(&clock);
MockFunction<BufferedRanges()> get_buffered;
MockFunction<void(MediaReadyState)> ready_state_changed;
EXPECT_CALL(clock, GetMonotonicTime()).WillRepeatedly(Return(0));
EXPECT_CALL(pipeline, GetDuration()).WillRepeatedly(Return(NAN));
EXPECT_CALL(pipeline, GetPipelineStatus())
.WillRepeatedly(Return(PipelineStatus::Paused));
{
#define SET_BUFFERED_RANGE(start, end) \
EXPECT_CALL(get_buffered, Call()) \
.WillRepeatedly(Return(BufferedRanges{{start, end}}));
#define SET_NOTHING_BUFFERED() \
EXPECT_CALL(get_buffered, Call()).WillRepeatedly(Return(BufferedRanges()));
InSequence seq;
SET_BUFFERED_RANGE(0, 10);
EXPECT_CALL(ready_state_changed, Call(HAVE_FUTURE_DATA)).Times(1);
SET_BUFFERED_RANGE(0, 0);
EXPECT_CALL(ready_state_changed, Call(HAVE_CURRENT_DATA)).Times(1);
SET_BUFFERED_RANGE(0, 10);
EXPECT_CALL(ready_state_changed, Call(HAVE_FUTURE_DATA)).Times(1);
SET_NOTHING_BUFFERED();
EXPECT_CALL(ready_state_changed, Call(HAVE_METADATA)).Times(1);
SET_BUFFERED_RANGE(0, 0);
EXPECT_CALL(ready_state_changed, Call(HAVE_CURRENT_DATA)).Times(1);
SET_BUFFERED_RANGE(0, 0);
#undef SET_BUFFERED_RANGE
#undef SET_NOTHING_BUFFERED
}
PipelineMonitor monitor(CALLBACK(get_buffered), CALLBACK(get_buffered),
CALLBACK1(ready_state_changed), &clock, &pipeline);
util::Clock::Instance.SleepSeconds(0.01);
monitor.Stop();
}
TEST(PipelineMonitorTest, ChangesPiplineStatuses) {
NiceMock<MockClock> clock;
StrictMock<MockPipelineManager> pipeline(&clock);
MockFunction<BufferedRanges()> get_buffered;
NiceMock<MockFunction<void(MediaReadyState)>> ready_state_changed;
EXPECT_CALL(pipeline, GetPipelineStatus())
.WillRepeatedly(Return(PipelineStatus::Paused));
EXPECT_CALL(pipeline, GetDuration()).WillRepeatedly(Return(10));
EXPECT_CALL(get_buffered, Call())
.WillRepeatedly(Return(BufferedRanges{{0, 4}, {6, 10}}));
{
// What we want is to say: these things must appear in this order, then
// the next calls can appear in any order. Unfortunately I don't know of a
// way to do this easily. So this creates two sequences to allow the two
// calls at the end to be in any order WRT each other.
Sequence seq1, seq2;
EXPECT_CALL(pipeline, GetCurrentTime())
.InSequence(seq1, seq2)
.WillRepeatedly(Return(0));
EXPECT_CALL(pipeline, CanPlay()).Times(1).InSequence(seq1, seq2);
EXPECT_CALL(pipeline, GetCurrentTime())
.InSequence(seq1, seq2)
.WillRepeatedly(Return(3));
EXPECT_CALL(pipeline, CanPlay()).Times(1).InSequence(seq1, seq2);
EXPECT_CALL(pipeline, GetCurrentTime())
.InSequence(seq1, seq2)
.WillRepeatedly(Return(5));
EXPECT_CALL(pipeline, Stalled()).Times(1).InSequence(seq1, seq2);
EXPECT_CALL(pipeline, GetCurrentTime())
.InSequence(seq1, seq2)
.WillRepeatedly(Return(8));
EXPECT_CALL(pipeline, CanPlay()).Times(1).InSequence(seq1, seq2);
EXPECT_CALL(pipeline, GetCurrentTime())
.InSequence(seq1, seq2)
.WillRepeatedly(Return(10));
EXPECT_CALL(pipeline, OnEnded()).Times(1).InSequence(seq1, seq2);
// Defaults when sequence is done.
EXPECT_CALL(pipeline, GetCurrentTime())
.InSequence(seq1)
.WillRepeatedly(Return(10));
EXPECT_CALL(pipeline, OnEnded()).Times(AtLeast(1)).InSequence(seq2);
}
PipelineMonitor monitor(CALLBACK(get_buffered), CALLBACK(get_buffered),
CALLBACK1(ready_state_changed), &clock, &pipeline);
util::Clock::Instance.SleepSeconds(0.01);
monitor.Stop();
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/media/video_renderer.h
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MEDIA_MEDIA_VIDEO_RENDERER_H_
#define SHAKA_EMBEDDED_MEDIA_MEDIA_VIDEO_RENDERER_H_
#include <functional>
#include <memory>
#include "src/debug/mutex.h"
#include "src/media/frame_drawer.h"
#include "src/media/renderer.h"
#include "src/util/macros.h"
namespace shaka {
namespace media {
class Stream;
/**
* Defines a renderer that draws video frames to the screen.
*/
class VideoRenderer : public Renderer {
public:
VideoRenderer(std::function<double()> get_time, Stream* stream);
~VideoRenderer() override;
NON_COPYABLE_OR_MOVABLE_TYPE(VideoRenderer);
Frame DrawFrame(int* dropped_frame_count, bool* is_new_frame,
double* delay) override;
void OnSeek() override;
void OnSeekDone() override;
private:
void SetDrawerForTesting(std::unique_ptr<FrameDrawer> drawer);
friend class VideoRendererTest;
Mutex mutex_;
Stream* const stream_;
const std::function<double()> get_time_;
std::unique_ptr<FrameDrawer> drawer_;
double prev_time_;
bool is_seeking_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_MEDIA_VIDEO_RENDERER_H_
<file_sep>/shaka/test/main.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include <SDL2/SDL.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <stdlib.h>
#ifdef USING_V8
# include <v8.h>
#endif
#include <algorithm>
#include <fstream>
#include <functional>
#include <string>
#include "shaka/js_manager.h"
#include "src/core/js_manager_impl.h"
#include "src/mapping/callback.h"
#include "src/mapping/register_member.h"
#include "src/test/media_files.h"
#include "src/util/file_system.h"
#include "test/src/test/js_test_fixture.h"
namespace shaka {
// Defined in generated code by //shaka/test/embed_tests.py
void LoadJsTests();
namespace {
DEFINE_bool(no_colors, false, "Don't print colors in test output.");
#ifdef USING_V8
DEFINE_string(v8_flags, "", "Pass the given flags to V8.");
#endif
int RunTests(int argc, char** argv) {
#ifdef OS_IOS
const std::string dynamic_data_dir = std::string(getenv("HOME")) + "/Library";
const std::string static_data_dir = ".";
#else
const std::string dynamic_data_dir = util::FileSystem::DirName(argv[0]);
const std::string static_data_dir = dynamic_data_dir;
#endif
// Init gflags.
gflags::ParseCommandLineFlags(&argc, &argv, true);
// Init logging.
FLAGS_alsologtostderr = true;
google::InitGoogleLogging(argv[0]);
#ifdef USING_V8
// Expose GC to tests (must be done before initializing V8).
const std::string flags_for_v8 = "--expose-gc";
v8::V8::SetFlagsFromString(flags_for_v8.c_str(), flags_for_v8.length());
v8::V8::SetFlagsFromString(FLAGS_v8_flags.c_str(), FLAGS_v8_flags.length());
#endif
// Init gtest.
if (FLAGS_no_colors) {
testing::FLAGS_gtest_color = "no";
setenv("AV_LOG_FORCE_NOCOLOR", "1", 0);
}
if (testing::FLAGS_gtest_output.empty()) {
const std::string file = util::FileSystem::GetPathForDynamicFile(
dynamic_data_dir, "TESTS-results.xml");
testing::FLAGS_gtest_output = "xml:" + file;
}
testing::InitGoogleTest(&argc, argv);
// Find the location of the media files.
InitMediaFiles(argv[0]);
// Start the main JavaScript engine that contains the JavaScript tests.
JsManager::StartupOptions opts;
opts.dynamic_data_dir = dynamic_data_dir;
opts.static_data_dir = static_data_dir;
opts.is_static_relative_to_bundle = true;
JsManager engine(opts);
JsManagerImpl::Instance()->MainThread()->AddInternalTask(
TaskPriority::Immediate, "", PlainCallbackTask(&RegisterTestFixture));
LoadJsTests();
// Run all the tests.
return RUN_ALL_TESTS();
}
} // namespace
} // namespace shaka
#if defined(OS_IOS) && !defined(SHAKA_SDL_UTILS)
// SDL defines |main| so it can wrap it and handle startup. If we don't have
// the SDL utils, then we need to define out own entry point here.
# undef main
#endif
int main(int argc, char** argv) {
const int code = shaka::RunTests(argc, argv);
if (code == 0)
fprintf(stderr, "TEST RESULTS: PASS\n");
else
fprintf(stderr, "TEST RESULTS: FAIL\n");
return code;
}
<file_sep>/shaka/src/util/decryptor_darwin.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/util/decryptor.h"
#include <CommonCrypto/CommonCryptor.h>
#include <Security/Security.h>
#include <glog/logging.h>
namespace shaka {
namespace util {
namespace {
void IncrementIv(std::vector<uint8_t>* iv) {
DCHECK_EQ(iv->size(), AES_BLOCK_SIZE);
auto* iv_ptr = reinterpret_cast<uint64_t*>(iv->data() + 8);
// This converts the number from network (big) byte order to host order, then
// increases the value, then converts back to network byte order.
*iv_ptr = htonll(ntohll(*iv_ptr) + 1);
}
} // namespace
struct Decryptor::Impl {};
Decryptor::Decryptor(eme::EncryptionScheme scheme,
const std::vector<uint8_t>& key,
const std::vector<uint8_t>& iv)
: scheme_(scheme), key_(key), iv_(iv) {
DCHECK_EQ(AES_BLOCK_SIZE, key.size());
DCHECK_EQ(AES_BLOCK_SIZE, iv.size());
}
Decryptor::~Decryptor() {}
bool Decryptor::DecryptPartialBlock(const uint8_t* data, size_t data_size,
uint32_t block_offset, uint8_t* dest) {
if (scheme_ == eme::EncryptionScheme::AesCtr) {
// Mac/iOS only supports CBC, so we need to implement CTR mode based on
// their AES encryption.
size_t data_offset = 0;
while (data_offset < data_size) {
uint8_t encrypted_iv[AES_BLOCK_SIZE];
size_t length;
CCCryptorStatus result = CCCrypt(
kCCEncrypt, kCCAlgorithmAES128, 0, key_.data(), key_.size(), nullptr,
iv_.data(), iv_.size(), encrypted_iv, AES_BLOCK_SIZE, &length);
if (result != kCCSuccess) {
LOG(ERROR) << "Error decrypting data: " << result;
return false;
}
if (length != AES_BLOCK_SIZE) {
LOG(ERROR) << "Not all data decrypted";
return false;
}
const size_t to_decrypt = AES_BLOCK_SIZE - block_offset;
for (size_t i = 0; i < to_decrypt && i + data_offset < data_size; i++) {
dest[data_offset + i] =
data[data_offset + i] ^ encrypted_iv[i + block_offset];
}
data_offset += to_decrypt;
block_offset = 0;
IncrementIv(&iv_);
}
} else {
if (block_offset != 0) {
LOG(ERROR) << "Cannot have block offset when using CBC";
return false;
}
if (data_size % AES_BLOCK_SIZE != 0u) {
LOG(ERROR) << "CBC requires protected ranges to be a multiple of the "
"block size.";
return false;
}
// This uses AES-CBC.
size_t length;
CCCryptorStatus result =
CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0, key_.data(), key_.size(),
iv_.data(), data, data_size, dest, data_size, &length);
if (result != kCCSuccess) {
LOG(ERROR) << "Error decrypting data: " << result;
return false;
}
if (length != data_size) {
LOG(ERROR) << "Not all data decrypted";
return false;
}
if (data_size >= AES_BLOCK_SIZE) {
iv_.assign(data + data_size - AES_BLOCK_SIZE, data + data_size);
}
}
return true;
}
bool Decryptor::Decrypt(const uint8_t* data, size_t data_size, uint8_t* dest) {
return DecryptPartialBlock(data, data_size, 0, dest);
}
bool Decryptor::InitIfNeeded() {
return true;
}
} // namespace util
} // namespace shaka
<file_sep>/shaka/src/mapping/js_utils.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MAPPING_JS_UTILS_H_
#define SHAKA_EMBEDDED_MAPPING_JS_UTILS_H_
#include <string>
#include <vector>
#include "src/mapping/js_wrappers.h"
namespace shaka {
/**
* Traverses a namespace/object structure to get a descendant member. This will
* repeatedly get the child of the current object with a name from @a names,
* starting at @a root. This will return an empty value if one of the children
* isn't found or isn't an object.
*
* @param root The object to start traversing at.
* @param names The member names to traverse with.
* @return The descendant at the given path, or an empty value if not found.
*/
ReturnVal<JsValue> GetDescendant(Handle<JsObject> root,
const std::vector<std::string>& names);
} // namespace shaka
#endif // SHAKA_EMBEDDED_MAPPING_JS_UTILS_H_
<file_sep>/shaka/src/js/mse/source_buffer.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/mse/source_buffer.h"
#include <cmath>
#include <utility>
#include "src/js/events/event.h"
#include "src/js/events/event_names.h"
#include "src/js/js_error.h"
#include "src/js/mse/media_source.h"
#include "src/js/mse/time_ranges.h"
#include "src/media/media_utils.h"
namespace shaka {
namespace js {
namespace mse {
SourceBuffer::SourceBuffer(RefPtr<MediaSource> media_source,
media::SourceType type)
: mode(AppendMode::SEGMENTS),
updating(false),
timestamp_offset_(0),
append_window_start_(0),
append_window_end_(HUGE_VAL /* Infinity */),
media_source_(media_source),
type_(type) {
AddListenerField(EventType::UpdateStart, &on_update_start);
AddListenerField(EventType::Update, &on_update);
AddListenerField(EventType::UpdateEnd, &on_update_end);
AddListenerField(EventType::Error, &on_error);
AddListenerField(EventType::Abort, &on_abort);
}
// \cond Doxygen_Skip
SourceBuffer::~SourceBuffer() {}
// \endcond Doxygen_Skip
void SourceBuffer::Trace(memory::HeapTracer* tracer) const {
events::EventTarget::Trace(tracer);
tracer->Trace(&append_buffer_);
tracer->Trace(&media_source_);
}
ExceptionOr<void> SourceBuffer::AppendBuffer(ByteBuffer data) {
if (!media_source_) {
return JsError::DOMException(
InvalidStateError, "SourceBuffer has been detached from the <video>.");
}
if (updating) {
return JsError::DOMException(InvalidStateError,
"Already performing an update.");
}
if (media_source_->ready_state == MediaSourceReadyState::ENDED) {
media_source_->ready_state = MediaSourceReadyState::OPEN;
media_source_->ScheduleEvent<events::Event>(EventType::SourceOpen);
}
using namespace std::placeholders; // NOLINT
append_buffer_ = std::move(data);
if (!media_source_->GetController()->AppendData(
type_, timestamp_offset_, append_window_start_, append_window_end_,
append_buffer_.data(), append_buffer_.size(),
std::bind(&SourceBuffer::OnAppendComplete, this, _1))) {
return JsError::DOMException(
InvalidStateError, "Unable to find source type " + to_string(type_));
}
updating = true;
return {};
}
void SourceBuffer::Abort() {
// TODO:
}
ExceptionOr<void> SourceBuffer::Remove(double start, double end) {
if (!media_source_) {
return JsError::DOMException(
InvalidStateError, "SourceBuffer has been detached from the <video>.");
}
if (updating) {
return JsError::DOMException(InvalidStateError,
"Already performing an update.");
}
// TODO: Consider running this on a background thread.
if (!media_source_->GetController()->Remove(type_, start, end)) {
return JsError::DOMException(
InvalidStateError, "Unable to find source type " + to_string(type_));
}
ScheduleEvent<events::Event>(EventType::UpdateEnd);
return {};
}
void SourceBuffer::CloseMediaSource() {
media_source_ = nullptr;
}
ExceptionOr<RefPtr<TimeRanges>> SourceBuffer::GetBuffered() const {
if (!media_source_) {
return JsError::DOMException(
InvalidStateError,
"SourceBuffer is detached from the <video> element.");
}
return new TimeRanges(
media_source_->GetController()->GetBufferedRanges(type_));
}
double SourceBuffer::TimestampOffset() const {
return timestamp_offset_;
}
ExceptionOr<void> SourceBuffer::SetTimestampOffset(double offset) {
if (!std::isfinite(offset)) {
return JsError::TypeError("timestampOffset cannot be NaN or +/-Infinity.");
}
if (!media_source_) {
return JsError::DOMException(
InvalidStateError,
"SourceBuffer is detached from the <video> element.");
}
if (updating) {
return JsError::DOMException(InvalidStateError,
"Already performing an update.");
}
timestamp_offset_ = offset;
return {};
}
double SourceBuffer::AppendWindowStart() const {
return append_window_start_;
}
ExceptionOr<void> SourceBuffer::SetAppendWindowStart(double window_start) {
if (!std::isfinite(window_start)) {
return JsError::TypeError(
"appendWindowStart cannot be NaN or +/-Infinity.");
}
if (!media_source_) {
return JsError::DOMException(
InvalidStateError,
"SourceBuffer is detached from the <video> element.");
}
if (updating) {
return JsError::DOMException(InvalidStateError,
"Already performing an update.");
}
if (window_start < 0) {
return JsError::TypeError("appendWindowStart cannot be negative.");
}
if (window_start >= append_window_end_) {
return JsError::TypeError(
"appendWindowStart cannot be greater than appendWindowEnd.");
}
append_window_start_ = window_start;
return {};
}
double SourceBuffer::AppendWindowEnd() const {
return append_window_end_;
}
ExceptionOr<void> SourceBuffer::SetAppendWindowEnd(double window_end) {
if (!media_source_) {
return JsError::DOMException(
InvalidStateError,
"SourceBuffer is detached from the <video> element.");
}
if (updating) {
return JsError::DOMException(InvalidStateError,
"Already performing an update.");
}
if (std::isnan(window_end)) {
return JsError::TypeError("appendWindowEnd cannot be NaN.");
}
if (window_end <= append_window_start_) {
return JsError::TypeError(
"appendWindowEnd cannot be less than appendWindowStart.");
}
append_window_end_ = window_end;
return {};
}
void SourceBuffer::OnAppendComplete(media::Status status) {
VLOG(1) << "Finish appending media segment: " << status;
updating = false;
if (status != media::Status::Success) {
Abort();
ScheduleEvent<events::Event>(EventType::Error);
}
ScheduleEvent<events::Event>(EventType::UpdateEnd);
}
SourceBufferFactory::SourceBufferFactory() {
AddListenerField(EventType::UpdateStart, &SourceBuffer::on_update_start);
AddListenerField(EventType::Update, &SourceBuffer::on_update);
AddListenerField(EventType::UpdateEnd, &SourceBuffer::on_update_end);
AddListenerField(EventType::Error, &SourceBuffer::on_error);
AddListenerField(EventType::Abort, &SourceBuffer::on_abort);
AddGenericProperty("buffered", &SourceBuffer::GetBuffered);
AddGenericProperty("timestampOffset", &SourceBuffer::TimestampOffset,
&SourceBuffer::SetTimestampOffset);
AddGenericProperty("appendWindowStart", &SourceBuffer::AppendWindowStart,
&SourceBuffer::SetAppendWindowStart);
AddGenericProperty("appendWindowEnd", &SourceBuffer::AppendWindowEnd,
&SourceBuffer::SetAppendWindowEnd);
AddReadWriteProperty("mode", &SourceBuffer::mode);
AddReadOnlyProperty("updating", &SourceBuffer::updating);
AddMemberFunction("appendBuffer", &SourceBuffer::AppendBuffer);
AddMemberFunction("abort", &SourceBuffer::Abort);
AddMemberFunction("remove", &SourceBuffer::Remove);
NotImplemented("audioTracks");
NotImplemented("videoTracks");
NotImplemented("textTracks");
}
} // namespace mse
} // namespace js
} // namespace shaka
<file_sep>/shaka/src/media/audio_renderer.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/audio_renderer.h"
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavutil/opt.h>
#include <libswresample/swresample.h>
}
#include <algorithm>
#include <utility>
#include "src/media/ffmpeg_decoded_frame.h"
#include "src/util/clock.h"
#include "src/util/utils.h"
namespace shaka {
namespace media {
namespace {
/**
* The maximum playback rate we will adjust audio for. If the playback rate
* is more than this, we will mute the audio.
*/
constexpr const double kMaxPlaybackRate = 4;
/**
* The maximum delay, in seconds, between the frame time and the real time it
* will be played before a seek happens. This can happen when muted or if the
* frames have gaps. If the delay is too large, simulate a seek and start
* playing frames based on the current real time.
*/
constexpr const double kMaxDelay = 0.2;
SDL_AudioFormat SDLFormatFromFFmpeg(AVSampleFormat format) {
// Try to use the same format to avoid work by swresample.
switch (format) {
case AV_SAMPLE_FMT_U8:
case AV_SAMPLE_FMT_U8P:
return AUDIO_U8;
case AV_SAMPLE_FMT_S16:
case AV_SAMPLE_FMT_S16P:
return AUDIO_S16SYS;
case AV_SAMPLE_FMT_S32:
case AV_SAMPLE_FMT_S32P:
return AUDIO_S32SYS;
case AV_SAMPLE_FMT_FLT:
case AV_SAMPLE_FMT_FLTP:
return AUDIO_F32SYS;
case AV_SAMPLE_FMT_DBL:
case AV_SAMPLE_FMT_DBLP: {
LOG_ONCE(WARNING) << "SDL doesn't support double-precision audio "
<< "formats, converting to floats.";
return AUDIO_F32SYS;
}
case AV_SAMPLE_FMT_S64:
case AV_SAMPLE_FMT_S64P: {
LOG_ONCE(WARNING) << "SDL doesn't support 64-bit audio "
<< "formats, converting to 32-bit.";
return AUDIO_S32SYS;
}
default:
LOG(DFATAL) << "Unknown audio sample format: " << format;
return AUDIO_S32SYS;
}
}
AVSampleFormat FFmpegFormatFromSDL(int format) {
// Note that AUDIO_*SYS is an alias for either AUDIO_*LSB or AUDIO_*MSB.
switch (format) {
case AUDIO_U8:
return AV_SAMPLE_FMT_U8;
case AUDIO_S16LSB:
case AUDIO_S16MSB:
if (format != AUDIO_S16SYS) {
LOG(ERROR) << "swresample doesn't support non-native endian audio";
return AV_SAMPLE_FMT_NONE;
}
return AV_SAMPLE_FMT_S16;
case AUDIO_S32LSB:
case AUDIO_S32MSB:
if (format != AUDIO_S32SYS) {
LOG(ERROR) << "swresample doesn't support non-native endian audio";
return AV_SAMPLE_FMT_NONE;
}
return AV_SAMPLE_FMT_S32;
case AUDIO_F32LSB:
case AUDIO_F32MSB:
if (format != AUDIO_F32SYS) {
LOG(ERROR) << "swresample doesn't support non-native endian audio";
return AV_SAMPLE_FMT_NONE;
}
return AV_SAMPLE_FMT_FLT;
case AUDIO_S8:
LOG(ERROR) << "swresample doesn't support signed 8-bit audio.";
return AV_SAMPLE_FMT_NONE;
case AUDIO_U16LSB:
case AUDIO_U16MSB:
LOG(ERROR) << "swresample doesn't support unsigned 16-bit audio";
return AV_SAMPLE_FMT_NONE;
default:
LOG(DFATAL) << "Unknown audio sample format: " << format;
return AV_SAMPLE_FMT_S32;
}
}
int64_t GetChannelLayout(int num_channels) {
// See |channels| in https://wiki.libsdl.org/SDL_AudioSpec.
switch (num_channels) {
case 1:
return AV_CH_LAYOUT_MONO;
case 2:
return AV_CH_LAYOUT_STEREO;
case 4:
return AV_CH_LAYOUT_QUAD;
case 6:
return AV_CH_LAYOUT_5POINT1;
default:
LOG(DFATAL) << "Unsupported channel count: " << num_channels;
return AV_CH_LAYOUT_STEREO;
}
}
} // namespace
AudioRenderer::AudioRenderer(std::function<double()> get_time,
std::function<double()> get_playback_rate,
Stream* stream)
: get_time_(std::move(get_time)),
get_playback_rate_(std::move(get_playback_rate)),
stream_(stream),
mutex_("AudioRenderer"),
on_reset_("Reset AudioRenderer"),
audio_device_(0),
swr_ctx_(nullptr),
cur_time_(-1),
volume_(1),
shutdown_(false),
need_reset_(true),
is_seeking_(false),
thread_("AudioRenderer", std::bind(&AudioRenderer::ThreadMain, this)) {}
AudioRenderer::~AudioRenderer() {
{
std::unique_lock<Mutex> lock(mutex_);
shutdown_ = true;
}
on_reset_.SignalAllIfNotSet();
thread_.join();
if (audio_device_ > 0)
SDL_CloseAudioDevice(audio_device_);
swr_free(&swr_ctx_);
}
void AudioRenderer::OnSeek() {
std::unique_lock<Mutex> lock(mutex_);
is_seeking_ = true;
cur_time_ = -1;
}
void AudioRenderer::OnSeekDone() {
std::unique_lock<Mutex> lock(mutex_);
is_seeking_ = false;
// Now that the seek is done, discard frames from the old time.
const double time = get_time_();
stream_->GetDecodedFrames()->Remove(0, time - 3);
stream_->GetDecodedFrames()->Remove(time + 3, HUGE_VAL);
}
void AudioRenderer::SetVolume(double volume) {
std::unique_lock<Mutex> lock(mutex_);
volume_ = volume;
if (swr_ctx_) {
av_opt_set_double(swr_ctx_, "rematrix_volume", volume_, 0);
swr_init(swr_ctx_);
}
}
void AudioRenderer::ThreadMain() {
std::unique_lock<Mutex> lock(mutex_);
while (!shutdown_) {
if (need_reset_) {
if (audio_device_ != 0) {
SDL_CloseAudioDevice(audio_device_);
audio_device_ = 0;
}
cur_time_ = get_time_();
auto base_frame = stream_->GetDecodedFrames()->GetFrameAfter(cur_time_);
if (!base_frame) {
util::Unlocker<Mutex> unlock(&lock);
util::Clock::Instance.SleepSeconds(0.01);
continue;
}
CHECK(base_frame->frame_type() == FrameType::FFmpegDecodedFrame);
auto* frame = static_cast<const FFmpegDecodedFrame*>(base_frame.get());
if (!InitDevice(frame))
return;
SDL_PauseAudioDevice(audio_device_, 0);
need_reset_ = false;
}
on_reset_.ResetAndWaitWhileUnlocked(lock);
}
}
bool AudioRenderer::InitDevice(const FFmpegDecodedFrame* frame) {
if (!SDL_WasInit(SDL_INIT_AUDIO)) {
SDL_SetMainReady();
if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
LOG(ERROR) << "Error initializing SDL: " << SDL_GetError();
return false;
}
}
memset(&audio_spec_, 0, sizeof(audio_spec_));
audio_spec_.freq = frame->raw_frame()->sample_rate;
audio_spec_.format = SDLFormatFromFFmpeg(frame->sample_format());
audio_spec_.channels = static_cast<Uint8>(frame->raw_frame()->channels);
audio_spec_.samples = static_cast<Uint16>(frame->raw_frame()->nb_samples *
frame->raw_frame()->channels);
audio_spec_.callback = &OnAudioCallback;
audio_spec_.userdata = this;
audio_device_ =
SDL_OpenAudioDevice(nullptr, 0, &audio_spec_, &obtained_audio_spec_,
SDL_AUDIO_ALLOW_ANY_CHANGE);
if (audio_device_ == 0) {
LOG(ERROR) << "Error opening audio device: " << SDL_GetError();
return false;
}
// SDL may change the format so we get hardware acceleration. Make sure
// to use the format SDL expects.
const AVSampleFormat av_sample_format =
FFmpegFormatFromSDL(obtained_audio_spec_.format);
if (av_sample_format == AV_SAMPLE_FMT_NONE)
return false;
swr_ctx_ = swr_alloc_set_opts(
swr_ctx_,
GetChannelLayout(obtained_audio_spec_.channels), // out_ch_layout
av_sample_format, // out_sample_fmt
obtained_audio_spec_.freq, // out_sample_rate
frame->raw_frame()->channel_layout, // in_ch_layout
frame->sample_format(), // in_sample_fmt
frame->raw_frame()->sample_rate, // in_sample_rate
0, // log_offset,
nullptr); // log_ctx
if (!swr_ctx_) {
LOG(ERROR) << "Unable to allocate swrescale context.";
return false;
}
// Minimum difference before changing samples to match timestamps.
av_opt_set_double(swr_ctx_, "min_comp", 0.01, 0);
// Maximum factor to adjust existing samples by.
av_opt_set_double(swr_ctx_, "max_soft_comp", 0.01, 0);
// Minimum difference before applying hard compensation (adding/dropping
// samples).
av_opt_set_double(swr_ctx_, "min_hard_comp", 0.1, 0);
// Sync samples to timestamps.
av_opt_set_double(swr_ctx_, "async", 1, 0);
// Change volume to this value.
av_opt_set_double(swr_ctx_, "rematrix_volume", volume_, 0);
swr_init(swr_ctx_);
return true;
}
// static
void AudioRenderer::OnAudioCallback(void* user_data, uint8_t* data, int size) {
reinterpret_cast<AudioRenderer*>(user_data)->AudioCallback(data, size);
}
void AudioRenderer::AudioCallback(uint8_t* data, int size) {
std::unique_lock<Mutex> lock(mutex_);
if (cur_time_ >= 0)
stream_->GetDecodedFrames()->Remove(0, cur_time_ - 0.2);
const double playback_rate = get_playback_rate_();
// TODO: Support playback rate by using atemp filter.
DCHECK(playback_rate == 0 || playback_rate == 1)
<< "Only playbackRate of 0 and 1 are supported.";
if (need_reset_ || is_seeking_ || volume_ == 0 || playback_rate <= 0 ||
playback_rate > kMaxPlaybackRate) {
memset(data, obtained_audio_spec_.silence, size);
return;
}
const AVSampleFormat av_sample_format =
FFmpegFormatFromSDL(obtained_audio_spec_.format);
const int sample_size =
av_get_bytes_per_sample(av_sample_format) * obtained_audio_spec_.channels;
int size_in_samples = size / sample_size;
DCHECK_EQ(size % sample_size, 0);
const double now_time = get_time_();
if (cur_time_ >= 0) {
// |cur_time_ - delay| represents the playhead time that is about to be
// played.
const double delay = swr_get_delay(swr_ctx_, 1000) / 1000.0;
if (cur_time_ - delay < now_time - kMaxDelay) {
// The next frame being played is from too long ago; so simulate a seek to
// play the audio at the playhead.
cur_time_ = -1;
}
}
if (cur_time_ < 0) {
cur_time_ = now_time;
// swr will adjust samples to match their expected timestamps; reset the
// context on seek so it doesn't break with the new timestamps.
swr_init(swr_ctx_);
}
// Flush existing data before reading more frames.
const int initial_sample_count =
swr_convert(swr_ctx_, &data, size_in_samples, nullptr, 0);
if (initial_sample_count < 0) {
memset(data, 0, size);
return;
}
DCHECK_LE(initial_sample_count, size_in_samples);
size_in_samples -= initial_sample_count;
data += initial_sample_count * sample_size;
while (size_in_samples > 0) {
auto base_frame = stream_->GetDecodedFrames()->GetFrameAfter(cur_time_);
if (!base_frame)
break;
CHECK(base_frame->frame_type() == FrameType::FFmpegDecodedFrame);
auto* frame = static_cast<const FFmpegDecodedFrame*>(base_frame.get());
// If the source changed, we need to reset. If the new frame has a lower
// sample rate or channel count, we can just use swresample to change
// these. If they are higher, we want to try to create a new device so we
// get the benefits.
if (frame->raw_frame()->sample_rate > audio_spec_.freq ||
frame->raw_frame()->channels > audio_spec_.channels ||
SDLFormatFromFFmpeg(frame->sample_format()) != audio_spec_.format) {
need_reset_ = true;
on_reset_.SignalAll();
break;
}
if (frame->raw_frame()->sample_rate != audio_spec_.freq) {
av_opt_set_int(swr_ctx_, "in_sample_rate",
frame->raw_frame()->sample_rate, 0);
swr_init(swr_ctx_);
audio_spec_.freq = frame->raw_frame()->sample_rate;
}
if (frame->raw_frame()->channels != audio_spec_.channels) {
av_opt_set_int(swr_ctx_, "in_channel_layout",
GetChannelLayout(frame->raw_frame()->channels), 0);
swr_init(swr_ctx_);
audio_spec_.channels = static_cast<Uint8>(frame->raw_frame()->channels);
}
// Assume the first byte in the array will be played "right-now", or at
// |now_time|. This is technically not correct, but the delay shouldn't be
// noticeable.
const auto pts =
static_cast<uint64_t>(frame->pts * obtained_audio_spec_.freq *
frame->raw_frame()->sample_rate);
// Swr will adjust the audio so the next sample will happen at |pts|.
if (swr_next_pts(swr_ctx_, pts) < 0)
break;
const int samples_read =
swr_convert(swr_ctx_, &data, size_in_samples,
const_cast<const uint8_t**>(frame->data()), // NOLINT
frame->raw_frame()->nb_samples);
if (samples_read < 0)
break;
DCHECK_LE(samples_read, size_in_samples);
size_in_samples -= samples_read;
data += samples_read * sample_size;
cur_time_ = frame->pts;
}
// Set any remaining data to silence in the event of errors.
memset(data, obtained_audio_spec_.silence, size_in_samples * sample_size);
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/mapping/struct.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/mapping/struct.h"
#include "src/mapping/weak_js_ptr.h"
namespace shaka {
Struct::Struct() {}
Struct::~Struct() {}
Struct::Struct(const Struct&) = default;
Struct::Struct(Struct&&) = default;
Struct& Struct::operator=(const Struct&) = default;
Struct& Struct::operator=(Struct&&) = default;
bool Struct::TryConvert(Handle<JsValue> value) {
if (!IsObject(value))
return false;
LocalVar<JsObject> obj = UnsafeJsCast<JsObject>(value);
for (auto& converter : converters_)
converter->SearchAndStore(this, obj);
return true;
}
ReturnVal<JsValue> Struct::ToJsValue() const {
WeakJsPtr<JsObject> obj(CreateObject());
for (auto& converter : converters_)
converter->AddToObject(this, obj.handle());
return obj.value();
}
void Struct::Trace(memory::HeapTracer* tracer) const {
for (auto& converter : converters_)
converter->Trace(this, tracer);
}
} // namespace shaka
<file_sep>/shaka/src/util/file_system_win.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/util/file_system.h"
#include <Shlwapi.h>
#include <glog/logging.h>
namespace shaka {
namespace util {
// static
std::string FileSystem::PathJoin(const std::string& a, const std::string& b) {
std::string ret(MAX_PATH, '\0');
if (!PathCombineA(ret.c_str(), a.c_str(), b.c_str()))
return "";
ret.resize(strlen(ret.c_str()));
return ret;
}
// static
std::string FileSystem::DirName(const std::string& path) {
#error "Not implemented for Windows"
}
bool FileSystem::FileExists(const std::string& path) const {
// Cannot use fstream for this since it allows opening directories.
return PathFileExists(path.c_str());
}
bool FileSystem::DirectoryExists(const std::string& path) const {
return PathIsDirectory(path.c_str());
}
bool FileSystem::ListFiles(const std::string& path,
std::vector<std::string>* files) const {
files->clear();
#error "Not implemented for Windows"
return true;
}
} // namespace util
} // namespace shaka
<file_sep>/shaka/src/public/error.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "shaka/error.h"
#include "src/util/macros.h"
namespace shaka {
class Error::Impl {};
Error::Error(ErrorType type, const std::string& message)
: message(message), type(type), category(0), code(0), severity(0) {}
Error::Error(int category, int code, int severity, const std::string& message)
: message(message),
type(ErrorType::ShakaError),
category(category),
code(code),
severity(severity) {}
Error::Error(const Error& other)
: message(other.message),
type(other.type),
category(other.category),
code(other.code),
severity(other.severity) {}
Error::Error(Error&&) = default;
Error::~Error() {}
Error& Error::operator=(const Error& other) {
message = other.message;
type = other.type;
category = other.category;
code = other.code;
severity = other.severity;
return *this;
}
Error& Error::operator=(Error&&) = default;
} // namespace shaka
<file_sep>/shaka/src/util/templates.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_UTIL_TEMPLATES_H_
#define SHAKA_EMBEDDED_UTIL_TEMPLATES_H_
#include <type_traits>
#if defined(USING_V8)
# include <v8.h>
#endif
namespace shaka {
template <typename T>
class optional;
namespace util {
/**
* A conditional type to determine if a type T is a V8 type. Note that for
* incomplete types, this returns false as we never forward-declare V8 types.
*/
template <typename T, typename = void>
struct is_v8_type : std::false_type {};
// Can only call sizeof(T) for complete types.
#if defined(USING_V8)
template <typename T>
struct is_v8_type<T, decltype(void(sizeof(T)))> : std::is_base_of<v8::Data, T> {
};
#endif
/**
* A conditional type to determine whether the given type is a JavaScript
* number, namely a number (non-bool) type or an enumeration.
*/
template <typename T>
struct is_number
: std::integral_constant<bool, std::is_arithmetic<T>::value &&
!std::is_same<T, bool>::value> {};
template <typename A, typename B>
struct decay_is_same
: std::is_same<typename std::decay<A>::type, typename std::decay<B>::type> {
};
template <bool B, typename T = void>
using enable_if_t = typename std::enable_if<B, T>::type;
} // namespace util
} // namespace shaka
#endif // SHAKA_EMBEDDED_UTIL_TEMPLATES_H_
<file_sep>/shaka/src/util/shared_lock.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/util/shared_lock.h"
namespace shaka {
namespace util {
shared_mutex::shared_mutex() {}
shared_mutex::~shared_mutex() {
DCHECK(!is_exclusive_) << "Trying to destroy a locked mutex";
DCHECK_EQ(0, shared_count_) << "Trying to destroy a locked mutex";
}
void shared_mutex::unlock() {
{
std::unique_lock<std::mutex> lock(mutex_);
DCHECK(is_exclusive_) << "Trying to unlock an already unlocked mutex";
DCHECK_EQ(shared_count_, 0) << "Cannot have shared locks in exclusive mode";
is_exclusive_ = false;
}
signal_.notify_all();
}
void shared_mutex::unlock_shared() {
{
std::unique_lock<std::mutex> lock(mutex_);
DCHECK(!is_exclusive_) << "Cannot hold unique lock with shared lock";
DCHECK_GT(shared_count_, 0) << "Trying to unlock an already unlocked mutex";
shared_count_--;
}
signal_.notify_all();
}
bool shared_mutex::maybe_try_lock(bool only_try) {
// Note this lock is only held transitively, so it shouldn't block for long.
std::unique_lock<std::mutex> lock(mutex_);
while (is_exclusive_ || shared_count_ > 0) {
if (only_try)
return false;
is_exclusive_waiting_ = true;
signal_.wait(lock);
}
is_exclusive_ = true;
is_exclusive_waiting_ = false;
return true;
}
bool shared_mutex::maybe_try_lock_shared(bool only_try) {
// Note this lock is only held transitively, so it shouldn't block for long.
std::unique_lock<std::mutex> lock(mutex_);
// Wait if there is an exclusive lock waiting. This ensures that if there
// are a bunch of readers, a writer can still get in.
while (is_exclusive_ || is_exclusive_waiting_) {
if (only_try)
return false;
signal_.wait(lock);
}
shared_count_++;
return true;
}
} // namespace util
} // namespace shaka
<file_sep>/shaka/tools/idl/exposed_type_generator.py
#!/usr/bin/python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""A code-generator used for exposing types from JavaScript through the API.
This generates several types from the same IDL definition: (a) an internal
type used in the mapping framework, (b) a type exposed to the C++ API, and
(c) a type exposed in the Objective-C API.
"""
import argparse
import os
import re
import sys
TOOLS_DIR = os.path.join(os.path.dirname(__file__), '..')
ROOT_DIR = os.path.join(TOOLS_DIR, '..', '..')
sys.path.append(TOOLS_DIR)
sys.path.append(os.path.join(ROOT_DIR, 'third_party', 'ply', 'src'))
sys.path.append(os.path.join(TOOLS_DIR, 'webidl'))
import embed_utils
import webidl
def _MapCppType(t, other_types, is_public):
"""Returns a C++ type name for the given IDL type."""
if t.element_type:
assert t.name == 'sequence'
ret = 'std::vector<%s>' % _MapCppType(
t.element_type, other_types, is_public)
elif t.name in other_types:
if is_public:
return 'shaka::' + t.name
else:
return 'shaka::js::' + t.name
else:
type_map = {
# IDL -> C++
'boolean': 'bool',
'double': 'double',
'DOMString': 'std::string',
}
assert t.name in type_map, 'Type %s not found' % t.name
ret = type_map[t.name]
return 'shaka::optional<%s>' % ret if t.nullable else ret
def _MapObjcType(t, other_types):
"""Returns an Objective-C type name for the given IDL type."""
if t.element_type:
assert t.name == 'sequence'
return 'NSArray<%s>*' % _MapObjcType(t.element_type, other_types)
elif t.name in other_types:
return 'Shaka%s*' % t.name
else:
type_map = {
# IDL -> Objective-C
'boolean': 'BOOL',
'double': 'double',
'DOMString': 'NSString*',
}
assert t.name in type_map, 'Type %s not found' % t.name
return type_map[t.name]
def _GetPublicFieldName(attr):
"""Converts a lowerCamelCase field name to lower_with_underscores."""
return re.sub(r'([A-Z])', r'_\1', attr.name).lower()
def _GetObjcName(attr):
"""Returns the Objective-C name for the given attribute."""
if attr.name.startswith('init'):
return 'getI' + attr.name[1:]
return attr.name
def _FormatDoc(obj, indent):
"""Formats a docstring for printing."""
# Find how much the first part is indented.
prefix = ' ' * (obj.docDebug.col - 1)
lines = obj.doc.split('\n')
# Then remove that much from each next line so we preserve relative indenting.
for i in range(1, len(lines)):
assert lines[i].startswith(prefix)
lines[i] = (' ' * indent) + lines[i][len(prefix):]
return '\n'.join(lines).lstrip()
def _GetDefault(t):
"""Returns a string containing the default value of the given type."""
if t.element_type or t.nullable:
return None # Arrays and optional<T> are default-initialized
type_map = {
'boolean': 'false',
'double': '0',
'DOMString': None, # std::string are default-initialized.
}
assert t.name in type_map, 'Type %s not found' % t.name
return type_map[t.name]
def _GenerateJsHeader(results, f, name, public_header):
"""Generates the header for the JavaScript mapping type."""
other_types = [t.name for t in results.types]
writer = embed_utils.CodeWriter(f)
writer.Write('#ifndef SHAKA_EMBEDDED_INTERNAL_%s_H_', name.upper())
writer.Write('#define SHAKA_EMBEDDED_INTERNAL_%s_H_', name.upper())
writer.Write()
writer.Write('#include <string>')
writer.Write('#include <vector>')
writer.Write()
writer.Write('#include "shaka/optional.h"')
writer.Write('#include "%s"', public_header)
writer.Write('#include "src/mapping/convert_js.h"')
writer.Write('#include "src/mapping/struct.h"')
writer.Write()
with writer.Namespace('shaka'):
with writer.Namespace('js'):
for t in results.types:
with writer.Block('struct %s : Struct' % t.name, semicolon=True):
with writer.Block('static std::string name()'):
writer.Write('return "%s";', t.name)
writer.Write()
writer.Write('%s();', t.name)
writer.Write('%s(const %s&);', t.name, t.name)
writer.Write('%s(%s&&);', t.name, t.name)
writer.Write('~%s();', t.name)
writer.Write()
writer.Write('%s& operator=(const %s&);', t.name, t.name)
writer.Write('%s& operator=(%s&&);', t.name, t.name)
writer.Write()
for attr in t.attributes:
writer.Write('ADD_DICT_FIELD(%s, %s);',
_MapCppType(attr.type, other_types, is_public=False),
attr.name)
writer.Write()
writer.Write()
for t in results.types:
writer.Write('template <>')
with writer.Block(
'struct impl::ConvertHelper<shaka::%s, void>' % t.name,
semicolon=True):
with writer.Block('static bool FromJsValue(Handle<JsValue> source, '
'shaka::%s* dest)' % t.name):
writer.Write('shaka::js::%s temp;', t.name)
with writer.Block('if (!ConvertHelper<shaka::js::%s>::FromJsValue('
'source, &temp))' % t.name):
writer.Write('return false;')
writer.Write('*dest = shaka::%s(temp);', t.name)
writer.Write('return true;')
writer.Write()
writer.Write()
writer.Write('#endif // SHAKA_EMBEDDED_INTERNAL_%s_H_', name.upper())
def _GenerateJsSource(results, f, header):
"""Generates the source file for the JavaScript mapping type."""
writer = embed_utils.CodeWriter(f)
writer.Write('#include "%s"', header)
writer.Write()
with writer.Namespace('shaka'):
with writer.Namespace('js'):
for t in results.types:
writer.Write('%s::%s() {}', t.name, t.name)
writer.Write('%s::%s(const %s&) = default;', t.name, t.name, t.name)
writer.Write('%s::%s(%s&&) = default;', t.name, t.name, t.name)
writer.Write('%s::~%s() {}', t.name, t.name)
writer.Write()
writer.Write('%s& %s::operator=(const %s&) = default;', t.name, t.name,
t.name)
writer.Write('%s& %s::operator=(%s&&) = default;', t.name, t.name,
t.name)
writer.Write()
writer.Write()
def _GeneratePublicHeader(results, f, name):
"""Generates the header for the public C++ type."""
other_types = [t.name for t in results.types]
writer = embed_utils.CodeWriter(f)
writer.Write('#ifndef SHAKA_EMBEDDED_%s_H_', name.upper())
writer.Write('#define SHAKA_EMBEDDED_%s_H_', name.upper())
writer.Write()
writer.Write('#include <memory>')
writer.Write('#include <string>')
writer.Write('#include <vector>')
writer.Write()
writer.Write('#include "macros.h"')
writer.Write('#include "optional.h"')
writer.Write()
with writer.Namespace('shaka'):
with writer.Namespace('js'):
for t in results.types:
writer.Write('struct %s;', t.name)
writer.Write()
for t in results.types:
if t.doc:
writer.Write(_FormatDoc(t, indent=0))
with writer.Block('class SHAKA_EXPORT %s final' % t.name, semicolon=True):
writer.Write('public:', offset=-1)
writer.Write('%s();', t.name)
writer.Write('%s(const js::%s& internal);', t.name, t.name)
writer.Write('%s(const %s&);', t.name, t.name)
writer.Write('%s(%s&&);', t.name, t.name)
writer.Write('~%s();', t.name)
writer.Write()
writer.Write('%s& operator=(const %s&);', t.name, t.name)
writer.Write('%s& operator=(%s&&);', t.name, t.name)
writer.Write()
for attr in t.attributes:
if attr.doc:
writer.Write(_FormatDoc(attr, indent=2))
writer.Write('%s %s() const;',
_MapCppType(attr.type, other_types, is_public=True),
_GetPublicFieldName(attr))
writer.Write()
writer.Write('private:', offset=-1)
writer.Write('friend class Player;')
writer.Write()
writer.Write('const js::%s& GetInternal() const;', t.name)
writer.Write()
writer.Write('class Impl;')
writer.Write('std::shared_ptr<Impl> impl_;')
writer.Write()
writer.Write()
writer.Write('#endif // SHAKA_EMBEDDED_%s_H_', name.upper())
def _GeneratePublicSource(results, f, public_header, internal_header):
"""Generates the source for the public C++ type."""
other_types = [t.name for t in results.types]
writer = embed_utils.CodeWriter(f)
writer.Write('#include "%s"', public_header)
writer.Write()
writer.Write('#include "%s"', internal_header)
writer.Write()
with writer.Namespace('shaka'):
for t in results.types:
with writer.Block('class %s::Impl' % t.name, semicolon=True):
writer.Write('public:', offset=-1)
writer.Write('const js::%s value;', t.name)
writer.Write()
writer.Write('%s::%s() : impl_(new Impl) {}', t.name, t.name)
writer.Write(
'%s::%s(const js::%s& internal) : impl_(new Impl{internal}) {}',
t.name, t.name, t.name)
writer.Write('%s::%s(const %s&) = default;', t.name, t.name, t.name)
writer.Write('%s::%s(%s&&) = default;', t.name, t.name, t.name)
writer.Write('%s::~%s() {}', t.name, t.name)
writer.Write()
writer.Write('%s& %s::operator=(const %s&) = default;', t.name, t.name,
t.name)
writer.Write('%s& %s::operator=(%s&&) = default;', t.name, t.name, t.name)
writer.Write()
for attr in t.attributes:
with writer.Block('%s %s::%s() const' %
(_MapCppType(attr.type, other_types, is_public=True),
t.name, _GetPublicFieldName(attr))):
if attr.type.name == 'sequence':
writer.Write(
'return {impl_->value.%s.begin(), impl_->value.%s.end()};',
attr.name, attr.name)
else:
writer.Write('return impl_->value.%s;', attr.name)
writer.Write()
writer.Write()
with writer.Block('const js::%s& %s::GetInternal() const' %
(t.name, t.name)):
writer.Write('return impl_->value;')
writer.Write()
writer.Write()
def _GenerateObjcHeader(results, f, name):
"""Generates the header for the public Objective-C type."""
other_types = [t.name for t in results.types]
writer = embed_utils.CodeWriter(f)
writer.Write('#ifndef SHAKA_EMBEDDED_OBJC_%s_H_', name.upper())
writer.Write('#define SHAKA_EMBEDDED_OBJC_%s_H_', name.upper())
writer.Write()
writer.Write('#import <Foundation/Foundation.h>')
writer.Write()
writer.Write('#include "macros.h"')
writer.Write()
for t in results.types:
if t.doc:
writer.Write(_FormatDoc(t, indent=0))
writer.Write('SHAKA_EXPORT')
writer.Write('@interface Shaka%s : NSObject', t.name)
writer.Write()
for attr in t.attributes:
if attr.doc:
writer.Write(_FormatDoc(attr, indent=0))
writer.Write('@property (atomic, readonly) %s %s;',
_MapObjcType(attr.type, other_types), _GetObjcName(attr))
writer.Write()
writer.Write('@end')
writer.Write()
writer.Write()
writer.Write('#endif // SHAKA_EMBEDDED_OBJC_%s_H_', name.upper())
def _GenerateObjcSource(results, f, header, objc_internal_header):
"""Generates the source for the public Objective-C type."""
other_types = [t.name for t in results.types]
writer = embed_utils.CodeWriter(f)
writer.Write('#import "%s"', header)
writer.Write('#import "%s"', objc_internal_header)
writer.Write('#import "src/util/objc_utils.h"')
writer.Write()
for t in results.types:
writer.Write('@implementation Shaka%s', t.name)
writer.Write()
with writer.Block(
'- (instancetype)initWithCpp:(const shaka::%s&)obj' % t.name):
with writer.Block('if ((self = [super init]))'):
writer.Write('self->value = obj;')
writer.Write('return self;')
writer.Write()
with writer.Block('- (const shaka::%s&)toCpp' % t.name):
writer.Write('return self->value;')
writer.Write()
for attr in t.attributes:
with writer.Block('- (%s)%s' %
(_MapObjcType(attr.type, other_types),
_GetObjcName(attr))):
writer.Write(
'return shaka::util::ObjcConverter<%s>::ToObjc(self->value.%s());',
_MapCppType(attr.type, other_types, is_public=True),
_GetPublicFieldName(attr))
writer.Write()
writer.Write('@end')
writer.Write()
writer.Write()
def _GenerateObjcInternalHeader(results, f, name, public_header, objc_header):
"""Generates the header for the internal Objective-C type."""
writer = embed_utils.CodeWriter(f)
writer.Write('#ifndef SHAKA_EMBEDDED_OBJC_%s_INTERNAL_H_', name.upper())
writer.Write('#define SHAKA_EMBEDDED_OBJC_%s_INTERNAL_H_', name.upper())
writer.Write()
writer.Write('#import "%s"', objc_header)
writer.Write('#include "%s"', public_header)
writer.Write('#include "src/util/objc_utils.h"')
writer.Write()
for t in results.types:
with writer.Block('@interface Shaka%s()' % t.name):
writer.Write('shaka::%s value;', t.name)
writer.Write()
writer.Write('- (instancetype)initWithCpp:(const shaka::%s&)obj;', t.name)
writer.Write()
writer.Write('- (const shaka::%s&)toCpp;', t.name)
writer.Write()
writer.Write('@end')
writer.Write()
writer.Write('template <>')
with writer.Block('struct shaka::util::ObjcConverter<shaka::%s>' % t.name,
semicolon=True):
with writer.Block('static Shaka%s* ToObjc(const shaka::%s& val)' %
(t.name, t.name)):
writer.Write('return [[Shaka%s alloc] initWithCpp:val];', t.name)
writer.Write()
writer.Write()
writer.Write()
writer.Write('#endif // SHAKA_EMBEDDED_OBJC_%s_INTERNAL_H_', name.upper())
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--internal-dir', dest='internal', required=True,
help='The directory to output internal files to.')
parser.add_argument('--internal-rel-dir', dest='internal_rel', required=True,
help='The relative path for the internal directory, '
'used for #include.')
parser.add_argument('--public-dir', dest='public', required=True,
help='The directory to output public files to.')
parser.add_argument('input', help='The IDL file to parse.')
ns = parser.parse_args(args)
with open(ns.input, 'r') as f:
# Only allow dictionaries without required fields or defaults.
opts = webidl.Options('dictionary')
results = webidl.ParseFile(ns.input, f.read(), options=opts)
if not os.path.exists(ns.internal):
os.makedirs(ns.internal)
# Remove the 'shaka/' prefix.
internal_rel = ns.internal_rel[ns.internal_rel.index('/')+1:]
name = os.path.splitext(os.path.basename(ns.input))[0]
public_header = 'shaka/%s.h' % name
internal_header = '%s/%s.h' % (internal_rel, name)
objc_internal_header = '%s/%s+Internal.h' % (internal_rel, name)
with open(os.path.join(ns.internal, name + '.h'), 'w+') as f:
_GenerateJsHeader(results, f, name, public_header)
with open(os.path.join(ns.internal, name + '_js.cc'), 'w+') as f:
_GenerateJsSource(results, f, internal_header)
with open(os.path.join(ns.public, name + '.h'), 'w+') as f:
_GeneratePublicHeader(results, f, name)
with open(os.path.join(ns.public, name + '.cc'), 'w+') as f:
_GeneratePublicSource(results, f, public_header, internal_header)
with open(os.path.join(ns.public, name + '_objc.h'), 'w+') as f:
_GenerateObjcHeader(results, f, name)
with open(os.path.join(ns.public, name + '_objc.mm'), 'w+') as f:
_GenerateObjcSource(results, f, name + '_objc.h', objc_internal_header)
with open(os.path.join(ns.internal, name + '+Internal.h'), 'w+') as f:
_GenerateObjcInternalHeader(results, f, name, public_header,
'shaka/%s_objc.h' % name)
if __name__ == '__main__':
main(sys.argv[1:])
<file_sep>/shaka/src/public/vtt_cue_public.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "shaka/vtt_cue.h"
#include <cmath>
namespace shaka {
VTTCue::VTTCue(double start_time, double end_time, const std::string& text)
: start_time_(start_time),
end_time_(end_time),
pause_on_exit_(false),
vertical_(DirectionSetting::Horizontal),
snap_to_lines_(true),
line_(NAN),
line_align_(LineAlignSetting::Start),
position_(NAN),
position_align_(PositionAlignSetting::Auto),
size_(100),
align_(AlignSetting::Center),
text_(text) {}
VTTCue::VTTCue(const VTTCue& cue)
: id_(cue.id_),
start_time_(cue.start_time_),
end_time_(cue.end_time_),
pause_on_exit_(cue.pause_on_exit_),
vertical_(cue.vertical_),
snap_to_lines_(cue.snap_to_lines_),
line_(cue.line_),
line_align_(cue.line_align_),
position_(cue.position_),
position_align_(cue.position_align_),
size_(cue.size_),
align_(cue.align_),
text_(cue.text_) {}
VTTCue::VTTCue(VTTCue&& cue)
: id_(std::move(cue.id_)),
start_time_(cue.start_time_),
end_time_(cue.end_time_),
pause_on_exit_(cue.pause_on_exit_),
vertical_(cue.vertical_),
snap_to_lines_(cue.snap_to_lines_),
line_(cue.line_),
line_align_(cue.line_align_),
position_(cue.position_),
position_align_(cue.position_align_),
size_(cue.size_),
align_(cue.align_),
text_(std::move(cue.text_)) {}
VTTCue::~VTTCue() {}
VTTCue& VTTCue::operator=(const VTTCue& cue) {
*this = VTTCue(cue); // Use move-assignment and copy-constructor.
return *this;
}
VTTCue& VTTCue::operator=(VTTCue&& cue) {
id_ = std::move(cue.id_);
start_time_ = cue.start_time_;
end_time_ = cue.end_time_;
pause_on_exit_ = cue.pause_on_exit_;
vertical_ = cue.vertical_;
snap_to_lines_ = cue.snap_to_lines_;
line_ = cue.line_;
line_align_ = cue.line_align_;
position_ = cue.position_;
position_align_ = cue.position_align_;
size_ = cue.size_;
align_ = cue.align_;
text_ = std::move(cue.text_);
return *this;
}
std::string VTTCue::id() const {
std::unique_lock<std::mutex> lock(mutex_);
return id_;
}
void VTTCue::SetId(const std::string& id) {
std::unique_lock<std::mutex> lock(mutex_);
id_ = id;
}
double VTTCue::startTime() const {
std::unique_lock<std::mutex> lock(mutex_);
return start_time_;
}
void VTTCue::SetStartTime(double time) {
std::unique_lock<std::mutex> lock(mutex_);
start_time_ = time;
}
double VTTCue::endTime() const {
std::unique_lock<std::mutex> lock(mutex_);
return end_time_;
}
void VTTCue::SetEndTime(double time) {
std::unique_lock<std::mutex> lock(mutex_);
end_time_ = time;
}
bool VTTCue::pauseOnExit() const {
std::unique_lock<std::mutex> lock(mutex_);
return pause_on_exit_;
}
void VTTCue::SetPauseOnExit(bool pause) {
std::unique_lock<std::mutex> lock(mutex_);
pause_on_exit_ = pause;
}
DirectionSetting VTTCue::vertical() const {
std::unique_lock<std::mutex> lock(mutex_);
return vertical_;
}
void VTTCue::SetVertical(DirectionSetting setting) {
std::unique_lock<std::mutex> lock(mutex_);
vertical_ = setting;
}
bool VTTCue::snapToLines() const {
std::unique_lock<std::mutex> lock(mutex_);
return snap_to_lines_;
}
void VTTCue::SetSnapToLines(bool snap) {
std::unique_lock<std::mutex> lock(mutex_);
snap_to_lines_ = snap;
}
LineAlignSetting VTTCue::lineAlign() const {
std::unique_lock<std::mutex> lock(mutex_);
return line_align_;
}
void VTTCue::SetLineAlign(LineAlignSetting align) {
std::unique_lock<std::mutex> lock(mutex_);
line_align_ = align;
}
double VTTCue::line() const {
std::unique_lock<std::mutex> lock(mutex_);
return line_;
}
void VTTCue::SetLine(double line) {
std::unique_lock<std::mutex> lock(mutex_);
line_ = line;
}
double VTTCue::position() const {
std::unique_lock<std::mutex> lock(mutex_);
return position_;
}
void VTTCue::SetPosition(double position) {
std::unique_lock<std::mutex> lock(mutex_);
position_ = position;
}
PositionAlignSetting VTTCue::positionAlign() const {
std::unique_lock<std::mutex> lock(mutex_);
return position_align_;
}
void VTTCue::SetPositionAlign(PositionAlignSetting align) {
std::unique_lock<std::mutex> lock(mutex_);
position_align_ = align;
}
double VTTCue::size() const {
std::unique_lock<std::mutex> lock(mutex_);
return size_;
}
void VTTCue::SetSize(double size) {
std::unique_lock<std::mutex> lock(mutex_);
size_ = size;
}
AlignSetting VTTCue::align() const {
std::unique_lock<std::mutex> lock(mutex_);
return align_;
}
void VTTCue::SetAlign(AlignSetting align) {
std::unique_lock<std::mutex> lock(mutex_);
align_ = align;
}
std::string VTTCue::text() const {
std::unique_lock<std::mutex> lock(mutex_);
return text_;
}
void VTTCue::SetText(const std::string& text) {
std::unique_lock<std::mutex> lock(mutex_);
text_ = text;
}
} // namespace shaka
<file_sep>/shaka/src/js/vtt_cue.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_VTT_CUE_H_
#define SHAKA_EMBEDDED_JS_VTT_CUE_H_
#include <string>
#include "shaka/variant.h"
#include "shaka/vtt_cue.h"
#include "src/mapping/backing_object.h"
#include "src/mapping/backing_object_factory.h"
#include "src/mapping/enum.h"
namespace shaka {
namespace js {
enum class AutoKeyword {
Auto,
};
class VTTCue : public BackingObject, public shaka::VTTCue {
DECLARE_TYPE_INFO(VTTCue);
public:
VTTCue(double start_time, double end_time, const std::string& text);
explicit VTTCue(const shaka::VTTCue& pub);
static VTTCue* Create(double start, double end, const std::string& text) {
return new VTTCue(start, end, text);
}
variant<double, AutoKeyword> PositionJs() const;
void SetPositionJs(variant<double, AutoKeyword> value);
variant<double, AutoKeyword> LineJs() const;
void SetLineJs(variant<double, AutoKeyword> value);
};
class VTTCueFactory : public BackingObjectFactory<VTTCue> {
public:
VTTCueFactory();
};
} // namespace js
} // namespace shaka
DEFINE_ENUM_MAPPING(shaka::js, AutoKeyword) {
AddMapping(Enum::Auto, "auto");
}
DEFINE_ENUM_MAPPING(shaka, DirectionSetting) {
AddMapping(Enum::Horizontal, "");
AddMapping(Enum::LeftToRight, "lr");
AddMapping(Enum::RightToLeft, "rl");
}
DEFINE_ENUM_MAPPING(shaka, LineAlignSetting) {
AddMapping(Enum::Start, "start");
AddMapping(Enum::Center, "center");
AddMapping(Enum::End, "end");
}
DEFINE_ENUM_MAPPING(shaka, PositionAlignSetting) {
AddMapping(Enum::LineLeft, "line-left");
AddMapping(Enum::Center, "center");
AddMapping(Enum::LineRight, "line-right");
AddMapping(Enum::Auto, "auto");
}
DEFINE_ENUM_MAPPING(shaka, AlignSetting) {
AddMapping(Enum::Start, "start");
AddMapping(Enum::Center, "center");
AddMapping(Enum::End, "end");
AddMapping(Enum::Left, "left");
AddMapping(Enum::Right, "right");
}
#endif // SHAKA_EMBEDDED_JS_VTT_CUE_H_
<file_sep>/shaka/src/media/ffmpeg_decoded_frame.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/ffmpeg_decoded_frame.h"
namespace shaka {
namespace media {
FFmpegDecodedFrame::FFmpegDecodedFrame(AVFrame* frame, double pts, double dts,
double duration)
: BaseFrame(pts, dts, duration, true), frame_(frame) {}
FFmpegDecodedFrame::~FFmpegDecodedFrame() {
av_frame_unref(frame_);
av_frame_free(&frame_);
}
// static
FFmpegDecodedFrame* FFmpegDecodedFrame::CreateFrame(AVFrame* frame, double time,
double duration) {
// TODO(modmaker): Add an AVFrame pool to reuse objects.
AVFrame* copy = av_frame_clone(frame);
if (!copy)
return nullptr;
return new (std::nothrow) FFmpegDecodedFrame(copy, time, time, duration);
}
uint8_t** FFmpegDecodedFrame::data() const {
return frame_->data;
}
int* FFmpegDecodedFrame::linesize() const {
return frame_->linesize;
}
FrameType FFmpegDecodedFrame::frame_type() const {
return FrameType::FFmpegDecodedFrame;
}
size_t FFmpegDecodedFrame::EstimateSize() const {
size_t size = sizeof(*this) + sizeof(*frame_);
for (int i = AV_NUM_DATA_POINTERS; i; i--) {
if (frame_->buf[i - 1])
size += frame_->buf[i - 1]->size;
}
for (int i = frame_->nb_extended_buf; i; i--)
size += frame_->extended_buf[i - 1]->size;
for (int i = frame_->nb_side_data; i; i--)
size += frame_->side_data[i - 1]->size;
return size;
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/test/src/media/pipeline_manager_unittest.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/pipeline_manager.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "src/util/clock.h"
namespace shaka {
namespace media {
namespace {
using namespace std::placeholders; // NOLINT
using testing::_;
using testing::InSequence;
using testing::MockFunction;
using testing::NiceMock;
using testing::Return;
class MockClock : public util::Clock {
public:
MOCK_CONST_METHOD0(GetMonotonicTime, uint64_t());
MOCK_CONST_METHOD1(SleepSeconds, void(double));
};
void IgnoreSeek() {}
} // namespace
TEST(PipelineManagerTest, Initialization) {
NiceMock<MockClock> clock;
MockFunction<void(PipelineStatus)> client;
auto callback = std::bind(&decltype(client)::Call, &client, _1);
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
PipelineManager pipeline(callback, &IgnoreSeek, &clock);
EXPECT_EQ(pipeline.GetPipelineStatus(), PipelineStatus::Initializing);
pipeline.DoneInitializing();
EXPECT_EQ(pipeline.GetPipelineStatus(), PipelineStatus::Paused);
}
TEST(PipelineManagerTest, CalculatesCurrentTime) {
NiceMock<MockClock> clock;
NiceMock<MockFunction<void(PipelineStatus)>> client;
auto callback = std::bind(&decltype(client)::Call, &client, _1);
MockFunction<void(int)> task;
{
InSequence seq;
EXPECT_CALL(clock, GetMonotonicTime()).WillRepeatedly(Return(0));
EXPECT_CALL(task, Call(1)).Times(1);
EXPECT_CALL(clock, GetMonotonicTime()).WillRepeatedly(Return(2 * 1000));
EXPECT_CALL(task, Call(2)).Times(1);
EXPECT_CALL(clock, GetMonotonicTime()).WillRepeatedly(Return(3 * 1000));
EXPECT_CALL(task, Call(3)).Times(1);
EXPECT_CALL(clock, GetMonotonicTime()).WillRepeatedly(Return(7 * 1000));
EXPECT_CALL(task, Call(4)).Times(1);
EXPECT_CALL(clock, GetMonotonicTime()).WillRepeatedly(Return(9 * 1000));
EXPECT_CALL(task, Call(5)).Times(1);
EXPECT_CALL(clock, GetMonotonicTime()).WillRepeatedly(Return(12 * 1000));
EXPECT_CALL(task, Call(6)).Times(1);
EXPECT_CALL(clock, GetMonotonicTime()).WillRepeatedly(Return(13 * 1000));
}
PipelineManager pipeline(callback, &IgnoreSeek, &clock);
ASSERT_EQ(pipeline.GetPlaybackRate(), 1);
pipeline.DoneInitializing();
pipeline.Play();
pipeline.CanPlay();
EXPECT_EQ(pipeline.GetCurrentTime(), 0);
task.Call(1);
EXPECT_EQ(pipeline.GetCurrentTime(), 2);
task.Call(2);
EXPECT_EQ(pipeline.GetCurrentTime(), 3);
pipeline.Pause();
task.Call(3);
EXPECT_EQ(pipeline.GetCurrentTime(), 3);
pipeline.Play();
pipeline.CanPlay();
task.Call(4);
EXPECT_EQ(pipeline.GetCurrentTime(), 5);
task.Call(5);
pipeline.SetPlaybackRate(2);
task.Call(6);
EXPECT_EQ(pipeline.GetCurrentTime(), 10);
}
TEST(PipelineManagerTest, SeeksIfPastEndWhenSettingDuration) {
NiceMock<MockClock> clock;
MockFunction<void(PipelineStatus)> client;
auto callback = std::bind(&decltype(client)::Call, &client, _1);
MockFunction<void()> seek;
auto on_seek = std::bind(&decltype(seek)::Call, &seek);
{
InSequence seq;
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
EXPECT_CALL(seek, Call()).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::SeekingPause)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
EXPECT_CALL(seek, Call()).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::SeekingPause)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Ended)).Times(1);
}
PipelineManager pipeline(callback, on_seek, &clock);
pipeline.DoneInitializing();
pipeline.SetCurrentTime(15);
pipeline.CanPlay(); // Complete initial seek.
pipeline.SetDuration(10);
EXPECT_EQ(pipeline.GetCurrentTime(), 10);
EXPECT_EQ(pipeline.GetDuration(), 10);
pipeline.OnEnded();
EXPECT_EQ(pipeline.GetPipelineStatus(), PipelineStatus::Ended);
}
TEST(PipelineManagerTest, DoesntChangeStatusAfterErrors) {
NiceMock<MockClock> clock;
MockFunction<void(PipelineStatus)> client;
auto callback = std::bind(&decltype(client)::Call, &client, _1);
{
InSequence seq;
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Errored)).Times(1);
}
PipelineManager pipeline(callback, &IgnoreSeek, &clock);
pipeline.DoneInitializing();
pipeline.OnError();
pipeline.SetCurrentTime(15);
pipeline.CanPlay();
pipeline.OnEnded();
pipeline.Play();
EXPECT_EQ(pipeline.GetPipelineStatus(), PipelineStatus::Errored);
pipeline.Stalled();
pipeline.Pause();
EXPECT_EQ(pipeline.GetPipelineStatus(), PipelineStatus::Errored);
pipeline.OnError();
}
TEST(PipelineManagerTest, PlayPauseStall) {
NiceMock<MockClock> clock;
MockFunction<void(PipelineStatus)> client;
auto callback = std::bind(&decltype(client)::Call, &client, _1);
{
InSequence seq;
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Stalled)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Playing)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Stalled)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
}
PipelineManager pipeline(callback, &IgnoreSeek, &clock);
pipeline.DoneInitializing();
EXPECT_EQ(pipeline.GetPipelineStatus(), PipelineStatus::Paused);
pipeline.Play();
pipeline.CanPlay();
EXPECT_EQ(pipeline.GetPipelineStatus(), PipelineStatus::Playing);
pipeline.Stalled();
pipeline.Pause();
EXPECT_EQ(pipeline.GetPipelineStatus(), PipelineStatus::Paused);
}
TEST(PipelineManagerTest, PlayingSeek) {
NiceMock<MockClock> clock;
MockFunction<void(PipelineStatus)> client;
auto callback = std::bind(&decltype(client)::Call, &client, _1);
MockFunction<void()> seek;
auto on_seek = std::bind(&decltype(seek)::Call, &seek);
{
InSequence seq;
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Stalled)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Playing)).Times(1);
EXPECT_CALL(seek, Call()).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::SeekingPlay)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Playing)).Times(1);
}
PipelineManager pipeline(callback, on_seek, &clock);
pipeline.DoneInitializing();
pipeline.Play();
pipeline.CanPlay();
pipeline.SetCurrentTime(10);
pipeline.CanPlay();
}
TEST(PipelineManagerTest, PausedSeek) {
NiceMock<MockClock> clock;
MockFunction<void(PipelineStatus)> client;
auto callback = std::bind(&decltype(client)::Call, &client, _1);
MockFunction<void()> seek;
auto on_seek = std::bind(&decltype(seek)::Call, &seek);
{
InSequence seq;
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
EXPECT_CALL(seek, Call()).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::SeekingPause)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
}
PipelineManager pipeline(callback, on_seek, &clock);
pipeline.DoneInitializing();
pipeline.SetCurrentTime(10);
pipeline.CanPlay();
}
TEST(PipelineManagerTest, PlayingSeekPause) {
NiceMock<MockClock> clock;
MockFunction<void(PipelineStatus)> client;
auto callback = std::bind(&decltype(client)::Call, &client, _1);
MockFunction<void()> seek;
auto on_seek = std::bind(&decltype(seek)::Call, &seek);
{
InSequence seq;
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
EXPECT_CALL(seek, Call()).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::SeekingPause)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::SeekingPlay)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Playing)).Times(1);
}
PipelineManager pipeline(callback, on_seek, &clock);
pipeline.DoneInitializing();
pipeline.SetCurrentTime(10);
pipeline.Play();
pipeline.CanPlay();
}
TEST(PipelineManagerTest, StalledSeek) {
NiceMock<MockClock> clock;
MockFunction<void(PipelineStatus)> client;
auto callback = std::bind(&decltype(client)::Call, &client, _1);
MockFunction<void()> seek;
auto on_seek = std::bind(&decltype(seek)::Call, &seek);
{
InSequence seq;
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Stalled)).Times(1);
EXPECT_CALL(seek, Call()).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::SeekingPlay)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Playing)).Times(1);
}
PipelineManager pipeline(callback, on_seek, &clock);
pipeline.DoneInitializing();
pipeline.Play();
pipeline.SetCurrentTime(10);
pipeline.CanPlay();
}
TEST(PipelineManagerTest, SeekFiresMultipleTimes) {
NiceMock<MockClock> clock;
MockFunction<void(PipelineStatus)> client;
auto callback = std::bind(&decltype(client)::Call, &client, _1);
MockFunction<void()> seek;
auto on_seek = std::bind(&decltype(seek)::Call, &seek);
{
InSequence seq;
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
EXPECT_CALL(seek, Call()).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::SeekingPause)).Times(1);
EXPECT_CALL(seek, Call()).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::SeekingPause)).Times(1);
}
PipelineManager pipeline(callback, on_seek, &clock);
pipeline.DoneInitializing();
pipeline.SetCurrentTime(10);
pipeline.SetCurrentTime(20);
}
TEST(PipelineManagerTest, IgnoresSeeksBeforeStartup) {
NiceMock<MockClock> clock;
MockFunction<void(PipelineStatus)> client;
auto callback = std::bind(&decltype(client)::Call, &client, _1);
MockFunction<void()> seek;
auto on_seek = std::bind(&decltype(seek)::Call, &seek);
EXPECT_CALL(client, Call(_)).Times(0);
EXPECT_CALL(seek, Call()).Times(0);
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
PipelineManager pipeline(callback, on_seek, &clock);
pipeline.SetCurrentTime(50);
pipeline.DoneInitializing();
EXPECT_EQ(pipeline.GetCurrentTime(), 0);
}
TEST(PipelineManagerTest, SeekAfterEnd) {
NiceMock<MockClock> clock;
MockFunction<void(PipelineStatus)> client;
auto callback = std::bind(&decltype(client)::Call, &client, _1);
MockFunction<void()> seek;
auto on_seek = std::bind(&decltype(seek)::Call, &seek);
{
InSequence seq;
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
EXPECT_CALL(seek, Call()).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::SeekingPause)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Ended)).Times(1);
EXPECT_CALL(seek, Call()).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::SeekingPause)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
}
PipelineManager pipeline(callback, on_seek, &clock);
pipeline.SetDuration(10);
pipeline.DoneInitializing();
pipeline.SetCurrentTime(12);
EXPECT_EQ(pipeline.GetCurrentTime(), 10);
pipeline.OnEnded();
EXPECT_EQ(pipeline.GetPipelineStatus(), PipelineStatus::Ended);
pipeline.SetCurrentTime(2);
pipeline.CanPlay();
EXPECT_EQ(pipeline.GetCurrentTime(), 2);
EXPECT_EQ(pipeline.GetPipelineStatus(), PipelineStatus::Paused);
}
TEST(PipelineManagerTest, PlayAfterEnd) {
NiceMock<MockClock> clock;
MockFunction<void(PipelineStatus)> client;
auto callback = std::bind(&decltype(client)::Call, &client, _1);
MockFunction<void()> seek;
auto on_seek = std::bind(&decltype(seek)::Call, &seek);
{
InSequence seq;
EXPECT_CALL(client, Call(PipelineStatus::Paused)).Times(1);
EXPECT_CALL(seek, Call()).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::SeekingPause)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Ended)).Times(1);
EXPECT_CALL(seek, Call()).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::SeekingPlay)).Times(1);
EXPECT_CALL(client, Call(PipelineStatus::Playing)).Times(1);
}
PipelineManager pipeline(callback, on_seek, &clock);
pipeline.SetDuration(10);
pipeline.DoneInitializing();
pipeline.SetCurrentTime(12);
EXPECT_EQ(pipeline.GetCurrentTime(), 10);
pipeline.OnEnded();
EXPECT_EQ(pipeline.GetPipelineStatus(), PipelineStatus::Ended);
pipeline.Play();
pipeline.CanPlay();
EXPECT_EQ(pipeline.GetCurrentTime(), 0);
EXPECT_EQ(pipeline.GetPipelineStatus(), PipelineStatus::Playing);
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/include/shaka/optional.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_OPTIONAL_H_
#define SHAKA_EMBEDDED_OPTIONAL_H_
#include <assert.h>
#include <type_traits>
#include <utility>
namespace shaka {
// Note that we shouldn't use the C++17 type even if we are compiling with that
// version of C++. This is because Shaka Embedded is compiled using C++11 and
// will use this type. So the app should always use this type for our API.
// Otherwise using different types will cause subtle bugs.
/** @see https://en.cppreference.com/w/cpp/utility/optional/nullopt_t */
struct nullopt_t {
explicit nullopt_t(int) {}
};
extern const nullopt_t nullopt;
template <class T>
class optional;
template <class T>
struct is_optional : std::false_type {};
template <class T>
struct is_optional<optional<T>> : std::true_type {};
/**
* This is a look-alike for the std::optional type. The most common
* usages of this type have been implemented, but this is not a general
* implementation. For example, this doesn't throw exceptions and instead
* asserts.
*
* @see https://en.cppreference.com/w/cpp/utility/optional
*/
template <class T>
class optional {
public:
optional() : has_value_(false) {}
optional(nullopt_t) : has_value_(false) {}
// Avoid errors when returning |nullptr| instead of |nullopt|.
optional(std::nullptr_t) = delete;
template <class U = T, class = typename std::enable_if<
std::is_constructible<T, U&&>::value>::type>
optional(U&& value) : value_(std::forward<U>(value)), has_value_(true) {}
optional(const optional& other) : has_value_(other.has_value_) {
if (has_value_)
new (&value_) T(other.value_);
}
optional(optional&& other) : has_value_(other.has_value_) {
if (has_value_) {
new (&value_) T(std::move(other.value_));
other.reset();
}
}
template <class U>
optional(const optional<U>& other) : has_value_(other.has_value_) {
if (has_value_)
new (&value_) T(other.value_);
}
template <class U>
optional(optional<U>&& other) : has_value_(other.has_value_) {
if (has_value_) {
new (&value_) T(std::move(other.value_));
other.reset();
}
}
~optional() {
reset();
}
// This type will still accept assigning to other values but it will use the
// constructors to create a temporary first. This avoids having to create a
// bunch of overloads here.
optional& operator=(const optional& other) {
reset();
has_value_ = other.has_value_;
if (has_value_)
new (&value_) T(other.value_);
return *this;
}
optional& operator=(optional&& other) {
reset();
has_value_ = other.has_value_;
if (has_value_) {
new (&value_) T(std::move(other.value_));
other.reset();
}
return *this;
}
const T* operator->() const {
assert(has_value_);
return &value_;
}
T* operator->() {
assert(has_value_);
return &value_;
}
const T& operator*() const& {
assert(has_value_);
return value_;
}
T& operator*() & {
assert(has_value_);
return value_;
}
const T&& operator*() const&& {
assert(has_value_);
return std::move(value_);
}
T&& operator*() && {
assert(has_value_);
return std::move(value_);
}
explicit operator bool() const {
return has_value_;
}
bool has_value() const {
return has_value_;
}
const T& value() const& {
assert(has_value_);
return value_;
}
T& value() & {
assert(has_value_);
return value_;
}
const T&& value() const&& {
assert(has_value_);
return std::move(value_);
}
T&& value() && {
assert(has_value_);
return std::move(value_);
}
template <class U>
T value_or(U&& default_value) const& {
return has_value_ ? value_ : static_cast<T>(std::forward<U>(default_value));
}
template <class U>
T value_or(U&& default_value) && {
return has_value_ ? std::move(value_)
: static_cast<T>(std::forward<U>(default_value));
}
void reset() {
if (has_value_) {
value_.~T();
has_value_ = false;
}
}
template <class... Args>
T& emplace(Args&&... args) {
reset();
has_value_ = true;
new (&value_) T(std::forward<Args>(args)...);
return value_;
}
private:
template <class U>
friend class optional;
union {
T value_;
void* dummy_;
};
bool has_value_;
};
// Note that "no value" < "has value" for any value.
// See https://en.cppreference.com/w/cpp/utility/optional/operator_cmp
template <class A, class B>
bool operator==(const optional<A>& lhs, const optional<B>& rhs) {
if (!lhs.has_value() || !rhs.has_value())
return lhs.has_value() == rhs.has_value();
else
return lhs.value() == rhs.value();
}
template <class A, class B>
bool operator!=(const optional<A>& lhs, const optional<B>& rhs) {
return !(lhs == rhs);
}
template <class A, class B>
bool operator<(const optional<A>& lhs, const optional<B>& rhs) {
if (!lhs.has_value() || !rhs.has_value())
return rhs.has_value();
else
return lhs.value() == rhs.value();
}
template <class A, class B>
bool operator<=(const optional<A>& lhs, const optional<B>& rhs) {
return lhs < rhs || lhs == rhs;
}
template <class A, class B>
bool operator>(const optional<A>& lhs, const optional<B>& rhs) {
return rhs < lhs;
}
template <class A, class B>
bool operator>=(const optional<A>& lhs, const optional<B>& rhs) {
return rhs < lhs || lhs == rhs;
}
template <class T>
bool operator==(const optional<T>& opt, nullopt_t) {
return !opt; // 7
}
template <class T>
bool operator==(nullopt_t, const optional<T>& opt) {
return !opt; // 8
}
template <class T>
bool operator!=(const optional<T>& opt, nullopt_t) {
return bool(opt); // 9
}
template <class T>
bool operator!=(nullopt_t, const optional<T>& opt) {
return bool(opt); // 10
}
template <class T>
bool operator<(const optional<T>& opt, nullopt_t) {
return false; // 11
}
template <class T>
bool operator<(nullopt_t, const optional<T>& opt) {
return bool(opt); // 12
}
template <class T>
bool operator<=(const optional<T>& opt, nullopt_t) {
return !opt; // 13
}
template <class T>
bool operator<=(nullopt_t, const optional<T>& opt) {
return true; // 14
}
template <class T>
bool operator>(const optional<T>& opt, nullopt_t) {
return bool(opt); // 15
}
template <class T>
bool operator>(nullopt_t, const optional<T>& opt) {
return false; // 16
}
template <class T>
bool operator>=(const optional<T>& opt, nullopt_t) {
return true; // 17
}
template <class T>
bool operator>=(nullopt_t, const optional<T>& opt) {
return !opt; // 18
}
template <class A, class B>
bool operator==(const optional<A>& opt, const B& value) {
return bool(opt) ? *opt == value : false; // 19
}
template <class A, class B>
bool operator==(const A& value, const optional<B>& opt) {
return bool(opt) ? value == *opt : false; // 20
}
template <class A, class B>
bool operator!=(const optional<A>& opt, const B& value) {
return bool(opt) ? *opt != value : true; // 21
}
template <class A, class B>
bool operator!=(const A& value, const optional<B>& opt) {
return bool(opt) ? value == *opt : true; // 22
}
template <class A, class B>
bool operator<(const optional<A>& opt, const B& value) {
return bool(opt) ? *opt < value : true; // 23
}
template <class A, class B>
bool operator<(const A& value, const optional<B>& opt) {
return bool(opt) ? value < *opt : false; // 24
}
template <class A, class B>
bool operator<=(const optional<A>& opt, const B& value) {
return bool(opt) ? *opt <= value : true; // 25
}
template <class A, class B>
bool operator<=(const A& value, const optional<B>& opt) {
return bool(opt) ? value <= *opt : false; // 26
}
template <class A, class B>
bool operator>(const optional<A>& opt, const B& value) {
return bool(opt) ? *opt > value : false; // 27
}
template <class A, class B>
bool operator>(const A& value, const optional<B>& opt) {
return bool(opt) ? value > *opt : true; // 28
}
template <class A, class B>
bool operator>=(const optional<A>& opt, const B& value) {
return bool(opt) ? *opt >= value : false; // 29
}
template <class A, class B>
bool operator>=(const A& value, const optional<B>& opt) {
return bool(opt) ? value >= *opt : true; // 30
}
} // namespace shaka
#endif // SHAKA_EMBEDDED_OPTIONAL_H_
<file_sep>/shaka/tools/presubmit.py
#!/usr/bin/python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Verifies changes conform to project requirements."""
import argparse
import logging
import os
import re
import subprocess
import sys
import clang_tidy
import utils
TOOLS_DIR = os.path.dirname(os.path.realpath(__file__))
ROOT_DIR = os.path.join(TOOLS_DIR, '..', '..')
_LICENSE = r"""(##?|//) Copyright 20\d\d Google LLC
\1
\1 Licensed under the Apache License, Version 2.0 \(the "License"\);
\1 you may not use this file except in compliance with the License.
\1 You may obtain a copy of the License at
\1
\1 https://www.apache.org/licenses/LICENSE-2.0
\1
\1 Unless required by applicable law or agreed to in writing, software
\1 distributed under the License is distributed on an "AS IS" BASIS,
\1 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\1 See the License for the specific language governing permissions and
\1 limitations under the License.
"""
_STEPS = []
def _Check(func):
"""A decorator for a presubmit check."""
_STEPS.append(func)
return func
def _GetBinary(bin_name, parsed_args):
"""Returns the binary path for the given program."""
attr_name = bin_name.replace('-', '_')
if getattr(parsed_args, attr_name):
return getattr(parsed_args, attr_name)
elif utils.ExistsOnPath(bin_name):
return bin_name
elif utils.ExistsOnPath(bin_name + '.exe'):
return 'clang-tidy.exe'
elif parsed_args.force:
logging.error('Unable to find %s binary on PATH', bin_name)
return None
else:
logging.warn("Skipping %s test since we can't find it", bin_name)
return None
@_Check
def _CheckLicense(_):
# TODO: Fix license errors.
logging.info('Checking license headers for files...')
ignore_files = [
'.clang-format',
'.gitignore',
'.gitmodules',
'LICENSE',
'sample_xcode_project/LICENSE',
'shaka/js/shaka-player.compiled.js',
'shaka/js/shaka-player.compiled.debug.js',
]
ignore_extensions = [
'.json',
'.md',
'.mp4',
'.patch',
'.pbxproj',
'.plist',
'.png',
'.jpg',
'.txt',
'.storyboard',
'.webm',
'.xml',
]
log = subprocess.check_output(['git', '-C', ROOT_DIR, 'ls-files'])
has_bad_license = False
for path in log.strip().split('\n'):
full_path = os.path.join(ROOT_DIR, path)
if (path.startswith('third_party') or path in ignore_files or
os.path.splitext(path)[1] in ignore_extensions or
not os.path.isfile(full_path)):
continue
with open(full_path, 'r') as f:
text = f.read()
match = re.match('#!(/usr/bin/python|/bin/bash)\n', text)
if match:
text = text[match.end(0):]
if not re.match(_LICENSE, text):
if not has_bad_license:
logging.error('File(s) have invalid license header:')
has_bad_license = True
logging.error(' %s', path)
return 1 if has_bad_license else 0
@_Check
def _CheckCppLint(_):
logging.info('Checking cpplint...')
utils.LoadSubmodule('third_party/styleguide/src')
files = []
for root, _, cur_files in os.walk(os.path.join(ROOT_DIR, 'shaka', 'src')):
files += [os.path.join(root, f) for f in cur_files
if f.endswith('.cc') or f.endswith('.h')]
lint = os.path.join(
ROOT_DIR, 'third_party', 'styleguide', 'src', 'cpplint', 'cpplint.py')
ignored_checks = [
# cpplint doesn't calculate the correct header guard value.
'build/header_guard',
# We allow other C++11 headers.
'build/c++11',
# We use NOLINT directives that cpplint doesn't recognize.
'readability/nolint',
# We don't have owners on all our TODOs.
'readability/todo',
]
filter_ = '--filter=-' + ',-'.join(ignored_checks)
# Filter out stdout so we only print the errors.
with open(os.devnull, 'w') as f:
return subprocess.call([lint, filter_] + files, stdout=f)
@_Check
def _CheckClangTidy(parsed_args):
logging.info('Checking clang-tidy...')
exe = _GetBinary('clang-tidy', parsed_args)
if not exe:
return 1 if parsed_args.force else 0
utils.CheckConfigName(parsed_args.config)
build_dir = utils.ConfigPath(parsed_args.config)
return clang_tidy.RunClangTidy(build_dir, exe, parsed_args.fix)
@_Check
def _CheckClangFormat(parsed_args):
logging.info('Checking clang-format...')
exe = _GetBinary('clang-format', parsed_args)
if not exe:
return 1 if parsed_args.force else 0
files = []
for d in ['demo', 'include', 'src', 'test']:
files += utils.GetSourceFiles(os.path.join(ROOT_DIR, 'shaka', d))
if parsed_args.fix:
# Just run clang-format with -i to edit the files.
return subprocess.call([exe, '-i'] + files, cwd=ROOT_DIR)
# Run clang-format on each file and detect if it made any changes to the file.
has_bad_format = False
for path in files:
result = subprocess.check_output([exe, path], cwd=ROOT_DIR)
with open(path, 'r') as f:
if f.read() != result:
if not has_bad_format:
has_bad_format = True
logging.error('File(s) have invalid formatting:')
logging.error(' %s', os.path.relpath(path, ROOT_DIR))
return 1 if has_bad_format else 0
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'--config-name', dest='config',
help='Do a special in-tree build with this configuration name.')
parser.add_argument('--fix', action='store_true',
help='Automatically apply fixes to issues.')
parser.add_argument('--clang-tidy',
help='Use the given binary for clang-tidy.')
parser.add_argument('--clang-format',
help='Use the given binary for clang-format.')
parser.add_argument('--force', action='store_true',
help="Fail checks if required tools can't be found")
ns = parser.parse_args(args)
for func in _STEPS:
if func(ns) != 0:
return 1
return 0
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
sys.exit(main(sys.argv[1:]))
<file_sep>/shaka/src/media/pipeline_manager.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/pipeline_manager.h"
#include <algorithm>
#include <cmath>
#include <utility>
#include "src/util/utils.h"
namespace shaka {
namespace media {
PipelineManager::PipelineManager(
std::function<void(PipelineStatus)> on_status_changed,
std::function<void()> on_seek, const util::Clock* clock)
: mutex_("PipelineManager"),
on_status_changed_(std::move(on_status_changed)),
on_seek_(std::move(on_seek)),
clock_(clock),
status_(PipelineStatus::Initializing),
prev_media_time_(0),
prev_wall_time_(clock->GetMonotonicTime()),
playback_rate_(1),
duration_(NAN),
autoplay_(false) {}
PipelineManager::~PipelineManager() {}
void PipelineManager::DoneInitializing() {
PipelineStatus new_status;
{
std::unique_lock<SharedMutex> lock(mutex_);
if (status_ == PipelineStatus::Errored)
return;
DCHECK_EQ(status_, PipelineStatus::Initializing);
if (autoplay_) {
new_status = status_ = PipelineStatus::Stalled;
} else {
new_status = status_ = PipelineStatus::Paused;
}
}
on_status_changed_(new_status);
}
PipelineStatus PipelineManager::GetPipelineStatus() const {
util::shared_lock<SharedMutex> lock(mutex_);
return status_;
}
double PipelineManager::GetDuration() const {
util::shared_lock<SharedMutex> lock(mutex_);
return duration_;
}
void PipelineManager::SetDuration(double duration) {
PipelineStatus new_status = PipelineStatus::Initializing;
{
std::unique_lock<SharedMutex> lock(mutex_);
duration_ = duration;
// Seek to duration if current time is past the new duration.
const uint64_t wall_time = clock_->GetMonotonicTime();
if (!std::isnan(duration) && GetTimeFor(wall_time) > duration) {
{
util::Unlocker<SharedMutex> unlock(&lock);
on_seek_();
}
prev_media_time_ = duration;
prev_wall_time_ = wall_time;
if (status_ == PipelineStatus::Playing ||
status_ == PipelineStatus::Stalled) {
new_status = status_ = PipelineStatus::SeekingPlay;
} else if (status_ == PipelineStatus::Paused ||
status_ == PipelineStatus::Ended) {
new_status = status_ = PipelineStatus::SeekingPause;
}
}
}
if (new_status != PipelineStatus::Initializing)
on_status_changed_(new_status);
}
double PipelineManager::GetCurrentTime() const {
util::shared_lock<SharedMutex> lock(mutex_);
return GetTimeFor(clock_->GetMonotonicTime());
}
void PipelineManager::SetCurrentTime(double time) {
PipelineStatus new_status = PipelineStatus::Initializing;
{
std::unique_lock<SharedMutex> lock(mutex_);
if (status_ != PipelineStatus::Initializing &&
status_ != PipelineStatus::Errored) {
{
util::Unlocker<SharedMutex> unlock(&lock);
on_seek_();
}
prev_media_time_ =
std::isnan(duration_) ? time : std::min(duration_, time);
prev_wall_time_ = clock_->GetMonotonicTime();
switch (status_) {
case PipelineStatus::Playing:
case PipelineStatus::Stalled:
case PipelineStatus::SeekingPlay:
new_status = status_ = PipelineStatus::SeekingPlay;
break;
case PipelineStatus::Paused:
case PipelineStatus::Ended:
case PipelineStatus::SeekingPause:
new_status = status_ = PipelineStatus::SeekingPause;
break;
default: // Ignore remaining enum values.
break;
}
}
}
if (new_status != PipelineStatus::Initializing)
on_status_changed_(new_status);
}
double PipelineManager::GetPlaybackRate() const {
util::shared_lock<SharedMutex> lock(mutex_);
return playback_rate_;
}
void PipelineManager::SetPlaybackRate(double rate) {
std::unique_lock<SharedMutex> lock(mutex_);
SyncPoint();
playback_rate_ = rate;
}
void PipelineManager::Play() {
PipelineStatus new_status = PipelineStatus::Initializing;
{
std::unique_lock<SharedMutex> lock(mutex_);
SyncPoint();
if (status_ == PipelineStatus::Paused) {
// Assume we are stalled; we will transition to Playing quickly if not.
new_status = status_ = PipelineStatus::Stalled;
} else if (status_ == PipelineStatus::Ended) {
{
util::Unlocker<SharedMutex> unlock(&lock);
on_seek_();
}
prev_media_time_ = 0;
new_status = status_ = PipelineStatus::SeekingPlay;
} else if (status_ == PipelineStatus::SeekingPause) {
new_status = status_ = PipelineStatus::SeekingPlay;
} else if (status_ == PipelineStatus::Initializing) {
autoplay_ = true;
}
}
if (new_status != PipelineStatus::Initializing)
on_status_changed_(new_status);
}
void PipelineManager::Pause() {
PipelineStatus new_status = PipelineStatus::Initializing;
{
std::unique_lock<SharedMutex> lock(mutex_);
SyncPoint();
if (status_ == PipelineStatus::Playing ||
status_ == PipelineStatus::Stalled) {
new_status = status_ = PipelineStatus::Paused;
} else if (status_ == PipelineStatus::SeekingPlay) {
new_status = status_ = PipelineStatus::SeekingPause;
} else if (status_ == PipelineStatus::Initializing) {
autoplay_ = false;
}
}
if (new_status != PipelineStatus::Initializing)
on_status_changed_(new_status);
}
void PipelineManager::Stalled() {
bool status_changed = false;
{
std::unique_lock<SharedMutex> lock(mutex_);
if (status_ == PipelineStatus::Playing) {
SyncPoint();
status_ = PipelineStatus::Stalled;
status_changed = true;
}
}
if (status_changed)
on_status_changed_(PipelineStatus::Stalled);
}
void PipelineManager::CanPlay() {
PipelineStatus new_status = PipelineStatus::Initializing;
{
std::unique_lock<SharedMutex> lock(mutex_);
SyncPoint();
if (status_ == PipelineStatus::Stalled ||
status_ == PipelineStatus::SeekingPlay) {
new_status = status_ = PipelineStatus::Playing;
} else if (status_ == PipelineStatus::SeekingPause) {
new_status = status_ = PipelineStatus::Paused;
}
}
if (new_status != PipelineStatus::Initializing)
on_status_changed_(new_status);
}
void PipelineManager::OnEnded() {
PipelineStatus new_status = PipelineStatus::Initializing;
{
std::unique_lock<SharedMutex> lock(mutex_);
if (status_ != PipelineStatus::Ended &&
status_ != PipelineStatus::Errored) {
const uint64_t wall_time = clock_->GetMonotonicTime();
DCHECK(!std::isnan(duration_));
prev_wall_time_ = wall_time;
prev_media_time_ = duration_;
new_status = status_ = PipelineStatus::Ended;
}
}
if (new_status != PipelineStatus::Initializing)
on_status_changed_(new_status);
}
void PipelineManager::OnError() {
bool fire_event = false;
{
std::unique_lock<SharedMutex> lock(mutex_);
if (status_ != PipelineStatus::Errored) {
SyncPoint();
status_ = PipelineStatus::Errored;
fire_event = true;
}
}
if (fire_event)
on_status_changed_(PipelineStatus::Errored);
}
double PipelineManager::GetTimeFor(uint64_t wall_time) const {
if (status_ != PipelineStatus::Playing)
return prev_media_time_;
const uint64_t wall_diff = wall_time - prev_wall_time_;
const double time = prev_media_time_ + (wall_diff * playback_rate_ / 1000.0);
return std::isnan(duration_) ? time : std::min(duration_, time);
}
void PipelineManager::SyncPoint() {
const uint64_t wall_time = clock_->GetMonotonicTime();
prev_media_time_ = GetTimeFor(wall_time);
prev_wall_time_ = wall_time;
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/public/text_track_public.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "shaka/text_track.h"
#include "src/js/mse/text_track.h"
#include "src/js/vtt_cue.h"
#include "src/util/js_wrapper.h"
namespace shaka {
using JSTextTrack = js::mse::TextTrack;
class TextTrack::Impl : public util::JSWrapper<JSTextTrack> {
public:
explicit Impl(JSTextTrack* inner) {
this->inner = inner;
}
};
TextTrack::TextTrack(js::mse::TextTrack* inner) : impl_(new Impl(inner)) {
CHECK(inner) << "Must pass a TextTrack instance";
}
TextTrack& TextTrack::operator=(TextTrack&& other) {
std::swap(impl_, other.impl_);
return *this;
}
TextTrack::TextTrack(TextTrack&&) = default;
TextTrack::~TextTrack() {}
void TextTrack::SetCueChangeEventListener(std::function<void()> callback) {
auto task = PlainCallbackTask([=]() {
impl_->inner->SetCppEventListener(js::EventType::CueChange, callback);
});
const std::string task_name = "TextTrack SetCueChangeEventListener";
JsManagerImpl::Instance()
->MainThread()
->AddInternalTask(TaskPriority::Internal, task_name, task)
->GetValue();
}
void TextTrack::UnsetCueChangeEventListener() {
auto task = PlainCallbackTask(
[=]() { impl_->inner->UnsetCppEventListener(js::EventType::CueChange); });
const std::string task_name = "TextTrack UnsetCueChangeEventListener";
JsManagerImpl::Instance()
->MainThread()
->AddInternalTask(TaskPriority::Internal, task_name, task)
->GetValue();
}
TextTrackKind TextTrack::kind() {
return impl_->GetMemberVariable(&JSTextTrack::kind);
}
void TextTrack::SetKind(TextTrackKind kind) {
impl_->SetMemberVariable(&JSTextTrack::kind, kind);
}
std::string TextTrack::label() {
return impl_->GetMemberVariable(&JSTextTrack::label);
}
void TextTrack::SetLabel(const std::string label) {
impl_->SetMemberVariable(&JSTextTrack::label, label);
}
std::string TextTrack::language() {
return impl_->GetMemberVariable(&JSTextTrack::language);
}
void TextTrack::SetLanguage(const std::string language) {
impl_->SetMemberVariable(&JSTextTrack::language, language);
}
std::string TextTrack::id() {
return impl_->GetMemberVariable(&JSTextTrack::id);
}
void TextTrack::SetId(const std::string id) {
impl_->SetMemberVariable(&JSTextTrack::id, id);
}
TextTrackMode TextTrack::mode() {
return impl_->CallInnerMethod(&JSTextTrack::mode);
}
void TextTrack::SetMode(TextTrackMode mode) {
impl_->CallInnerMethod(&JSTextTrack::SetMode, mode);
}
std::vector<VTTCue*> TextTrack::cues() {
auto cues = impl_->GetMemberVariable(&JSTextTrack::cues);
return std::vector<VTTCue*>(cues.begin(), cues.end());
}
void TextTrack::AddCue(const VTTCue& cue) {
// Copy the cue into an inner cue.
RefPtr<js::VTTCue> inner_cue = new js::VTTCue(cue);
impl_->CallInnerMethod(&JSTextTrack::AddCue, inner_cue);
}
void TextTrack::RemoveCue(VTTCue* cue) {
// Locate cue in list.
auto cues = impl_->GetMemberVariable(&JSTextTrack::cues);
auto inner_cue_iter = std::find(cues.begin(), cues.end(), cue);
CHECK(inner_cue_iter != cues.end())
<< "Can only remove cues retrieved from cues list";
if (inner_cue_iter != cues.end()) {
RefPtr<js::VTTCue> inner_cue = *inner_cue_iter;
impl_->CallInnerMethod(&JSTextTrack::RemoveCue, inner_cue);
}
}
} // namespace shaka
<file_sep>/shaka/tools/webidl/tests/defaults_test.py
#!/usr/bin/python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
import math
import unittest
from . import test_common
from webidl import parser
from webidl import types
class DefaultsTest(test_common.TestBase):
def _parse_default(self, code):
"""Returns the parsed default."""
results = self.parser.parse('', 'dictionary F {long x = %s;};' % code)
self.assertEqual(1, len(results.types))
self.assertEqual(1, len(results.types[0].attributes))
self.assertEqual('x', results.types[0].attributes[0].name)
return results.types[0].attributes[0].default
def test_numbers(self):
self.assertEqual(self._parse_default('0'), 0)
self.assertEqual(self._parse_default('1234'), 1234)
self.assertEqual(self._parse_default('1.2345e12'), 1.2345e12)
self.assertEqual(self._parse_default('-999'), -999)
self.assertEqual(self._parse_default('-.901'), -.901)
self.assertEqual(self._parse_default('Infinity'), float('inf'))
self.assertEqual(self._parse_default('-Infinity'), float('-inf'))
self.assertTrue(math.isnan(self._parse_default('NaN')))
def test_boolean(self):
self.assertEqual(self._parse_default('true'), True)
self.assertEqual(self._parse_default('false'), False)
def test_null(self):
self.assertIs(self._parse_default('null'), types.IdlNull)
def test_string(self):
self.assertEqual(self._parse_default('"foo"'), 'foo')
self.assertEqual(self._parse_default('""'), '')
self.assertEqual(self._parse_default('"foo\nbar"'), 'foo\nbar')
def test_array(self):
self.assertEqual(self._parse_default('[]'), [])
def test_syntax_error(self):
bad_code = [
'',
'1.2.3',
'+1234',
'x123',
'0b123',
'0x3g2',
'--2',
'-',
'foobar',
]
for code in bad_code:
with self.assertRaises(parser.IdlSyntaxError):
self._parse_default(code)
if __name__ == '__main__':
unittest.main()
<file_sep>/shaka/tools/webidl/webidl/lexer.py
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Defines a lex tokenizer for IDL files.
This uses PLY for the basis:
http://www.dabeaz.com/ply/
This parses WebIDL syntax:
https://heycam.github.io/webidl/#idl-grammar
"""
# pylint: disable=invalid-name
from __future__ import print_function
from ply import lex
__all__ = ['IdlLexer']
class IdlLexer(object):
"""A PLY lexer that reads WebIDL syntax.
This has two special fields: tokens and literals. Other members that start
with 't_' are special and define how to parse different tokens. These
parsers are invoked in the order they are defined, so it is important that
early ones override later ones.
"""
def __init__(self):
self.lex = lex.lex(object=self, optimize=0)
self.file_name = None
self.contents = None
self.last = None
@property
def lineno(self):
try:
return self.lex.lineno
except AttributeError:
# This can be called before the |lex| value is set; ignore in this case.
return 1
@property
def lexpos(self):
try:
return self.lex.lexpos
except AttributeError:
# This can be called before the |lex| value is set; ignore in this case.
return 1
def set_contents(self, name, contents):
"""Resets the lexer to read from the given text."""
self.lex.lineno = 1
self.lex.input(contents)
self.file_name = name
self.contents = contents
self.last = None
def token(self):
ret = self.lex.token()
if ret:
self.last = ret
return ret
def get_col(self, pos):
"""Gets the column index of the given lexpos."""
return pos - self.contents.rfind('\n', 0, pos)
def get_line(self, pos):
"""Gets the line of text that is at position |pos|."""
prev = self.contents.rfind('\n', 0, pos)
nxt = self.contents.find('\n', pos)
if nxt < 0:
nxt = len(self.contents)
return self.contents[prev+1:nxt]
_keywords = (
'any',
'dictionary',
'false',
'Infinity',
'NaN',
'null',
'required',
'sequence',
'true',
'void',
'boolean',
'byte',
'double',
'float',
'long',
'short',
'octet',
'unrestricted',
'unsigned',
'ByteString',
'DOMString',
'FrozenArray',
'Promise',
'USVString',
)
literals = '.(){}[]<>,;=?-'
tokens = (
'FLOAT_LITERAL',
'INTEGER_LITERAL',
'STRING_LITERAL',
'DOCSTRING',
'IDENTIFIER',
) + tuple(k.upper() for k in _keywords)
def t_error(self, t):
msg = 'Unexpected character "%s"' % t.value[0]
line = self.get_line(t.lexpos)
col = self.get_col(t.lexpos)
raise SyntaxError(msg, (self.file_name, t.lineno, col, line))
t_ignore = ' \t'
@lex.TOKEN(r'-?(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][+-]?[0-9]+)?|'
r' [0-9]+[Ee][+-]?[0-9]+)')
def t_FLOAT_LITERAL(self, t):
t.value = float(t.value)
return t
@lex.TOKEN('-?([1-9][0-9]*|0[Xx][0-9A-Fa-f]+|0[0-7]*)')
def t_INTEGER_LITERAL(self, t):
if t.value.lower().startswith('0x') or t.value.lower().startswith('-0x'):
t.value = int(t.value, 16)
elif t.value.startswith('0') or t.value.startswith('-0'):
t.value = int(t.value, 8)
else:
t.value = int(t.value, 10)
return t
@lex.TOKEN(r'"[^"]*"')
def t_STRING_LITERAL(self, t):
t.value = t.value[1:-1]
self.lex.lineno += t.value.count('\n')
return t
@lex.TOKEN(r'\n+')
def t_newline(self, t):
self.lex.lineno += len(t.value)
@lex.TOKEN(r'/\*\*(.|\n)+?\*/')
def t_DOCSTRING(self, t):
self.lex.lineno += t.value.count('\n')
return t
@lex.TOKEN(r'(/\*(.|\n)*?\*/)|(//.*\n)')
def t_COMMENT(self, t):
self.lex.lineno += t.value.count('\n')
@lex.TOKEN(r'_?[A-Za-z][0-9A-Za-z_-]*')
def t_IDENTIFIER(self, t):
if t.value in self._keywords:
t.type = t.value.upper()
else:
t.type = 'IDENTIFIER'
return t
<file_sep>/shaka/include/shaka/eme/data.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_EME_DATA_H_
#define SHAKA_EMBEDDED_EME_DATA_H_
#include <stddef.h> // For size_t
#include <stdint.h> // For uint8_t
#include <memory>
#include "../macros.h"
namespace shaka {
class ByteBuffer;
namespace js {
namespace eme {
class MediaKeys;
class MediaKeySession;
} // namespace eme
} // namespace js
namespace eme {
/**
* Defines a wrapper around data passed into EME. This type will keep the
* backing data alive so long as this object is alive.
*
* @ingroup eme
*/
class SHAKA_EXPORT Data final {
public:
Data(const Data& other) = delete;
Data(Data&& other);
~Data();
Data& operator=(const Data& other) = delete;
Data& operator=(Data&& other);
/** @return A raw pointer to the data. */
const uint8_t* data() const;
/** @return The number of bytes in this data. */
size_t size() const;
private:
friend class ClearKeyImplementationTest;
friend class js::eme::MediaKeys;
friend class js::eme::MediaKeySession;
Data(ByteBuffer* buffer);
class Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace eme
} // namespace shaka
#endif // SHAKA_EMBEDDED_EME_DATA_H_
<file_sep>/shaka/include/shaka/ShakaPlayerEmbedded.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
// Include language-agnostic headers.
#include "config_names.h"
#include "shaka_config.h"
#include "version.h"
// Include Objective-C headers if we are compiling Objective-C or Objective-C++.
#if defined(__OBJC__)
# import "ShakaPlayerView.h"
# import "manifest_objc.h"
# import "player_externs_objc.h"
# import "stats_objc.h"
# import "track_objc.h"
#endif
// Include C++ headers if we are compiling in C++ or Objective-C++.
#ifdef __cplusplus
# include "async_results.h"
# include "error.h"
# include "frame.h"
# include "js_manager.h"
# include "manifest.h"
# include "player.h"
# include "player_externs.h"
# include "stats.h"
# ifdef SHAKA_SDL_UTILS
# include "sdl_frame_drawer.h"
# endif
# include "text_track.h"
# include "track.h"
# include "utils.h"
# include "video.h"
# include "vtt_cue.h"
# include "eme/configuration.h"
# include "eme/data.h"
# include "eme/implementation.h"
# include "eme/implementation_factory.h"
# include "eme/implementation_helper.h"
# include "eme/implementation_registry.h"
#endif
<file_sep>/shaka/src/js/dom/exception_code.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_DOM_EXCEPTION_CODE_H_
#define SHAKA_EMBEDDED_JS_DOM_EXCEPTION_CODE_H_
#include <functional> // for std::hash
namespace shaka {
enum ExceptionCode {
// General (used in multiple parts).
NotFoundError,
NotSupportedError,
InvalidStateError,
QuotaExceededError,
// DOM/XML
IndexSizeError,
HierarchyRequestError,
// IndexedDB.
DataCloneError,
UnknownError,
TransactionInactiveError,
ReadOnlyError,
VersionError,
};
} // namespace shaka
namespace std {
// Enumerations are not hashable until C++14.
template <>
struct hash<shaka::ExceptionCode> : hash<int> {};
} // namespace std
#endif // SHAKA_EMBEDDED_JS_DOM_EXCEPTION_CODE_H_
<file_sep>/shaka/include/shaka/video.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_VIDEO_H_
#define SHAKA_EMBEDDED_VIDEO_H_
#include <stdint.h>
#include <memory>
#include "frame.h"
#include "js_manager.h"
#include "macros.h"
#include "shaka_config.h"
#include "text_track.h"
namespace shaka {
namespace js {
namespace mse {
class HTMLVideoElement;
} // namespace mse
} // namespace js
/**
* This manages both a native "video" element and the JavaScript object that
* uses it. This will create a native implementation of a "video" element
* and pass it to a created JavaScript object that implements the
* HTMLVideoElement type.
*
* @ingroup player
*/
class SHAKA_EXPORT Video final {
public:
/**
* Creates a new Video instance.
* @param engine The JavaScript engine to use.
*/
Video(JsManager* engine);
Video(const Video&) = delete;
Video(Video&&);
~Video();
Video& operator=(const Video&) = delete;
Video& operator=(Video&&);
/**
* Initializes the video element. This must be called once before any other
* methods are called and before passing to Player.Initialize.
*/
void Initialize();
/**
* Draws the current video frame onto a hardware texture and returns it. This
* can be called on any thread, but cannot be called at the same time on
* multiple threads. This will create a texture using the renderer given in
* the constructor. The texture will be the same size of the video to avoid
* resizing. Resizing and adding black bars is the job of the app.
*
* @param delay [OUT] Optional, if given, will hold the delay (in seconds)
* until the next frame should be rendered.
* @return The texture holding the video frame, or an invalid frame if nothing
* is ready.
*/
Frame DrawFrame(double* delay);
/** @return The duration of the video, or 0 if nothing is loaded. */
double Duration() const;
/** @return Whether the video is currently ended. */
bool Ended() const;
/** @return Whether the video is currently seeking. */
bool Seeking() const;
/** @return Whether the video is currently paused. */
bool Paused() const;
/** @return Whether the audio is currently muted. */
bool Muted() const;
/** Sets whether the audio is muted. */
void SetMuted(bool muted);
/** @return The text tracks of the video. */
std::vector<TextTrack> TextTracks();
/** @return The current volume of the audio. */
double Volume() const;
/** Sets the audio volume. */
void SetVolume(double volume);
/** @return The current time of the video, or 0 if nothing is loaded. */
double CurrentTime() const;
/**
* Seeks to a new position in the currently-playing stream. Does nothing
* if no content is loaded.
*
* @param time The presentation time to seek to.
*/
void SetCurrentTime(double time);
/**
* @return The current playback rate of the video, or 1 if nothing is loaded.
*/
double PlaybackRate() const;
/**
* Sets the playback rate of the video. Does nothing if no content is loaded.
* @param rate The new playback rate.
*/
void SetPlaybackRate(double rate);
/** Pauses the video. */
void Pause();
/** Plays the video. */
void Play();
private:
friend class Player;
js::mse::HTMLVideoElement* GetJavaScriptObject();
class Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_VIDEO_H_
<file_sep>/test.py
#!/usr/bin/python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Runs the unit tests for the project.
"""
from __future__ import print_function
import argparse
import os
import subprocess
import sys
ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(ROOT_DIR, 'shaka', 'tools'))
import run_ios_tests
import utils
def _RunTests(build_dir, no_colors):
"""Runs the tests in the given build dir."""
tools_path = os.path.join(ROOT_DIR, 'shaka', 'tools')
if subprocess.call([sys.executable, '-m', 'unittest', 'discover',
'-s', tools_path, '-p', '*_test.py']) != 0:
return 1
webidl_path = os.path.join(ROOT_DIR, 'shaka', 'tools', 'webidl')
# Add our PLY checkout so the subprocess can find it.
env = os.environ.copy()
env['PYTHONPATH'] = (os.path.join(ROOT_DIR, 'third_party', 'ply', 'src') +
os.pathsep + env.get('PYTHONPATH', ''))
if subprocess.call([sys.executable, '-m', 'unittest', 'discover',
'-s', webidl_path, '-p', '*_test.py'], env=env) != 0:
return 1
target_os = (utils.GetGnArg(build_dir, 'target_os') or
utils.GetGnArg(build_dir, 'host_os'))
if target_os == 'ios':
return run_ios_tests.RunTests(build_dir)
else:
args = [
'--media_directory', os.path.join(ROOT_DIR, 'shaka', 'test', 'media'),
]
if no_colors:
args += ['--no_colors']
return subprocess.call([os.path.join(build_dir, 'tests')] + args)
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'--config-name', dest='config',
help='Do a special in-tree build with this configuration name.')
parser.add_argument('--no-colors', action='store_true',
help="Don't print colors in test output.")
ns = parser.parse_args(args)
config_dir = utils.ConfigPath(ns.config)
return _RunTests(config_dir, ns.no_colors)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
<file_sep>/shaka/test/src/core/ref_ptr_unittest.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/core/ref_ptr.h"
#include <gtest/gtest.h>
#include <type_traits>
#include <unordered_map>
#include "src/core/member.h"
#include "src/mapping/convert_js.h"
#include "src/mapping/js_wrappers.h"
#include "src/memory/heap_tracer.h"
#include "src/memory/object_tracker.h"
namespace shaka {
namespace {
struct Base : BackingObject {
static std::string name() {
return "Base";
}
ReturnVal<JsValue> JsThis() {
CHECK(false);
}
void Trace(memory::HeapTracer*) const override {}
BackingObjectFactoryBase* factory() const override {
return nullptr;
}
int i = 12;
std::string j = "abc";
};
struct Derived : Base {};
} // namespace
class RefPtrTest : public testing::Test {
public:
~RefPtrTest() override {
tracker_.UnregisterAllObjects();
}
protected:
uint32_t GetRefCount(memory::Traceable* object) const {
return tracker_.GetRefCount(object);
}
void ExpectEmptyTracker() {
EXPECT_EQ(0u, tracker_.GetRefCount(&base1_));
EXPECT_EQ(0u, tracker_.GetRefCount(&base2_));
EXPECT_EQ(0u, tracker_.GetRefCount(&derived_));
}
memory::ObjectTracker::UnsetForTesting unset_;
memory::ObjectTracker tracker_;
Base base1_;
Base base2_;
Derived derived_;
};
TEST_F(RefPtrTest, BasicFlow) {
{
RefPtr<Base> ptr1(&base1_);
EXPECT_EQ(1u, GetRefCount(&base1_));
EXPECT_EQ(0u, GetRefCount(&base2_));
ptr1 = &base2_;
EXPECT_EQ(0u, GetRefCount(&base1_));
EXPECT_EQ(1u, GetRefCount(&base2_));
RefPtr<Base> ptr2(&base2_);
EXPECT_EQ(0u, GetRefCount(&base1_));
EXPECT_EQ(2u, GetRefCount(&base2_));
}
ExpectEmptyTracker();
}
TEST_F(RefPtrTest, SupportsCopyAndMove) {
{
RefPtr<Base> ptr1(&base1_);
RefPtr<Base> ptr2(ptr1);
RefPtr<Base> ptr3;
EXPECT_TRUE(ptr3.empty());
ptr3 = ptr1;
EXPECT_EQ(3u, GetRefCount(&base1_));
EXPECT_EQ(0u, GetRefCount(&base2_));
EXPECT_EQ(ptr1, ptr2);
EXPECT_EQ(ptr1, ptr3);
EXPECT_FALSE(ptr2.empty());
RefPtr<Base> ptr4(std::move(ptr2));
EXPECT_TRUE(ptr2.empty());
EXPECT_FALSE(ptr4.empty());
EXPECT_EQ(3u, GetRefCount(&base1_));
EXPECT_EQ(ptr1, ptr4);
EXPECT_NE(ptr2, ptr4);
ptr2 = std::move(ptr4);
EXPECT_TRUE(ptr4.empty());
EXPECT_FALSE(ptr2.empty());
EXPECT_EQ(3u, GetRefCount(&base1_));
ptr1 = ptr2;
EXPECT_EQ(3u, GetRefCount(&base1_));
ptr1 = nullptr;
EXPECT_EQ(2u, GetRefCount(&base1_));
EXPECT_TRUE(ptr1.empty());
ptr2.reset();
EXPECT_EQ(1u, GetRefCount(&base1_));
EXPECT_TRUE(ptr2.empty());
EXPECT_FALSE(ptr3.empty());
}
ExpectEmptyTracker();
}
TEST_F(RefPtrTest, SupportsCallingMethods) {
auto VerifyMethodArguments = [this](RefPtr<Base> copy, RefPtr<Base> move) {
// Cannot use an rvalue reference for |move| because the ref count would
// not be correct. When we don't use a reference, the value will be
// move-constructed into the argument, which is why the ref count is 1.
// When the method returns, the argument is destroyed, dropping the ref
// count to 0.
//
// If we used an rvalue reference, we would pass a reference and not
// create a temporary. What makes the ref count change is the
// constructor so because no constructor is invoked, the original
// variable would remain unchanged.
EXPECT_EQ(2u, GetRefCount(copy.get()));
EXPECT_EQ(1u, GetRefCount(move.get()));
};
{
RefPtr<Base> ptr1(&base1_);
RefPtr<Base> ptr2(&base2_);
EXPECT_EQ(1u, GetRefCount(&base1_));
EXPECT_EQ(1u, GetRefCount(&base2_));
VerifyMethodArguments(ptr1, std::move(ptr2));
EXPECT_FALSE(ptr1.empty());
EXPECT_TRUE(ptr2.empty());
EXPECT_EQ(1u, GetRefCount(&base1_));
EXPECT_EQ(0u, GetRefCount(&base2_));
}
ExpectEmptyTracker();
}
TEST_F(RefPtrTest, SupportsComparisons) {
RefPtr<Base> ptr1(&base1_);
EXPECT_FALSE(ptr1.empty());
EXPECT_TRUE(ptr1 == &base1_);
EXPECT_TRUE(&base1_ == ptr1);
EXPECT_FALSE(ptr1 != &base1_);
EXPECT_FALSE(&base1_ != ptr1);
EXPECT_FALSE(ptr1 == &base2_);
EXPECT_TRUE(ptr1 != &base2_);
EXPECT_FALSE(ptr1 == &derived_);
EXPECT_TRUE(ptr1 != &derived_);
EXPECT_FALSE(ptr1 == nullptr);
EXPECT_TRUE(ptr1 != nullptr);
EXPECT_FALSE(nullptr == ptr1);
EXPECT_TRUE(nullptr != ptr1);
ptr1 = &derived_;
EXPECT_FALSE(ptr1.empty());
EXPECT_FALSE(ptr1 == &base1_);
EXPECT_TRUE(ptr1 != &base1_);
EXPECT_TRUE(ptr1 == &derived_);
EXPECT_FALSE(ptr1 != &derived_);
EXPECT_FALSE(ptr1 == nullptr);
EXPECT_TRUE(ptr1 != nullptr);
ptr1 = nullptr;
EXPECT_TRUE(ptr1.empty());
EXPECT_FALSE(ptr1 == &base1_);
EXPECT_TRUE(ptr1 != &base1_);
EXPECT_FALSE(ptr1 == &derived_);
EXPECT_TRUE(ptr1 != &derived_);
EXPECT_TRUE(ptr1 == nullptr);
EXPECT_FALSE(ptr1 != nullptr);
Member<Base> mem1(&base1_);
Member<Derived> mem2(&derived_);
ptr1 = &base1_;
EXPECT_TRUE(ptr1 == mem1);
EXPECT_TRUE(mem1 == ptr1);
EXPECT_FALSE(ptr1 == mem2);
EXPECT_FALSE(mem2 == ptr1);
EXPECT_FALSE(ptr1 != mem1);
EXPECT_FALSE(mem1 != ptr1);
EXPECT_TRUE(ptr1 != mem2);
EXPECT_TRUE(mem2 != ptr1);
}
TEST_F(RefPtrTest, InteractsWithMember) {
{
RefPtr<Base> ptr1(&base1_);
Member<Base> mem1(ptr1);
EXPECT_EQ(mem1, ptr1);
EXPECT_EQ(ptr1, mem1);
Member<Base> mem2(std::move(ptr1));
EXPECT_TRUE(ptr1.empty());
EXPECT_TRUE(mem2 == &base1_);
ptr1 = mem1;
EXPECT_FALSE(ptr1.empty());
EXPECT_EQ(ptr1, &base1_);
ptr1.reset();
ptr1 = std::move(mem1);
EXPECT_TRUE(mem1.empty());
EXPECT_FALSE(ptr1.empty());
EXPECT_EQ(ptr1, &base1_);
RefPtr<Base> ptr2(std::move(mem2));
EXPECT_TRUE(mem2.empty());
EXPECT_FALSE(ptr2.empty());
EXPECT_EQ(ptr2, &base1_);
mem2 = ptr1;
EXPECT_FALSE(mem2.empty());
EXPECT_FALSE(ptr1.empty());
EXPECT_EQ(mem2, &base1_);
Member<Derived> mem3(&derived_);
ptr1 = mem3;
EXPECT_FALSE(ptr1.empty());
EXPECT_EQ(ptr1, &derived_);
ptr1.reset();
EXPECT_TRUE(ptr1.empty());
ptr1 = std::move(mem3);
EXPECT_TRUE(mem3.empty());
EXPECT_FALSE(ptr1.empty());
EXPECT_EQ(ptr1, &derived_);
mem3 = &derived_;
RefPtr<Base> ptr3(mem3);
EXPECT_FALSE(ptr3.empty());
EXPECT_EQ(ptr3, mem3);
}
ExpectEmptyTracker();
}
} // namespace shaka
<file_sep>/shaka/src/util/decryptor.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_UTIL_DECRYPTORS_H_
#define SHAKA_EMBEDDED_UTIL_DECRYPTORS_H_
#include <memory>
#include <vector>
#include "shaka/eme/configuration.h"
#include "src/util/macros.h"
#define AES_BLOCK_SIZE 16u
namespace shaka {
namespace util {
/**
* A utility class that decrypts data. This stores the current decryption state
* so it can be reused for a single decrypt operation. This will only succeed
* if all the data is decrypted, meaning for CBC, a whole AES block needs to be
* given. It is assumed the output is at least the same size as the input.
*/
class Decryptor {
public:
Decryptor(eme::EncryptionScheme scheme, const std::vector<uint8_t>& key,
const std::vector<uint8_t>& iv);
~Decryptor();
NON_COPYABLE_OR_MOVABLE_TYPE(Decryptor);
/**
* Decrypts the given partial block into the given buffer. This must be
* given a partial block and |data_size + block_offset <= AES_BLOCK_SIZE|.
*/
bool DecryptPartialBlock(const uint8_t* data, size_t data_size,
uint32_t block_offset, uint8_t* dest);
/**
* Decrypts the given data into the given buffer. This data size must be a
* multiple of AES_BLOCK_SIZE.
*/
bool Decrypt(const uint8_t* data, size_t data_size, uint8_t* dest);
private:
bool InitIfNeeded();
const eme::EncryptionScheme scheme_;
const std::vector<uint8_t> key_;
std::vector<uint8_t> iv_;
struct Impl;
std::unique_ptr<Impl> extra_;
};
} // namespace util
} // namespace shaka
#endif // SHAKA_EMBEDDED_UTIL_DECRYPTORS_H_
<file_sep>/shaka/src/mapping/backing_object.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/mapping/backing_object.h"
#include "src/mapping/backing_object_factory.h"
#include "src/memory/object_tracker.h"
namespace shaka {
BackingObject::BackingObject() {
memory::ObjectTracker::Instance()->RegisterObject(this);
}
BackingObject::~BackingObject() {
#ifdef USING_JSC
// If a short-lived object is destroyed, the private data in the JavaScript
// object will still point to this object, but it will be invalid.
if (!js_this_.empty())
JSObjectSetPrivate(js_this_.handle(), nullptr);
#endif
}
void BackingObject::Trace(memory::HeapTracer* tracer) const {
// Even though we can re-create the object later we need to trace it.
// JSC will not reset the weak pointer once the object is freed,
// giving us an invalid pointer. So we need to trace it so the pointer
// remains valid.
tracer->Trace(&js_this_);
}
bool BackingObject::IsRootedAlive() const {
#ifdef USING_JSC
return !js_this_.empty();
#else
return false;
#endif
}
std::string BackingObject::name() const {
return factory()->name();
}
bool BackingObject::DerivedFrom(const std::string& base) {
return factory()->DerivedFrom(base);
}
ReturnVal<JsValue> BackingObject::JsThis() {
// This allows a wrapper to be deleted or this object to be created in C++
// where |js_this_| is initially empty.
if (js_this_.empty()) {
// NOTE: WrapInstance will call the JavaScript constructor which will call
// SetJsThis, so no need to use the return value.
factory()->WrapInstance(this);
DCHECK(!js_this_.empty());
}
return js_this_.value();
}
void BackingObject::SetJsThis(Handle<JsObject> this_) {
js_this_ = this_;
}
} // namespace shaka
<file_sep>/shaka/src/mapping/promise.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/mapping/promise.h"
#include <utility>
#include "src/mapping/callback.h"
#include "src/mapping/register_member.h"
#include "src/memory/heap_tracer.h"
namespace shaka {
namespace {
#if defined(USING_V8)
v8::Local<v8::Promise::Resolver> NewPromiseResolver() {
return v8::Promise::Resolver::New(GetIsolate()->GetCurrentContext())
.ToLocalChecked();
}
v8::Local<v8::Promise> GetPromise(v8::Local<v8::Promise::Resolver> resolver) {
return resolver->GetPromise();
}
#elif defined(USING_JSC)
Handle<JSObjectRef> NewPromise(WeakJsPtr<JsObject>* resolve,
WeakJsPtr<JsObject>* reject) {
std::function<void(Callback, Callback)> callback = [&](Callback on_resolve,
Callback on_reject) {
*resolve = UnsafeJsCast<JsObject>(on_resolve.ToJsValue());
*reject = UnsafeJsCast<JsObject>(on_reject.ToJsValue());
};
JSValueRef ctor =
GetMemberRaw(JSContextGetGlobalObject(GetContext()), "Promise");
DCHECK_EQ(GetValueType(ctor), JSValueType::Function);
LocalVar<JsFunction> ctor_obj = UnsafeJsCast<JsFunction>(ctor);
LocalVar<JsValue> ret;
LocalVar<JsValue> args[] = {CreateStaticFunction("", "", callback)};
CHECK(InvokeConstructor(ctor_obj, 1, args, &ret));
return UnsafeJsCast<JsObject>(ret);
}
#endif
} // namespace
#ifdef USING_JSC
Promise::Promise() : promise_(NewPromise(&resolve_, &reject_)) {}
#else
Promise::Promise()
: resolver_(NewPromiseResolver()),
promise_(GetPromise(resolver_.handle())) {}
#endif
Promise::~Promise() {}
Promise::Promise(const Promise&) = default;
Promise::Promise(Promise&&) = default;
Promise& Promise::operator=(const Promise&) = default;
Promise& Promise::operator=(Promise&&) = default;
bool Promise::TryConvert(Handle<JsValue> value) {
if (GetValueType(value) != JSValueType::Promise)
return false;
#ifdef USING_JSC
resolve_ = nullptr;
reject_ = nullptr;
#else
resolver_ = nullptr;
#endif
promise_ = UnsafeJsCast<JsPromise>(value);
return true;
}
ReturnVal<JsValue> Promise::ToJsValue() const {
return promise_.value();
}
void Promise::Trace(memory::HeapTracer* tracer) const {
tracer->Trace(&promise_);
#ifdef USING_JSC
tracer->Trace(&resolve_);
tracer->Trace(&reject_);
#else
tracer->Trace(&resolver_);
#endif
}
void Promise::ResolveWith(Handle<JsValue> value, bool run_events) {
CHECK(CanResolve()) << "Can't reject JavaScript created Promises.";
#if defined(USING_V8)
(void)resolver_.handle()->Resolve(GetIsolate()->GetCurrentContext(), value);
// In V8, Promises are invoked automatically, but *after* executing some
// JavaScript. If we resolve it now, the handlers won't be invoked until we
// call into JavaScript again, and then only after that JavaScript runs. For
// example, if the next JavaScript is a timer, the timer will run first, then
// the Promise handlers will be invoked, which is not the correct order.
if (run_events)
GetIsolate()->RunMicrotasks();
#elif defined(USING_JSC)
LocalVar<JsValue> except;
if (!InvokeMethod(resolve_.handle(), Handle<JsObject>(), 1, &value,
&except)) {
OnUncaughtException(except, /* in_promise */ false);
}
#endif
}
void Promise::RejectWith(const js::JsError& error, bool run_events) {
CHECK(CanResolve()) << "Can't reject JavaScript created Promises.";
#if defined(USING_V8)
(void)resolver_.handle()->Reject(GetIsolate()->GetCurrentContext(),
error.error());
// See comment in ResolveWith().
if (run_events)
GetIsolate()->RunMicrotasks();
#elif defined(USING_JSC)
LocalVar<JsValue> except;
LocalVar<JsValue> rooted(error.error());
if (!InvokeMethod(reject_.handle(), Handle<JsObject>(), 1, &rooted,
&except)) {
OnUncaughtException(except, /* in_promise */ false);
}
#endif
}
void Promise::Then(std::function<void(Any)> on_resolve,
std::function<void(Any)> on_reject) {
// Note this will get from the prototype chain too.
LocalVar<JsValue> member_val = GetMemberRaw(promise_.handle(), "then");
LocalVar<JsFunction> member = UnsafeJsCast<JsFunction>(member_val);
LocalVar<JsValue> except;
LocalVar<JsFunction> on_resolve_js =
CreateStaticFunction("", "", std::move(on_resolve));
LocalVar<JsFunction> on_reject_js =
CreateStaticFunction("", "", std::move(on_reject));
LocalVar<JsValue> arguments[] = {RawToJsValue(on_resolve_js),
RawToJsValue(on_reject_js)};
CHECK(InvokeMethod(member, promise_.handle(), 2, arguments, &except))
<< ConvertToString(except);
}
} // namespace shaka
<file_sep>/shaka/src/js/xml_http_request.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_XML_HTTP_REQUEST_H_
#define SHAKA_EMBEDDED_JS_XML_HTTP_REQUEST_H_
#include <curl/curl.h>
#include <atomic>
#include <map>
#include <string>
#include "shaka/optional.h"
#include "shaka/variant.h"
#include "src/debug/mutex.h"
#include "src/js/events/event_target.h"
#include "src/mapping/backing_object_factory.h"
#include "src/mapping/byte_buffer.h"
#include "src/mapping/byte_string.h"
#include "src/mapping/exception_or.h"
#include "src/util/dynamic_buffer.h"
namespace shaka {
class NetworkThread;
namespace js {
/**
* An implementation of JavaScript XMLHttpRequest. This handles network
* requests using CURL.
*
* Notes:
* - Only supports asynchronous mode.
* - Only support 'arraybuffer' responseType, but still sets responseText.
* - Send() supports string, ArrayBuffer, or ArrayBufferView.
* - Supports responseURL.
* - Supports request/response headers.
* - Support Abort().
* - Fires abort, readystatechange, progress, load, timeout, and loadend events.
*
* IMPORTANT:
* - Ignores CORS.
* - Ignores withCredentials.
* - Does not validate request headers.
*/
class XMLHttpRequest : public events::EventTarget {
DECLARE_TYPE_INFO(XMLHttpRequest);
public:
enum ReadyState {
UNSENT = 0,
OPENED = 1,
HEADERS_RECEIVED = 2,
LOADING = 3,
DONE = 4,
};
XMLHttpRequest();
static XMLHttpRequest* Create() {
return new XMLHttpRequest();
}
void Trace(memory::HeapTracer* tracer) const override;
bool IsShortLived() const override;
void Abort();
std::string GetAllResponseHeaders() const;
optional<std::string> GetResponseHeader(const std::string& name) const;
ExceptionOr<void> Open(const std::string& method, const std::string& url,
optional<bool> async, optional<std::string> user,
optional<std::string> password);
ExceptionOr<void> Send(optional<variant<ByteBuffer, ByteString>> maybe_data);
ExceptionOr<void> SetRequestHeader(const std::string& key,
const std::string& value);
/**
* Called from a CURL callback when (part of) the body data is received.
*/
void OnDataReceived(uint8_t* buffer, size_t length);
/**
* Called from a CURL callback for each header that is received.
* @param buffer A buffer containing exactly one header.
* @param length The length of |buffer|.
*/
void OnHeaderReceived(const uint8_t* buffer, size_t length);
/** Called from a CURL callback when uploading data. */
size_t OnUpload(uint8_t* buffer, size_t length);
Listener on_abort;
Listener on_error;
Listener on_load;
Listener on_load_start;
Listener on_progress;
Listener on_ready_state_change;
Listener on_timeout;
Listener on_load_end;
int ready_state;
ByteBuffer response;
std::string response_text;
std::string response_type;
std::string response_url;
int status;
std::string status_text;
uint64_t timeout_ms; // JavaScript "timeout"
bool with_credentials;
private:
friend NetworkThread;
void RaiseProgressEvents();
/** Called when the request completes. */
void OnRequestComplete(CURLcode code);
void Reset();
mutable Mutex mutex_;
std::map<std::string, std::string> response_headers_;
util::DynamicBuffer temp_data_;
ByteBuffer upload_data_;
CURL* curl_;
curl_slist* request_headers_;
size_t upload_pos_;
uint64_t last_progress_time_;
double estimated_size_;
bool parsing_headers_;
std::atomic<bool> abort_pending_;
};
class XMLHttpRequestFactory
: public BackingObjectFactory<XMLHttpRequest, events::EventTarget> {
public:
XMLHttpRequestFactory();
};
} // namespace js
} // namespace shaka
#endif // SHAKA_EMBEDDED_JS_XML_HTTP_REQUEST_H_
<file_sep>/shaka/src/util/objc_utils.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_UTIL_OBJC_UTILS_H_
#define SHAKA_EMBEDDED_UTIL_OBJC_UTILS_H_
#if !defined(__OBJC__) || !defined(__cplusplus)
# error "Can only be included from Objective-C++"
#endif
#include <Foundation/Foundation.h>
#include <string>
#include <type_traits>
#include <vector>
#include "shaka/optional.h"
namespace shaka {
namespace util {
template <typename T>
struct ObjcConverter;
template <>
struct ObjcConverter<std::string> {
static NSString *ToObjc(const std::string &value) {
return [[NSString alloc] initWithBytes:value.c_str()
length:value.size()
encoding:NSUTF8StringEncoding];
}
};
template <>
struct ObjcConverter<bool> {
static BOOL ToObjc(bool value) {
return value ? YES : NO;
}
};
template <>
struct ObjcConverter<double> {
static double ToObjc(double value) {
return value;
}
};
template <>
struct ObjcConverter<optional<bool>> {
static BOOL ToObjc(optional<bool> value) {
return value.has_value() ? *value : NO;
}
};
template <>
struct ObjcConverter<optional<double>> {
static double ToObjc(optional<double> value) {
return value.has_value() ? *value : NAN;
}
};
template <>
struct ObjcConverter<optional<std::string>> {
static NSString *ToObjc(optional<std::string> value) {
return value.has_value() ? ObjcConverter<std::string>::ToObjc(*value) : nil;
}
};
template <typename T>
struct ObjcConverter<std::vector<T>> {
using dest_type = decltype(ObjcConverter<T>::ToObjc(std::declval<T>()));
static NSArray<dest_type> *ToObjc(const std::vector<T>& value) {
NSMutableArray<dest_type>* ret =
[[NSMutableArray<dest_type> alloc] initWithCapacity:value.size()];
for (size_t i = 0; i < value.size(); i++)
[ret addObject:ObjcConverter<T>::ToObjc(value[i])];
return ret;
}
};
} // namespace util
} // namespace shaka
#endif // SHAKA_EMBEDDED_UTIL_OBJC_UTILS_H_
<file_sep>/shaka/src/mapping/jsc/js_engine.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/mapping/js_engine.h"
#include "src/core/js_manager_impl.h"
#include "src/memory/heap_tracer.h"
#include "src/memory/object_tracker.h"
namespace shaka {
namespace {
constexpr const uint64_t kGcIntervalMs = 30 * 1000;
} // namespace
// \cond Doxygen_Skip
JsEngine::JsEngine()
: context_(JSGlobalContextCreate(nullptr)),
thread_id_(std::this_thread::get_id()) {
auto task = []() {
VLOG(1) << "Begin GC run";
auto* object_tracker = memory::ObjectTracker::Instance();
auto* heap_tracer = object_tracker->heap_tracer();
heap_tracer->BeginPass();
heap_tracer->TraceCommon(object_tracker->GetAliveObjects());
object_tracker->FreeDeadObjects(heap_tracer->alive());
// This will signal to JSC that we have just destroyed a lot of objects.
// See http://bugs.webkit.org/show_bug.cgi?id=84476
JSGarbageCollect(GetContext());
VLOG(1) << "End GC run";
};
// If the engine was created as part of a test, then don't create the timer
// since we don't need to GC.
JsManagerImpl* impl = JsManagerImpl::InstanceOrNull();
if (impl) {
impl->MainThread()->AddRepeatedTimer(kGcIntervalMs,
PlainCallbackTask(task));
}
}
JsEngine::~JsEngine() {
JSGlobalContextRelease(context_);
}
Handle<JsObject> JsEngine::global_handle() {
return JSContextGetGlobalObject(context());
}
ReturnVal<JsValue> JsEngine::global_value() {
return JSContextGetGlobalObject(context());
}
JSContextRef JsEngine::context() const {
// TODO: Consider asserting we are on the correct thread. Unlike other
// JavaScript engines, JSC allows access from any thread and will just
// serialize the requests. We can't assert as of now since the C++ API's
// Player will unref in the destructor.
return context_;
}
JsEngine::SetupContext::SetupContext() {}
JsEngine::SetupContext::~SetupContext() {}
// \endcond Doxygen_Skip
} // namespace shaka
<file_sep>/shaka/tools/webidl/webidl/types.py
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Defines the AST types for IDL parsing."""
from __future__ import print_function
import collections
import sys
try:
import enum # pylint: disable=g-import-not-at-top
except ImportError:
print('Requires the "enum34" pip polyfill to be installed', file=sys.stderr)
raise
class ExtensionLocation(enum.Enum):
"""Defines possible locations an extension can be put."""
# e.g. an 'interface' definition.
DEFINITION = 'definition'
# An annotated type (e.g. as an argument type). Note this is different than
# ARGUMENT. If the location is ambiguous, it favors the TYPE; this means that
# the extension will appear on the IdlType and not on the Argument.
TYPE = 'type'
MEMBER = 'member'
MIXIN_MEMBER = 'mixin member'
NAMESPACE_MEMBER = 'namespace member'
DICTIONARY_MEMBER = 'dictionary member'
ARGUMENT = 'argument'
class ExtensionKind(enum.Enum):
"""Defines the type of extension this is.
The type of extension defines the fields that exist on the object. The
constructor is given named arguments for each of the fields.
"""
# This has no fields.
# For example: [Replaceable]
NO_ARGS = 'NoArgs'
# - 'args': A list of Argument objects for the args.
# For example: [Constructor(double x, double y)]
ARG_LIST = 'ArgList'
# - 'argsName': The string name given.
# - 'args': A list of Argument objects for the args.
# For example: [NamedConstructor=Image(DOMString src)]
NAMED_ARG_LIST = 'NamedArgList'
# - 'arg': The string identifier given.
# For example: [PutForwards=name]
IDENT = 'Ident'
# - 'args': A list of strings for the identifiers given.
# For example: [Exposed=(Window,Worker)]
# Note this allows using [Exposed=Window] for a single item.
IDENT_LIST = 'IdentList'
class Extension(object):
"""Defines a base class for extensions.
Derived classes are expected to define the following type fields:
- name: A string name of the extension.
- kind: An ExtensionKind for the kind of extension.
- locations: A list of ExtensionLocation for where the extension can be.
The constructor will be called with name-value pairs based on the kind of
extension this is.
"""
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
# A signal value used to indicate a default value is "null".
IdlNull = object() # pylint: disable=invalid-name
class DebugInfo(collections.namedtuple('DebugInfo', ('lineno', 'col', 'line'))):
"""Defines where in the IDL an element was defined.
Properties:
lineno: The 1-based line number where the element starts.
col: The 1-based column offset where the element starts.
line: The string line that the definition starts at. This includes any text
before the definition itself. This only includes the first line if the
element spans multiple.
"""
__slots__ = ()
class Argument(collections.namedtuple(
'Argument', ('name', 'type', 'optional', 'is_variadic', 'default'))):
"""Defines an argument to a method.
Properties:
name: The string name of the argument.
type: An IdlType object that describes the type of the argument.
optional: Whether this argument is optional.
is_variadic: Whether this argument is variadic; this will only be True for
the last argument in the list.
default: The default value of the argument. This can be a number, string,
boolean, empty list, IdlNull, or None (for no default).
"""
__slots__ = ()
class IdlType(collections.namedtuple(
'IdlType', ('name', 'nullable', 'element_type'))):
"""Defines a type of an attribute or argument.
Properties:
name: The string name of the type.
nullable: Whether the type can be null.
element_type: If present, it is an IdlType that specifies the element type
for an array. In this case, |name| is always "sequence".
"""
__slots__ = ()
class Attribute(collections.namedtuple(
'Attribute', ('name', 'type', 'default', 'is_required', 'doc', 'debug',
'docDebug'))):
"""Defines an attribute on a type.
Properties:
name: The string name of the attribute.
type: An IdlType object defining the type of the attribute.
default: The default value of the attribute. This can be a number, string,
boolean, empty list, an IdlNull object, or None (for no default).
is_required: Whether the attribute is required to be present.
doc: The string comment describing the attribute.
debug: A DebugInfo object describing where this dictionary starts.
docDebug: A DebugInfo object describing where the docstring starts. This
is None if there is no docstring.
"""
__slots__ = ()
class Dictionary(collections.namedtuple(
'Dictionary', ('name', 'attributes', 'doc', 'debug', 'docDebug'))):
"""Defines a dictionary definition.
Properties:
name: The string name of the dictionary.
attributes: A list of Attribute objects for the attributes in the dict.
doc: The string comment describing the type.
debug: A DebugInfo object describing where this dictionary starts.
docDebug: A DebugInfo object describing where the docstring starts. This
is None if there is no docstring.
"""
__slots__ = ()
class Results(collections.namedtuple('Results', ('types',))):
"""Defines the results of parsing an IDL file.
Properties:
types: A list of types the file defines. Will always be a Dictionary type.
"""
__slots__ = ()
<file_sep>/shaka/src/js/eme/media_keys.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/eme/media_keys.h"
#include "src/js/eme/media_key_session.h"
#include "src/js/js_error.h"
#include "src/mapping/convert_js.h"
namespace shaka {
namespace js {
namespace eme {
MediaKeys::MediaKeys(ImplementationFactory* factory,
const std::string& key_system,
const MediaKeySystemConfiguration& config)
: helper_(key_system, this), factory_(factory) {
std::vector<std::string> audio_robustness, video_robustness;
for (auto& item : config.audioCapabilities) {
audio_robustness.push_back(item.robustness);
}
for (auto& item : config.videoCapabilities) {
video_robustness.push_back(item.robustness);
}
implementation_ = factory_->CreateImplementation(
&helper_, config.distinctiveIdentifier, config.persistentState,
audio_robustness, video_robustness);
}
// \cond Doxygen_Skip
MediaKeys::~MediaKeys() {
if (implementation_) {
implementation_->Destroy();
implementation_ = nullptr;
}
}
// \endcond Doxygen_Skip
void MediaKeys::Trace(memory::HeapTracer* tracer) const {
std::unique_lock<std::mutex> lock(mutex_);
BackingObject::Trace(tracer);
tracer->Trace(&sessions_);
}
bool MediaKeys::valid() const {
return implementation_;
}
ExceptionOr<RefPtr<MediaKeySession>> MediaKeys::CreateSession(
optional<MediaKeySessionType> session_type) {
const MediaKeySessionType type =
session_type.value_or(MediaKeySessionType::Temporary);
if (!factory_->SupportsSessionType(type)) {
return JsError::DOMException(NotSupportedError,
"The given session type is not supported.");
}
std::unique_lock<std::mutex> lock(mutex_);
RefPtr<MediaKeySession> session =
new MediaKeySession(type, factory_, implementation_, &helper_);
sessions_.emplace_back(session);
return session;
}
Promise MediaKeys::SetServerCertificate(ByteBuffer cert) {
Promise ret;
implementation_->SetServerCertificate(EmePromise(ret, /* has_value */ true),
Data(&cert));
return ret;
}
RefPtr<MediaKeySession> MediaKeys::GetSession(const std::string& session_id) {
std::unique_lock<std::mutex> lock(mutex_);
for (auto& session : sessions_) {
if (session->SessionId() == session_id)
return session;
}
return nullptr;
}
MediaKeysFactory::MediaKeysFactory() {
AddMemberFunction("createSession", &MediaKeys::CreateSession);
AddMemberFunction("setServerCertificate", &MediaKeys::SetServerCertificate);
}
} // namespace eme
} // namespace js
} // namespace shaka
<file_sep>/shaka/include/shaka/eme/eme_promise.h
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_EME_PROMISE_H_
#define SHAKA_EMBEDDED_EME_PROMISE_H_
#include <memory>
#include <string>
#include "configuration.h"
namespace shaka {
class Promise;
namespace js {
namespace eme {
class MediaKeys;
class MediaKeySession;
} // namespace eme
} // namespace js
namespace eme {
/**
* Defines a wrapper around a JavaScript Promise object.
*
* EME APIs are always given valid Promise objects; but if you use the default
* constructor or use std::move(), it will create an invalid Promise object.
* You can't call any methods on an invalid object except for valid().
*
* @ingroup eme
*/
class SHAKA_EXPORT EmePromise final {
public:
/**
* Creates an *invalid* Promise object. The members of this object can't be
* used unless a valid Promise is moved/copied into this.
*/
EmePromise();
EmePromise(const EmePromise& other);
EmePromise(EmePromise&& other);
~EmePromise();
EmePromise& operator=(const EmePromise& other);
EmePromise& operator=(EmePromise&& other);
/** @return Whether this object is valid and can be resolved/rejected. */
bool valid() const;
/**
* Resolves the Promise. If the Promise has already been resolved/rejected,
* this call is ignored.
*/
void Resolve();
/**
* Resolves the Promise with the given value. If the Promise has already been
* resolved/rejected, this call is ignored.
*/
void ResolveWith(bool value);
/**
* Rejects the Promise with the given error. If the Promise has already been
* resolved/rejected, this call is ignored.
*/
void Reject(ExceptionType except_type, const std::string& message);
private:
class Impl;
friend class ClearKeyImplementationTest;
friend class js::eme::MediaKeys;
friend class js::eme::MediaKeySession;
EmePromise(const Promise& promise, bool has_value);
EmePromise(std::shared_ptr<Impl> impl);
std::shared_ptr<Impl> impl_;
};
} // namespace eme
} // namespace shaka
#endif // SHAKA_EMBEDDED_EME_PROMISE_H_
<file_sep>/shaka/src/js/dom/container_node.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_JS_DOM_CONTAINER_NODE_H_
#define SHAKA_EMBEDDED_JS_DOM_CONTAINER_NODE_H_
#include <string>
#include <vector>
#include "src/core/member.h"
#include "src/core/ref_ptr.h"
#include "src/js/dom/node.h"
namespace shaka {
namespace js {
namespace dom {
class Element;
/**
* Defines a Node that has children. This defines a common base class between
* Element and Document.
*
* This also implements the ParentNode mixin:
* https://dom.spec.whatwg.org/#parentnode
*/
class ContainerNode : public Node {
DECLARE_TYPE_INFO(ContainerNode);
public:
ContainerNode(NodeType type, RefPtr<Document> document);
std::vector<RefPtr<Element>> GetElementsByTagName(
const std::string& name) const;
};
class ContainerNodeFactory : public BackingObjectFactory<ContainerNode, Node> {
public:
ContainerNodeFactory();
};
} // namespace dom
} // namespace js
} // namespace shaka
#endif // SHAKA_EMBEDDED_JS_DOM_CONTAINER_NODE_H_
<file_sep>/shaka/src/util/file_system_posix.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/util/file_system.h"
#include <dirent.h>
#include <libgen.h>
#include <sys/stat.h>
#include <unistd.h>
#include <glog/logging.h>
namespace shaka {
namespace util {
namespace {
const char kDirectorySeparator = '/';
} // namespace
// static
std::string FileSystem::PathJoin(const std::string& a, const std::string& b) {
if (b.empty())
return a;
if (a.empty() || b[0] == kDirectorySeparator)
return b;
if (a[a.size() - 1] == kDirectorySeparator)
return a + b;
return a + kDirectorySeparator + b;
}
// static
std::string FileSystem::DirName(const std::string& path) {
// Create a copy of |path|. Then dirname will edit the string to put a
// null char at the last slash. When it returns the argument, the string
// constructor will copy the string up to that null char.
std::string copy = path;
return dirname(©[0]);
}
bool FileSystem::FileExists(const std::string& path) const {
// Cannot use fstream for this since it allows opening directories.
struct stat info;
return stat(path.c_str(), &info) == 0 && S_ISREG(info.st_mode);
}
bool FileSystem::DirectoryExists(const std::string& path) const {
struct stat info;
return stat(path.c_str(), &info) == 0 && S_ISDIR(info.st_mode);
}
bool FileSystem::DeleteFile(const std::string& path) const {
return unlink(path.c_str()) == 0;
}
bool FileSystem::CreateDirectory(const std::string& path) const {
std::string::size_type pos = 0;
while ((pos = path.find(kDirectorySeparator, pos + 1)) != std::string::npos) {
if (mkdir(path.substr(0, pos).c_str(), 0755) != 0 && errno != EEXIST)
return false;
}
return mkdir(path.c_str(), 0755) == 0 || errno == EEXIST;
}
bool FileSystem::ListFiles(const std::string& path,
std::vector<std::string>* files) const {
files->clear();
DIR* dir;
dirent* entry;
if ((dir = opendir(path.c_str())) == nullptr) {
PLOG(ERROR) << "Unable to open directory '" << path << "'";
return false;
}
while ((entry = readdir(dir)) != nullptr) {
if (!strcmp(".", entry->d_name) || !strcmp("..", entry->d_name))
continue;
const std::string sub_path = PathJoin(path, entry->d_name);
struct stat info;
CHECK_EQ(0, stat(sub_path.c_str(), &info));
if (S_ISREG(info.st_mode))
files->push_back(entry->d_name);
else if (!S_ISDIR(info.st_mode))
LOG(WARNING) << "Unable to process folder entry '" << sub_path << "'";
}
closedir(dir);
return true;
}
} // namespace util
} // namespace shaka
<file_sep>/build.py
#!/usr/bin/python
# Copyright 2016 Google LLC
#
# Licensed under the Apache License, Version 2.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.
"""Compiles the library, demo, and tests.
"""
from __future__ import print_function
import argparse
import os
import shutil
import subprocess
import sys
ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(ROOT_DIR, 'shaka', 'tools'))
import utils
def CopyDataFiles(config_dir, dest, link=False):
"""Copies the data files to the given destination."""
def CopyFile(*path, **kwargs):
abs_src = os.path.join(ROOT_DIR, *path)
abs_dest = os.path.join(dest, kwargs.get('name', path[-1]))
if link and hasattr(os, 'symlink'):
try:
os.remove(abs_dest)
except IOError:
pass
os.symlink(abs_src, abs_dest)
else:
shutil.copy(abs_src, abs_dest)
if utils.GetGnArg(config_dir, 'is_debug', is_string=False) == 'true':
CopyFile('shaka', 'js', 'shaka-player.compiled.debug.js',
name='shaka-player.compiled.js')
else:
CopyFile('shaka', 'js', 'shaka-player.compiled.js')
def Build(build_dir, clean=False):
"""Builds the library."""
if clean:
return subprocess.call(['ninja', '-C', build_dir, '-t', 'clean'])
else:
return subprocess.call(['ninja', '-C', build_dir, 'player'])
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'--config-name', dest='config',
help='Do a special in-tree build with this configuration name.')
parser.add_argument('--clean', dest='clean', action='store_true',
help='Delete all temporary object files for this config.')
parser.add_argument('--data-dir', dest='data_dir',
help='The directory to copy program data to.')
parser.add_argument('--symlink-data', dest='symlink', action='store_true',
help='Don\'t copy program data, create symlinks instead.')
ns = parser.parse_args(args)
config_dir = utils.ConfigPath(ns.config)
if (not os.path.exists(os.path.join(config_dir, 'build.ninja')) and
os.path.exists(os.path.join(config_dir, 'args.gn'))):
print('Ninja files missing, trying to recover them...', file=sys.stderr)
configure = os.path.join(ROOT_DIR, 'configure')
if subprocess.call([configure, '--recover', '--config-name',
ns.config]) != 0:
return 1
utils.CheckConfigName(ns.config)
if Build(config_dir, ns.clean) != 0:
return 1
if not ns.clean:
CopyDataFiles(config_dir, ns.data_dir or config_dir, ns.symlink)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
<file_sep>/shaka/src/util/crypto_openssl.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/util/crypto.h"
#include <glog/logging.h>
#include <openssl/evp.h>
#define HASH_ALGORITHM EVP_md5()
namespace shaka {
namespace util {
std::vector<uint8_t> HashData(const uint8_t* data, size_t size) {
EVP_MD_CTX* ctx = EVP_MD_CTX_create();
CHECK(ctx);
CHECK_EQ(EVP_DigestInit_ex(ctx, HASH_ALGORITHM, nullptr), 1u);
CHECK_EQ(EVP_DigestUpdate(ctx, data, size), 1u);
std::vector<uint8_t> result(EVP_MD_size(HASH_ALGORITHM));
CHECK_EQ(EVP_DigestFinal_ex(ctx, result.data(), nullptr), 1u);
return result;
}
} // namespace util
} // namespace shaka
<file_sep>/shaka/src/mapping/byte_buffer.h
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#ifndef SHAKA_EMBEDDED_MAPPING_BYTE_BUFFER_H_
#define SHAKA_EMBEDDED_MAPPING_BYTE_BUFFER_H_
#include <cstring>
#include <string>
#include "src/mapping/generic_converter.h"
#include "src/mapping/js_wrappers.h"
#include "src/mapping/weak_js_ptr.h"
#include "src/util/dynamic_buffer.h"
namespace shaka {
/**
* Represents a buffer of data that is shared between C++ and JavaScript. This
* holds a single ArrayBuffer that refers to the data, which can be passed into
* JavaScript. Since ArrayBuffers are immutable, this type is read-only.
*/
class ByteBuffer : public GenericConverter, public memory::Traceable {
public:
static std::string name() {
return "arraybuffer";
}
ByteBuffer();
ByteBuffer(const uint8_t* data, size_t data_size);
~ByteBuffer() override;
ByteBuffer(const ByteBuffer&) = delete;
ByteBuffer(ByteBuffer&&);
ByteBuffer& operator=(const ByteBuffer& other) = delete;
ByteBuffer& operator=(ByteBuffer&& other);
/** @return A pointer to the buffer. */
const uint8_t* data() const {
return ptr_;
}
/** @return The size of the buffer (in bytes). */
size_t size() const {
return size_;
}
/** Clears all the data stored in the buffer. */
void Clear();
/**
* Clears the buffer and sets the contents to a copy of the given buffer.
* This can be called from any thread.
*
* This will allocate a block of memory the same as JavaScript expects and
* take ownership of it (own_ptr_). Then, when we need the ArrayBuffer, we
* create it then giving up ownership of the pointer so we don't have to copy
* it.
*/
void SetFromDynamicBuffer(const util::DynamicBuffer& other);
/** Similar to SetFromDynamicBuffer, except accepts a single buffer source. */
void SetFromBuffer(const void* buffer, size_t size);
bool TryConvert(Handle<JsValue> value) override;
ReturnVal<JsValue> ToJsValue() const override;
void Trace(memory::HeapTracer* tracer) const override;
private:
/** Resets all fields to empty. */
void ClearFields();
/**
* Clears the buffer and allocates a new buffer of the given size. This will
* allocate the block the same as JavaScript expects and take ownership of
* it (own_ptr_). Then, when we need the ArrayBuffer, we create it then,
* giving up ownership of the pointer so we don't have to copy it.
*/
void ClearAndAllocateBuffer(size_t size);
// Both |buffer_| and |ptr_| point to the same data block. |buffer_| and
// |own_ptr_| are mutable to allow ToJsValue to create a new ArrayBuffer to
// take ownership of |ptr_|.
mutable WeakJsPtr<JsObject> buffer_;
uint8_t* ptr_ = nullptr;
size_t size_ = 0;
// Whether we own |ptr_|, this may be slightly different from
// |buffer_.empty()| since the ArrayBuffer may be destroyed before we
// are during a GC run.
mutable bool own_ptr_ = false;
};
inline bool operator==(const ByteBuffer& lhs, const ByteBuffer& rhs) {
return lhs.size() == rhs.size() &&
memcmp(lhs.data(), rhs.data(), lhs.size()) == 0;
}
inline bool operator!=(const ByteBuffer& lhs, const ByteBuffer& rhs) {
return !(lhs == rhs);
}
} // namespace shaka
namespace std {
template <>
struct hash<shaka::ByteBuffer> {
size_t operator()(const shaka::ByteBuffer& buffer) const {
// Introduce some noise to make small buffers have a more distributed hash.
uint64_t ret = 0xacbdcfd0e1f20304;
const uint8_t* ptr = buffer.data();
for (size_t count = buffer.size(); count > 0; ptr++, count--) {
// Rotate the number to make the order of bytes matter and so we affect
// the whole number.
ret = (ret << 8) | (ret >> 56);
// "insert" the data into the hash.
ret ^= *ptr;
}
// Intentionally truncate on 32-bit platforms.
return static_cast<size_t>(ret);
}
};
} // namespace std
#endif // SHAKA_EMBEDDED_MAPPING_BYTE_BUFFER_H_
<file_sep>/shaka/src/media/decoder_thread.cc
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/media/decoder_thread.h"
#include <chrono>
#include <cmath>
#include <memory>
#include <utility>
#include <vector>
#include "src/media/media_processor.h"
#include "src/media/pipeline_manager.h"
#include "src/media/stream.h"
namespace shaka {
namespace media {
/** The number of seconds to keep decoded ahead of the playhead. */
constexpr const double kDecodeBufferSize = 1;
/** The number of seconds gap before we assume we are at the end. */
constexpr const double kEndDelta = 0.1;
DecoderThread::DecoderThread(std::function<double()> get_time,
std::function<void()> seek_done,
std::function<void()> on_waiting_for_key,
std::function<void(Status)> on_error,
MediaProcessor* processor,
PipelineManager* pipeline, Stream* stream)
: processor_(processor),
pipeline_(pipeline),
stream_(stream),
get_time_(std::move(get_time)),
seek_done_(std::move(seek_done)),
on_waiting_for_key_(std::move(on_waiting_for_key)),
on_error_(std::move(on_error)),
cdm_(nullptr),
shutdown_(false),
is_seeking_(false),
did_flush_(false),
last_frame_time_(NAN),
raised_waiting_event_(false),
thread_(processor->codec() + " decoder",
std::bind(&DecoderThread::ThreadMain, this)) {}
DecoderThread::~DecoderThread() {
CHECK(!thread_.joinable()) << "Need to call Stop() before destroying";
}
void DecoderThread::Stop() {
shutdown_.store(true, std::memory_order_release);
thread_.join();
}
void DecoderThread::OnSeek() {
last_frame_time_.store(NAN, std::memory_order_release);
is_seeking_.store(true, std::memory_order_release);
did_flush_.store(false, std::memory_order_release);
}
void DecoderThread::SetCdm(eme::Implementation* cdm) {
cdm_.store(cdm, std::memory_order_release);
}
void DecoderThread::ThreadMain() {
while (!shutdown_.load(std::memory_order_acquire)) {
const double cur_time = get_time_();
double last_time = last_frame_time_.load(std::memory_order_acquire);
LockedFrameList::Guard frame;
if (std::isnan(last_time)) {
processor_->ResetDecoder();
frame = stream_->GetDemuxedFrames()->GetKeyFrameBefore(cur_time);
} else {
frame = stream_->GetDemuxedFrames()->GetFrameAfter(last_time);
}
if (stream_->DecodedAheadOf(cur_time) > kDecodeBufferSize) {
std::this_thread::sleep_for(std::chrono::milliseconds(25));
continue;
}
if (!frame) {
if (!std::isnan(last_time) &&
last_time + kEndDelta >= pipeline_->GetDuration() &&
!did_flush_.load(std::memory_order_acquire)) {
// If this is the last frame, pass the null to DecodeFrame, which will
// flush the decoder.
did_flush_.store(true, std::memory_order_release);
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(25));
continue;
}
}
std::vector<std::unique_ptr<BaseFrame>> decoded;
eme::Implementation* cdm = cdm_.load(std::memory_order_acquire);
const Status decode_status =
processor_->DecodeFrame(cur_time, frame.get(), cdm, &decoded);
if (decode_status == Status::KeyNotFound) {
// If we don't have the required key, signal the <video> and wait.
if (!raised_waiting_event_) {
raised_waiting_event_ = true;
on_waiting_for_key_();
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
}
if (decode_status != Status::Success) {
on_error_(decode_status);
break;
}
raised_waiting_event_ = false;
const double last_pts = decoded.empty() ? -1 : decoded.back()->pts;
for (auto& decoded_frame : decoded)
stream_->GetDecodedFrames()->AppendFrame(std::move(decoded_frame));
if (frame) {
// Don't change the |last_frame_time_| if it was reset to NAN while this
// was running.
const bool updated = last_frame_time_.compare_exchange_strong(
last_time, frame->dts, std::memory_order_acq_rel);
if (updated && last_pts >= cur_time) {
bool expected = true;
if (is_seeking_.compare_exchange_strong(expected, false,
std::memory_order_acq_rel)) {
seek_done_();
}
}
}
}
}
} // namespace media
} // namespace shaka
<file_sep>/shaka/src/public/sdl_frame_drawer.cc
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "shaka/sdl_frame_drawer.h"
#include <list>
#include <unordered_set>
#include "src/util/macros.h"
namespace shaka {
namespace {
constexpr const size_t kMaxTextures = 8;
struct TextureInfo {
SDL_Texture* texture;
uint32_t pixel_format;
int width;
int height;
};
Uint32 SdlPixelFormatFromPublic(PixelFormat format) {
switch (format) {
#if SDL_VERSION_ATLEAST(2, 0, 4)
case PixelFormat::NV12:
return SDL_PIXELFORMAT_NV12;
#endif
case PixelFormat::YUV420P:
return SDL_PIXELFORMAT_IYUV;
case PixelFormat::RGB24:
return SDL_PIXELFORMAT_RGB24;
default:
return SDL_PIXELFORMAT_UNKNOWN;
}
}
PixelFormat PublicPixelFormatFromSdl(Uint32 format) {
switch (format) {
#if SDL_VERSION_ATLEAST(2, 0, 4)
case SDL_PIXELFORMAT_NV12:
return PixelFormat::NV12;
#endif
case SDL_PIXELFORMAT_IYUV:
return PixelFormat::YUV420P;
case SDL_PIXELFORMAT_RGB24:
return PixelFormat::RGB24;
default:
return PixelFormat::Unknown;
}
}
} // namespace
class SdlFrameDrawer::Impl {
public:
Impl() : renderer_(nullptr) {}
~Impl() {
Clear();
}
NON_COPYABLE_OR_MOVABLE_TYPE(Impl);
void SetRenderer(SDL_Renderer* renderer) {
Clear();
texture_formats_.clear();
renderer_ = renderer;
SDL_RendererInfo info;
if (SDL_GetRendererInfo(renderer, &info) == 0) {
texture_formats_.insert(info.texture_formats,
info.texture_formats + info.num_texture_formats);
}
if (texture_formats_.empty()) {
LOG(ERROR) << "No supported texture formats";
}
}
SDL_Texture* Draw(Frame* frame) {
if (!frame || !frame->valid())
return nullptr;
auto sdl_pix_fmt = SdlPixelFormatFromPublic(frame->pixel_format());
if (sdl_pix_fmt == SDL_PIXELFORMAT_UNKNOWN ||
texture_formats_.count(sdl_pix_fmt) == 0) {
if (!Convert(frame))
return nullptr;
sdl_pix_fmt = SdlPixelFormatFromPublic(frame->pixel_format());
}
SDL_Texture* texture =
GetTexture(sdl_pix_fmt, frame->width(), frame->height());
if (!texture)
return nullptr;
if (!DrawOntoTexture(frame, texture, sdl_pix_fmt))
return nullptr;
return texture;
}
private:
bool DrawOntoTexture(Frame* frame, SDL_Texture* texture, Uint32 sdl_pix_fmt) {
const uint8_t* const* frame_data = frame->data();
const int* frame_linesize = frame->linesize();
// TODO: It is possible for linesize values to be negative. Handle this
// case: https://www.ffmpeg.org/doxygen/trunk/ffplay_8c_source.html#l00905
DCHECK_GE(frame_linesize[0], 0);
if (sdl_pix_fmt == SDL_PIXELFORMAT_IYUV) {
if (SDL_UpdateYUVTexture(
texture, nullptr, frame_data[0], frame_linesize[0], frame_data[1],
frame_linesize[1], frame_data[2], frame_linesize[2]) < 0) {
LOG(ERROR) << "Error updating texture: " << SDL_GetError();
return false;
}
#if SDL_VERSION_ATLEAST(2, 0, 4)
} else if (sdl_pix_fmt == SDL_PIXELFORMAT_NV12 ||
sdl_pix_fmt == SDL_PIXELFORMAT_NV21) {
uint8_t* pixels;
int pitch;
if (SDL_LockTexture(texture, nullptr, reinterpret_cast<void**>(&pixels),
&pitch) < 0) {
LOG(ERROR) << "Error locking texture: " << SDL_GetError();
return false;
}
if (pitch == frame_linesize[0]) {
// TODO: Sometimes there is a green bar at the bottom.
const size_t size0 = pitch * frame->height();
memcpy(pixels, frame_data[0], size0);
memcpy(pixels + size0, frame_data[1], size0 / 2);
} else {
// FFmpeg may add padding to the rows, so we need to drop it by manually
// copying each line.
DCHECK_GE(frame_linesize[0], pitch);
const int min_width = std::min(pitch, frame_linesize[0]);
for (uint32_t row = 0; row < frame->height(); row++) {
uint8_t* dest = pixels + pitch * row;
const uint8_t* src = frame_data[0] + frame_linesize[0] * row;
memcpy(dest, src, min_width);
}
for (uint32_t row = 0; row < frame->height() / 2; row++) {
uint8_t* dest = pixels + pitch * (row + frame->height());
const uint8_t* src = frame_data[1] + frame_linesize[1] * row;
memcpy(dest, src, min_width);
}
}
SDL_UnlockTexture(texture);
#endif
} else {
if (SDL_UpdateTexture(texture, nullptr, frame_data[0],
frame_linesize[0]) < 0) {
LOG(ERROR) << "Error updating texture: " << SDL_GetError();
return false;
}
}
return true;
}
bool Convert(Frame* frame) {
for (Uint32 sdl_fmt : texture_formats_) {
auto public_fmt = PublicPixelFormatFromSdl(sdl_fmt);
if (public_fmt != PixelFormat::Unknown && frame->ConvertTo(public_fmt))
return true;
}
return false;
}
SDL_Texture* GetTexture(Uint32 pixel_format, int width, int height) {
if (!renderer_)
return nullptr;
for (auto it = textures_.begin(); it != textures_.end(); it++) {
if (it->pixel_format == pixel_format && it->width == width &&
it->height == height) {
if (std::next(it) != textures_.end()) {
// Move the texture to the end so elements at the beginning are ones
// that were least-recently used.
textures_.splice(textures_.end(), textures_, it);
}
return it->texture;
}
}
if (!textures_.empty() && textures_.size() >= kMaxTextures) {
SDL_DestroyTexture(textures_.front().texture);
textures_.erase(textures_.begin());
DCHECK_LT(textures_.size(), kMaxTextures);
}
SDL_Texture* texture = SDL_CreateTexture(
renderer_, pixel_format, SDL_TEXTUREACCESS_STREAMING, width, height);
if (texture)
textures_.push_back({texture, pixel_format, width, height});
else
LOG(ERROR) << "Error creating texture: " << SDL_GetError();
return texture;
}
void Clear() {
for (auto& info : textures_)
SDL_DestroyTexture(info.texture);
}
std::list<TextureInfo> textures_;
std::unordered_set<Uint32> texture_formats_;
SDL_Renderer* renderer_;
};
SdlFrameDrawer::SdlFrameDrawer() : impl_(new Impl) {}
SdlFrameDrawer::SdlFrameDrawer(SdlFrameDrawer&&) = default;
SdlFrameDrawer::~SdlFrameDrawer() {}
SdlFrameDrawer& SdlFrameDrawer::operator=(SdlFrameDrawer&&) = default;
void SdlFrameDrawer::SetRenderer(SDL_Renderer* renderer) {
impl_->SetRenderer(renderer);
}
SDL_Texture* SdlFrameDrawer::Draw(Frame* frame) {
return impl_->Draw(frame);
}
} // namespace shaka
<file_sep>/shaka/test/src/memory/heap_tracer_unittest.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/memory/heap_tracer.h"
#include <gtest/gtest.h>
#include "src/core/member.h"
#include "src/mapping/backing_object.h"
#include "src/memory/object_tracker.h"
namespace shaka {
namespace memory {
namespace {
class TestObject : public BackingObject {
public:
static std::string name() {
return "";
}
void Trace(memory::HeapTracer* tracer) const override {
// Don't trace JsThis since we don't actually use the value. We haven't
// setup the JavaScript engine, so we can't trace any JavaScript objects.
}
private:
BackingObjectFactoryBase* factory() const override {
return nullptr;
}
};
class TestObjectWithBackingChild : public TestObject {
public:
void Trace(HeapTracer* tracer) const override {
tracer->Trace(&member1);
tracer->Trace(&member2);
tracer->Trace(&member3);
}
Member<TestObject> member1;
Member<TestObject> member2;
Member<TestObject> member3;
};
} // namespace
class HeapTracerTest : public testing::Test {
public:
~HeapTracerTest() override {
tracker.UnregisterAllObjects();
}
protected:
template <typename T, typename... Args>
void ExpectAlive(T arg, Args... args) {
EXPECT_EQ(1u, tracker.heap_tracer()->alive().count(arg));
ExpectAlive(args...);
}
void ExpectAlive() {}
template <typename T, typename... Args>
void ExpectDead(T arg, Args... args) {
EXPECT_EQ(0u, tracker.heap_tracer()->alive().count(arg));
ExpectDead(args...);
}
void ExpectDead() {}
void RunTracer(const std::unordered_set<const Traceable*>& ref_alive,
Traceable* root) {
HeapTracer* tracer = tracker.heap_tracer();
tracer->BeginPass();
tracer->TraceCommon(ref_alive);
tracer->Trace(root);
}
ObjectTracker::UnsetForTesting unset_;
ObjectTracker tracker;
};
TEST_F(HeapTracerTest, BasicFlow) {
TestObject obj1;
TestObject obj2;
TestObject obj3;
TestObject obj4;
// Ref-counted alive objects: obj1, obj4.
std::unordered_set<const Traceable*> ref_alive = {&obj1, &obj4};
// JavaScript alive objects: obj3.
RunTracer(ref_alive, &obj3);
ExpectAlive(&obj1, &obj3, &obj4);
ExpectDead(&obj2);
}
TEST_F(HeapTracerTest, TracesIndirectChildren) {
// Root (alive) object.
TestObjectWithBackingChild root;
// Indirect alive objects.
TestObjectWithBackingChild A, B, C, D, E, F, G;
root.member1 = &A;
root.member2 = &B;
root.member3 = &C;
A.member1 = &D;
A.member2 = &E;
B.member1 = &E;
C.member1 = &E;
C.member2 = &F;
E.member1 = &F;
E.member2 = &G;
// Dead objects
TestObjectWithBackingChild H, I, J, K;
H.member1 = &C;
H.member2 = &J;
I.member1 = &A;
I.member2 = &D;
// First test using JavaScript alive objects.
std::unordered_set<const Traceable*> ref_alive;
RunTracer(ref_alive, &root);
// Check first test results.
ExpectAlive(&root, &A, &B, &C, &D, &E, &F, &G);
ExpectDead(&H, &I, &J, &K);
// Try again using ref-counted alive
ref_alive = {&root};
RunTracer(ref_alive, nullptr);
// Check results of second test.
ExpectAlive(&root, &A, &B, &C, &D, &E, &F, &G);
ExpectDead(&H, &I, &J, &K);
}
TEST_F(HeapTracerTest, SupportsCircularReferences) {
// Root (alive) object.
TestObjectWithBackingChild root;
// Indirect alive objects.
TestObjectWithBackingChild A, B, C;
root.member1 = &A;
A.member1 = &B;
A.member2 = &C;
B.member1 = &root;
// First test using JavaScript alive objects.
std::unordered_set<const Traceable*> ref_alive;
RunTracer(ref_alive, &root);
// Check first test results.
ExpectAlive(&root, &A, &B, &C);
// Try again using ref-counted alive
ref_alive = {&root};
RunTracer(ref_alive, nullptr);
// Check results of second test.
ExpectAlive(&root, &A, &B, &C);
}
} // namespace memory
} // namespace shaka
<file_sep>/shaka/src/js/dom/dom_exception.cc
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.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.
#include "src/js/dom/dom_exception.h"
#include <glog/logging.h>
#include <unordered_map>
#include "src/util/macros.h"
namespace shaka {
namespace js {
namespace dom {
namespace {
// See: https://www.w3.org/TR/WebIDL-1/#error-names
#define DEFINE_MAPPING(code, msg, number) \
{ #code, msg, code, number }
struct ExceptionInfo {
const char* name;
const char* message;
ExceptionCode type;
int native_code;
} g_exception_map_[] = {
DEFINE_MAPPING(NotFoundError, "The object can not be found here.", 8),
DEFINE_MAPPING(NotSupportedError, "The operation is not supported.", 9),
DEFINE_MAPPING(InvalidStateError, "The object is in an invalid state.", 11),
DEFINE_MAPPING(QuotaExceededError, "The quota has been exceeded.", 22),
DEFINE_MAPPING(IndexSizeError, "The index is not in the allowed range.", 1),
DEFINE_MAPPING(HierarchyRequestError,
"The operation would yield an incorrect node tree.", 3),
DEFINE_MAPPING(DataCloneError, "The object can not be cloned.", 25),
DEFINE_MAPPING(UnknownError,
"The operation failed for an unknown transient reason (e.g. "
"out of memory).",
0),
DEFINE_MAPPING(TransactionInactiveError,
"A request was placed against a transaction which is "
"currently not active, or which is finished.",
0),
DEFINE_MAPPING(
ReadOnlyError,
"The mutating operation was attempted in a \"readonly\" transaction.",
0),
DEFINE_MAPPING(VersionError,
"An attempt was made to open a database using a lower "
"version than the existing version.",
0),
};
#undef DEFINE_MAPPING
const ExceptionInfo& GetInfo(ExceptionCode type) {
for (const auto& except : g_exception_map_) {
if (except.type == type)
return except;
}
LOG(FATAL) << "Unknown exception type: " << type;
}
} // namespace
DOMException::DOMException(ExceptionCode type)
: error_name(GetInfo(type).name),
message(GetInfo(type).message),
code(GetInfo(type).native_code) {}
DOMException::DOMException(ExceptionCode type, const std::string& message)
: error_name(GetInfo(type).name),
message(message),
code(GetInfo(type).native_code) {}
DOMException::DOMException(const std::string& name,
optional<std::string> message)
: error_name(name), message(message.value_or("")), code(0) {}
// \cond Doxygen_Skip
DOMException::~DOMException() {}
// \endcond Doxygen_Skip
DOMExceptionFactory::DOMExceptionFactory() {
AddReadOnlyProperty("name", &DOMException::error_name);
AddReadOnlyProperty("message", &DOMException::message);
AddReadOnlyProperty("code", &DOMException::code);
AddReadOnlyProperty("stack", &DOMException::stack);
}
} // namespace dom
} // namespace js
} // namespace shaka
| 7388948c0f5aa1e73accf1095693f305804a68c0 | [
"JavaScript",
"Makefile",
"Python",
"C",
"C++",
"Shell"
] | 195 | C++ | pepedeka/shaka-player-embedded | 779ed5a2c9057e27809d1e8409059afe6e9b2365 | 26e62d673f9742d46abab19089d8b3dde5a3b458 |
refs/heads/master | <file_sep>
#' helloworld
#'
#' @param
#' @param
#' @return prints \code{"hello world"}
#' @examples
#' helloworld()
#'
#' @export
helloworld <- function(){
print("hello world")
}
| 6dd67cea53c144011f732e6a984941a8e9bd7e94 | [
"R"
] | 1 | R | laurettemhlanga/helloworld | 399916f5e875a9027ac00a823ebc9d7bff038c16 | b705a0c117704b74e4922ac8ca020f74e620f0aa |
refs/heads/master | <file_sep>#!/bin/bash
if [ -z ${WORKDIR} ]; then
if [[ $0 =~ ^(.*)/[^/]+$ ]]; then
WORKDIR=${BASH_REMATCH[1]}
fi
if [[ $0 == "bash" ]]; then
WORKDIR="."
fi
fi
if [ -z ${SDDCDIR} ]; then
SDDCDIR=${WORKDIR}
fi
STATEDIR="${WORKDIR}/state"
if [ ! -d ${STATEDIR} ]; then
mkdir ${STATEDIR}
fi
source ${WORKDIR}/drv.core
PARAMS=$(cat ${SDDCDIR}/sddc.parameters)
DOMAIN=$(echo "${PARAMS}" | jq -r '.domain')
SPEC=$(echo "${PARAMS}" | jq -r '.endpoints[] | select(.type=="vrni")')
VRNIHOST=$(echo "$SPEC" | jq -r '.hostname')
if [[ ! "$VRNIHOST" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
if [[ ! "$VRNIHOST" =~ [.] ]]; then
VRNIHOST+=".$DOMAIN" #if not an IP or FQDN, append domain
fi
fi
VRNIUSER=$(echo "$SPEC" | jq -r '.username')
VRNIPASS=$(echo "$SPEC" | jq -r '.password')
VRNIONLINE=$(echo "$SPEC" | jq -r '.online')
VRNISESSION="${STATEDIR}/vrni.token.txt"
VRNIBASE="https://${VRNIHOST}/api/ni/"
function isSuccess {
local STRING=${1}
local SESSION=$VRNISESSION
local CODE=$(getCode "${STRING}")
printf "[$(ccyan "${CODE}")] - " 1>&2
case $CODE in
2[0-9][0-9])
printf "SUCCESS\n" 1>&2
;;
40[0-3])
printf "ERROR-AUTH\n" 1>&2
if [ -f "${SESSION}" ]; then
rm "${SESSION}"
fi
;;
*)
printf "ERROR\n" 1>&2
;;
esac
local BODY=$(getBody "${STRING}")
printf "%s\n" "${BODY}"
}
function getCode {
local STRING=${1}
if [[ $STRING =~ ^(.*)([0-9]{3})$ ]]; then
local BODY=${BASH_REMATCH[1]}
local CODE=${BASH_REMATCH[2]}
fi
printf "%s\n" "${CODE}"
}
function getBody {
local STRING=${1}
if [[ $STRING =~ ^(.*)([0-9]{3})$ ]]; then
local BODY=${BASH_REMATCH[1]}
local CODE=${BASH_REMATCH[2]}
fi
printf "%s\n" "${BODY}"
}
function vrniLogin {
local URL="https://${VRNIHOST}/api/ni/auth/token"
read -r -d '' VRNIBODY <<-CONFIG
{
"username": "${VRNIUSER}",
"password": "${<PASSWORD>}",
"domain": {
"domain_type": "LOCAL"
}
}
CONFIG
local RESPONSE=$(curl -k -w "%{http_code}" -X POST \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d "$VRNIBODY" \
"${URL}" 2>/dev/null)
local RESULT=$(isSuccess "${RESPONSE}")
local CODE=$(getCode "${RESPONSE}")
if [[ $CODE =~ 2..$ ]]; then
local TOKEN=$(echo $RESULT | jq -r '.token')
printf "%s\n" "${TOKEN}"
fi
}
function vrniSession {
local SESSION=$VRNISESSION
local ONLINE=$VRNIONLINE
if [[ "$ONLINE" == "true" ]]; then
local RUNFIND="$(find ${SESSION} -mmin -10 2>/dev/null)"
if [[ -z ${RUNFIND} ]]; then
printf "No valid session found, authenticating... " 1>&2
local LOGIN=$(vrniLogin)
if [[ -n ${LOGIN} ]]; then
echo "${LOGIN}" >"$SESSION"
fi
fi
fi
printf "%s\n" "$(cat "${SESSION}" 2>/dev/null)"
}
function vrniPost {
local URL=${1}
local BODY=${2}
if [[ "$VRNIONLINE" == "true" ]]; then
RESPONSE=$(curl -k -w "%{http_code}" -X POST \
-H "Content-Type: application/json" \
-H 'Accept: application/json' \
-H "Authorization: NetworkInsight $(cat ${VRNISESSION})" \
-d "$BODY" \
"${URL}" 2>/dev/null)
RESULT=$(isSuccess "${RESPONSE}")
else
printf "[$(ccyan "OFFLINE")] - SUCCESS\n" 1>&2
fi
printf "%s\n" "${RESULT}" | jq --tab .
}
function vrniGet {
local URL=${1}
local BASE=${VRNIBASE}
local ONLINE="${VRNIONLINE}"
local STATE
if [[ "$ONLINE" == "true" ]]; then
local FILE=$(getFile "${URL}" "${BASE}")
STATE="${STATEDIR}/vrni${FILE}"
RESPONSE=$(curl -k -w "%{http_code}" -X GET \
-H "Content-Type: application/json" \
-H 'Accept: application/json' \
-H "Authorization: NetworkInsight $(cat ${VRNISESSION})" \
"${URL}" 2>/dev/null)
RESULT=$(isSuccess "${RESPONSE}")
else
printf "[$(ccyan "OFFLINE")] - SUCCESS\n" 1>&2
RESULT=$(cat "${URL}")
STATE="${URL}"
fi
printf "%s\n" "${RESULT}" | jq --tab . >"${STATE}"
printf "%s\n" "${RESULT}" | jq --tab .
}
function buildURL {
local ENDPOINT="${1}"
local BASE="${VRNIBASE}"
local STATE="${STATEDIR}"
local ONLINE="${VRNIONLINE}"
if [[ "$ONLINE" == "true" ]]; then
local SUCCESS=$(vrniSession)
if [[ -n ${SUCCESS} ]]; then
URL="$BASE$ENDPOINT"
else
URL="" #failed to obtain valid session
fi
else
local FILE=$(getFile "${ENDPOINT}")
URL="${STATE}/vrni${FILE}"
fi
printf "$URL"
}
<file_sep>#!/bin/bash
APPID="${1}"
TOKEN=$(cat vrni.token.txt)
URL="https://vRNI/api/ni/groups/applications/${APPID}/tiers"
RESPONSE=$(curl -k -X GET --header 'Accept: application/json' \
--header "Authorization: NetworkInsight ${TOKEN}" \
"${URL}" 2>/dev/null)
printf "${RESPONSE}" | jq --tab .
<file_sep>#!/bin/bash
read -r -d '' BODY <<-CONFIG
{
"username": "<EMAIL>",
"password": "<PASSWORD>!",
"domain": {
"domain_type": "LOCAL"
}
}
CONFIG
URL='https://1.1.1.1/api/ni/auth/token'
RESPONSE=$(curl -k -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' \
-d "${BODY}" \
"${URL}" 2>/dev/null)
printf "${RESPONSE}" | jq --tab . 1>&2
printf "${RESPONSE}" | jq -r '.token' > vrni.token.txt
<file_sep>#!/bin/bash
if [[ $0 =~ ^(.*)/[^/]+$ ]]; then
WORKDIR=${BASH_REMATCH[1]}
fi
source ${WORKDIR}/drv.core
source ${WORKDIR}/drv.vrni.client
CALL=$1
if [[ -n "${VRNIHOST}" && "${CALL}" ]]; then
ITEM="groups/applications"
URL=$(buildURL "${ITEM}")
if [[ -n "${CALL}" ]]; then
URL+="/${CALL}/tiers"
fi
if [[ -n "${URL}" ]]; then
printf "[$(cgreen "INFO")]: vrni [$(cgreen "list")] ${ITEM} [$(cgreen "$URL")]... " 1>&2
vrniGet "${URL}"
fi
else
printf "[$(corange "ERROR")]: command usage: $(cgreen "applications.tiers.list") $(ccyan "<application.id>")\n" 1>&2
fi
<file_sep>#!/bin/bash
TOKEN=$(cat vrni.token.txt)
URL='https://vRNI/api/ni/groups/applications?size=10'
RESPONSE=$(curl -k -X GET --header 'Accept: application/json' \
--header "Authorization: NetworkInsight ${TOKEN}" \
"${URL}" 2>/dev/null)
printf "${RESPONSE}" | jq --tab .
APPID=$(printf "${RESPONSE}" | jq -r '.results[0].entity_id')
#printf "${APPID}"
<file_sep>#!/bin/bash
if [[ $0 =~ ^(.*)/[^/]+$ ]]; then
WORKDIR=${BASH_REMATCH[1]}
fi
source ${WORKDIR}/drv.core
source ${WORKDIR}/drv.vrni.client
## input driver
NODES=$(${WORKDIR}/drv.applications.list.sh)
# re-base to drv.node....?
function getStatus {
local NODEID=${1}
./drv.applications.list.sh "${NODEID}"
}
function buildNode {
local KEY=${1}
read -r -d '' JQSPEC <<-CONFIG # collapse into single line
.results[] | select(.entity_id=="${KEY}")
CONFIG
NODE=$(echo ${NODES} | jq -r "$JQSPEC")
# build node record
read -r -d '' NODESPEC <<-CONFIG
{
"entity_id": .entity_id,
"entity_type": .entity_type
}
CONFIG
NEWNODE=$(echo "${NODE}" | jq -r "${NODESPEC}")
## get node status
RESULT=$(getStatus "$KEY")
read -r -d '' STATUSSPEC <<-CONFIG
{
"name": .name,
"created_by": .created_by
}
CONFIG
NEWSTAT=$(echo "${RESULT}" | jq -r "${STATUSSPEC}")
# merge node and status
MYNODE="$(echo "${NEWNODE}${NEWSTAT}" | jq -s '. | add')"
printf "%s\n" "${MYNODE}"
}
FINAL="[]"
for KEY in $(echo ${NODES} | jq -r '.results[] | .entity_id'); do
MYNODE=$(buildNode "${KEY}")
FINAL="$(echo "${FINAL}[${MYNODE}]" | jq -s '. | add')"
done
printf "${FINAL}" | jq --tab .
<file_sep>#!/bin/bash
if [[ $0 =~ ^(.*)/[^/]+$ ]]; then
WORKDIR=${BASH_REMATCH[1]}
fi
source ${WORKDIR}/drv.core
source ${WORKDIR}/drv.vrni.client
CALL=$1
if [[ -n "${VRNIHOST}" ]]; then
ITEM="groups/applications"
URL=$(buildURL "${ITEM}")
if [[ -n "${CALL}" ]]; then
URL+="/${CALL}"
else
URL+="?size=20"
fi
if [[ -n "${URL}" ]]; then
printf "[$(cgreen "INFO")]: nsx [$(cgreen "list")] ${ITEM} [$(cgreen "$URL")]... " 1>&2
vrniGet "${URL}"
fi
fi
| ff0be89515cea6152efad98d794a8fde20dcfddd | [
"Shell"
] | 7 | Shell | regmiboyer/vRNI | 793da4524cb367c84b21c5ded74daa293b528753 | 10798202a1cf12a0047e2deb7e5ebf81dc407096 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.