CCMain.m 250 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "NCAutoUpload.h"
  35. #import "NCBridgeSwift.h"
  36. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  37. {
  38. tableMetadata *_metadata;
  39. BOOL _isRoot;
  40. BOOL _isViewDidLoad;
  41. BOOL _isOfflineServerUrl;
  42. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  43. BOOL _isSelectedMode;
  44. NSMutableDictionary *_selectedFileIDsMetadatas;
  45. NSUInteger _numSelectedFileIDsMetadatas;
  46. NSMutableArray *_queueSelector;
  47. NSMutableDictionary *_statusSwipeCell;
  48. UIImageView *_ImageTitleHomeCryptoCloud;
  49. UIView *_reMenuBackgroundView;
  50. UITapGestureRecognizer *_singleFingerTap;
  51. NSString *_directoryGroupBy;
  52. NSString *_directoryOrder;
  53. NSUInteger _failedAttempts;
  54. NSDate *_lockUntilDate;
  55. NSString *_fatherPermission;
  56. UIRefreshControl *_refreshControl;
  57. UIDocumentInteractionController *_docController;
  58. CCHud *_hud;
  59. CCHud *_hudDeterminate;
  60. // Datasource
  61. CCSectionDataSourceMetadata *_sectionDataSource;
  62. NSDate *_dateReadDataSource;
  63. // Search
  64. BOOL _isSearchMode;
  65. NSString *_searchFileName;
  66. NSMutableArray *_searchResultMetadatas;
  67. NSString *_depth;
  68. NSString *_noFilesSearchTitle;
  69. NSString *_noFilesSearchDescription;
  70. NSTimer *_timerWaitInput;
  71. // Login
  72. CCLoginWeb *_loginWeb;
  73. CCLogin *_loginVC;
  74. BOOL _loadingFolder;
  75. }
  76. @end
  77. @implementation CCMain
  78. #pragma --------------------------------------------------------------------------------------------
  79. #pragma mark ===== Init =====
  80. #pragma --------------------------------------------------------------------------------------------
  81. - (id)initWithCoder:(NSCoder *)aDecoder
  82. {
  83. if (self = [super initWithCoder:aDecoder]) {
  84. _directoryOrder = [CCUtility getOrderSettings];
  85. _directoryGroupBy = [CCUtility getGroupBySettings];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  90. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  91. }
  92. return self;
  93. }
  94. #pragma --------------------------------------------------------------------------------------------
  95. #pragma mark ===== View =====
  96. #pragma --------------------------------------------------------------------------------------------
  97. - (void)viewDidLoad
  98. {
  99. [super viewDidLoad];
  100. // init object
  101. _metadata = [tableMetadata new];
  102. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  104. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  105. _statusSwipeCell = [NSMutableDictionary new];
  106. _queueSelector = [NSMutableArray new];
  107. _isViewDidLoad = YES;
  108. _fatherPermission = @"";
  109. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  110. _searchResultMetadatas = [NSMutableArray new];
  111. _searchFileName = @"";
  112. _depth = @"infinity";
  113. _noFilesSearchTitle = @"";
  114. _noFilesSearchDescription = @"";
  115. // delegate
  116. self.tableView.delegate = self;
  117. self.tableView.tableFooterView = [UIView new];
  118. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  119. self.tableView.emptyDataSetDelegate = self;
  120. self.tableView.emptyDataSetSource = self;
  121. self.searchController.delegate = self;
  122. self.searchController.searchBar.delegate = self;
  123. [[CCNetworking sharedNetworking] settingDelegate:self];
  124. // Custom Cell
  125. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  126. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  127. // long press recognizer TableView
  128. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  129. [self.tableView addGestureRecognizer:longPressRecognizer];
  130. // Pull-to-Refresh
  131. [self createRefreshControl];
  132. // Register for 3D Touch Previewing if available
  133. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  134. {
  135. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  136. }
  137. // Back Button
  138. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  139. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  140. // reMenu Background
  141. _reMenuBackgroundView = [[UIView alloc] init];
  142. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  143. // if this is not Main (the Main uses inizializeMain)
  144. if (_isRoot == NO && app.activeAccount.length > 0) {
  145. // Settings this folder & delegate & Loading datasource
  146. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  147. // Load Datasource
  148. [self reloadDatasource:_serverUrl];
  149. // Read (File) Folder
  150. [self readFileReloadFolder];
  151. }
  152. // Title
  153. [self setTitle];
  154. // Search
  155. self.definesPresentationContext = YES;
  156. self.searchController.searchResultsUpdater = self;
  157. self.searchController.dimsBackgroundDuringPresentation = NO;
  158. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  159. [self.searchController.searchBar sizeToFit];
  160. self.searchController.searchBar.delegate = self;
  161. // Hide Search Filed on Load
  162. self.tableView.tableHeaderView = self.searchController.searchBar;
  163. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  164. }
  165. // Apparirà
  166. - (void)viewWillAppear:(BOOL)animated
  167. {
  168. [super viewWillAppear:animated];
  169. // test
  170. if (app.activeAccount.length == 0)
  171. return;
  172. // Settings this folder & delegate & Loading datasource
  173. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  174. [[CCNetworking sharedNetworking] settingDelegate:self];
  175. // Color
  176. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  177. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  178. if (_isSelectedMode)
  179. [self setUINavigationBarSelected];
  180. else
  181. [self setUINavigationBarDefault];
  182. // If not editing mode remove _selectedFileIDs
  183. if (!self.tableView.editing)
  184. [_selectedFileIDsMetadatas removeAllObjects];
  185. // Plus Button
  186. [app plusButtonVisibile:true];
  187. }
  188. // E' arrivato
  189. - (void)viewDidAppear:(BOOL)animated
  190. {
  191. [super viewDidAppear:animated];
  192. // Active Main
  193. app.activeMain = self;
  194. // Test viewDidLoad
  195. if (_isViewDidLoad) {
  196. _isViewDidLoad = NO;
  197. } else {
  198. if (app.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  199. // Load Datasource
  200. [self reloadDatasource:_serverUrl];
  201. // Read (file) Folder
  202. [self readFileReloadFolder];
  203. }
  204. }
  205. // Title
  206. [self setTitle];
  207. }
  208. - (void)viewWillDisappear:(BOOL)animated
  209. {
  210. [super viewWillDisappear:animated];
  211. [self closeAllMenu];
  212. }
  213. - (void)didReceiveMemoryWarning
  214. {
  215. [super didReceiveMemoryWarning];
  216. // Dispose of any resources that can be recreated.
  217. }
  218. - (BOOL)prefersStatusBarHidden
  219. {
  220. return NO;
  221. }
  222. // detect scroll for remove keyboard in search mode
  223. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  224. {
  225. if (_isSearchMode && scrollView == self.tableView) {
  226. [self.searchController.searchBar endEditing:YES];
  227. }
  228. }
  229. - (void)changeTheming
  230. {
  231. if (self.isViewLoaded && self.view.window)
  232. [app changeTheming:self];
  233. // Refresh control
  234. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  235. // Reload Table View
  236. [self tableViewReloadData];
  237. }
  238. #pragma --------------------------------------------------------------------------------------------
  239. #pragma mark ===== Initizlize Mail =====
  240. #pragma --------------------------------------------------------------------------------------------
  241. - (void)initializeMain:(NSNotification *)notification
  242. {
  243. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  244. _directoryGroupBy = nil;
  245. _directoryOrder = nil;
  246. _dateReadDataSource = nil;
  247. // test
  248. if (app.activeAccount.length == 0)
  249. return;
  250. if ([app.listMainVC count] == 0 || _isRoot) {
  251. // This is Root home main add list
  252. appDelegate.homeMain = self;
  253. _isRoot = YES;
  254. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  255. appDelegate.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  256. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  257. // go Home
  258. [self.navigationController popToRootViewControllerAnimated:NO];
  259. // Crypto Mode
  260. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  261. appDelegate.isCryptoCloudMode = NO;
  262. } else {
  263. appDelegate.isCryptoCloudMode = YES;
  264. }
  265. _isFolderEncrypted = NO;
  266. // setting Networking
  267. [[CCNetworking sharedNetworking] settingDelegate:self];
  268. [[CCNetworking sharedNetworking] settingAccount];
  269. // Remove search mode
  270. [self cancelSearchBar];
  271. // populate shared Link & User
  272. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  273. if (results) {
  274. appDelegate.sharesLink = results[0];
  275. appDelegate.sharesUserAndGroup = results[1];
  276. }
  277. // Load Datasource
  278. [self reloadDatasource:_serverUrl];
  279. // Read (File) Folder
  280. [self readFileReloadFolder];
  281. // Setting Theming
  282. [app settingThemingColorBrand];
  283. // Load photo datasorce
  284. if (appDelegate.activePhotos)
  285. [appDelegate.activePhotos reloadDatasourceForced];
  286. // remove all of detail
  287. if (appDelegate.activeDetail)
  288. [appDelegate.activeDetail removeAllView];
  289. // remove all Notification Messages
  290. [appDelegate.listOfNotifications removeAllObjects];
  291. // Initializations
  292. [appDelegate applicationInitialized];
  293. } else {
  294. // reload datasource
  295. [self reloadDatasource:_serverUrl];
  296. }
  297. }
  298. #pragma --------------------------------------------------------------------------------------------
  299. #pragma mark ==== DZNEmptyDataSetSource ====
  300. #pragma --------------------------------------------------------------------------------------------
  301. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  302. {
  303. if (_loadingFolder)
  304. return NO;
  305. else
  306. return YES;
  307. }
  308. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  309. {
  310. return [UIColor whiteColor];
  311. }
  312. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  313. {
  314. if (_isSearchMode)
  315. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] color:[NCBrandColor sharedInstance].brand];
  316. else
  317. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  318. }
  319. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  320. {
  321. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  322. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  323. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  324. activityView.color = [NCBrandColor sharedInstance].brand;
  325. [activityView startAnimating];
  326. return activityView;
  327. }
  328. return nil;
  329. }
  330. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  331. {
  332. NSString *text;
  333. if (_isSearchMode) {
  334. text = _noFilesSearchTitle;
  335. } else {
  336. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  337. }
  338. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  339. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  340. }
  341. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  342. {
  343. NSString *text;
  344. if (_isSearchMode) {
  345. text = _noFilesSearchDescription;
  346. } else {
  347. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  348. }
  349. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  350. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  351. paragraph.alignment = NSTextAlignmentCenter;
  352. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  353. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  354. }
  355. #pragma --------------------------------------------------------------------------------------------
  356. #pragma mark ===== Text Field =====
  357. #pragma --------------------------------------------------------------------------------------------
  358. - (void)minCharTextFieldDidChange:(UITextField *)sender
  359. {
  360. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  361. if (alertController)
  362. {
  363. UITextField *fileName = alertController.textFields.firstObject;
  364. UIAlertAction *okAction = alertController.actions.lastObject;
  365. okAction.enabled = fileName.text.length > 0;
  366. }
  367. }
  368. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  369. [textField selectAll:textField];
  370. }
  371. #pragma --------------------------------------------------------------------------------------------
  372. #pragma mark ===== Graphic Window =====
  373. #pragma --------------------------------------------------------------------------------------------
  374. - (void)createRefreshControl
  375. {
  376. _refreshControl = [UIRefreshControl new];
  377. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  378. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  379. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  380. [self setRefreshControl:_refreshControl];
  381. }
  382. - (void)deleteRefreshControl
  383. {
  384. [_refreshControl endRefreshing];
  385. self.refreshControl = nil;
  386. }
  387. - (void)refreshControlTarget
  388. {
  389. [self readFolder:_serverUrl];
  390. // Actuate `Peek` feedback (weak boom)
  391. AudioServicesPlaySystemSound(1519);
  392. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  393. }
  394. - (void)setTitle
  395. {
  396. // Color text self.navigationItem.title
  397. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  398. if (_isSelectedMode) {
  399. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  400. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  401. self.navigationItem.titleView = nil;
  402. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  403. } else {
  404. // we are in home : LOGO BRAND
  405. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  406. self.navigationItem.title = nil;
  407. if ([app.reachability isReachable] == NO)
  408. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  409. else
  410. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  411. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  412. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  413. [singleTap setNumberOfTapsRequired:1];
  414. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  415. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  416. } else {
  417. self.navigationItem.title = _titleMain;
  418. }
  419. }
  420. }
  421. - (void)setUINavigationBarDefault
  422. {
  423. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  424. UIBarButtonItem *buttonMore, *buttonNotification;
  425. // =
  426. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  427. buttonMore.enabled = true;
  428. // <
  429. self.navigationController.navigationBar.hidden = NO;
  430. // Notification
  431. if ([app.listOfNotifications count] > 0) {
  432. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  433. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  434. buttonNotification.enabled = true;
  435. }
  436. if (buttonNotification)
  437. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  438. else
  439. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  440. self.navigationItem.leftBarButtonItem = nil;
  441. }
  442. - (void)setUINavigationBarSelected
  443. {
  444. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  445. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  446. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  447. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  448. self.navigationItem.leftBarButtonItem = leftButton;
  449. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  450. }
  451. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  452. {
  453. [self closeAllMenu];
  454. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  455. }];
  456. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  457. }
  458. - (void)cancelSelect
  459. {
  460. [self tableViewSelect:NO];
  461. [app.reSelectMenu close];
  462. }
  463. - (void)closeAllMenu
  464. {
  465. // close Menu
  466. [app.reSelectMenu close];
  467. [app.reMainMenu close];
  468. // Close Menu Logo
  469. [CCMenuAccount dismissMenu];
  470. }
  471. #pragma --------------------------------------------------------------------------------------------
  472. #pragma mark ===== Document Picker =====
  473. #pragma --------------------------------------------------------------------------------------------
  474. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  475. {
  476. NSLog(@"Cancelled");
  477. }
  478. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  479. {
  480. NSLog(@"Cancelled");
  481. }
  482. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  483. {
  484. documentPicker.delegate = self;
  485. [self presentViewController:documentPicker animated:YES completion:nil];
  486. }
  487. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  488. {
  489. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  490. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  491. __block NSError *error;
  492. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  493. NSString *fileName = [url lastPathComponent];
  494. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  495. NSData *data = [NSData dataWithContentsOfURL:newURL];
  496. if (data && error == nil) {
  497. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  498. // Upload File
  499. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  500. } else {
  501. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  502. }
  503. } else {
  504. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  505. }
  506. }];
  507. }
  508. }
  509. - (void)openImportDocumentPicker
  510. {
  511. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  512. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  513. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  514. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  515. documentProviderMenu.delegate = self;
  516. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  517. }
  518. #pragma --------------------------------------------------------------------------------------------
  519. #pragma mark ===== Assets Picker =====
  520. #pragma --------------------------------------------------------------------------------------------
  521. -(void)dismissFormUploadAssets
  522. {
  523. [self reloadDatasource];
  524. }
  525. - (void)openAssetsPickerController
  526. {
  527. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  528. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  529. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  530. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  531. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  532. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  533. dispatch_async(dispatch_get_main_queue(), ^{
  534. // init picker
  535. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  536. // set delegate
  537. picker.delegate = self;
  538. // to show selection order
  539. //picker.showsSelectionIndex = YES;
  540. // to present picker as a form sheet in iPad
  541. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  542. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  543. // present picker
  544. [self presentViewController:picker animated:YES completion:nil];
  545. });
  546. }];
  547. }
  548. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  549. {
  550. [picker dismissViewControllerAnimated:YES completion:^{
  551. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session delegate:self];
  552. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  553. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  554. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  555. [self presentViewController:navigationController animated:YES completion:nil];
  556. }];
  557. }
  558. #pragma --------------------------------------------------------------------------------------------
  559. #pragma mark ===== Create New (OpenModel) =====
  560. #pragma --------------------------------------------------------------------------------------------
  561. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  562. {
  563. UIViewController *viewController;
  564. NSString *fileName, *uuid, *fileID, *serverUrl;
  565. NSIndexPath *index = [self.tableView indexPathForSelectedRow];
  566. [self.tableView deselectRowAtIndexPath:index animated:NO];
  567. if (isnew) {
  568. fileName = nil;
  569. uuid = [CCUtility getUUID];
  570. fileID = nil;
  571. serverUrl = _serverUrl;
  572. } else {
  573. fileName = _metadata.fileName;
  574. uuid = _metadata.uuid;
  575. fileID = _metadata.fileID;
  576. serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  577. }
  578. if ([tipo isEqualToString:@"cartadicredito"])
  579. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  580. if ([tipo isEqualToString:@"bancomat"])
  581. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  582. if ([tipo isEqualToString:@"contocorrente"])
  583. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  584. if ([tipo isEqualToString:@"accountweb"])
  585. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  586. if ([tipo isEqualToString:@"patenteguida"])
  587. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  588. if ([tipo isEqualToString:@"cartaidentita"])
  589. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  590. if ([tipo isEqualToString:@"passaporto"])
  591. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  592. if ([tipo isEqualToString:@"note"]) {
  593. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  594. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  595. [self presentViewController:navigationController animated:YES completion:nil];
  596. } else {
  597. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  598. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  599. [self presentViewController:navigationController animated:YES completion:nil];
  600. }
  601. }
  602. // New folder or new photo or video
  603. - (void)returnCreate:(NSInteger)type
  604. {
  605. switch (type) {
  606. /* PLAIN */
  607. case k_returnCreateFolderPlain: {
  608. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  609. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  610. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  611. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  612. }];
  613. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  614. NSLog(@"Cancel action");
  615. }];
  616. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  617. UITextField *fileName = alertController.textFields.firstObject;
  618. [self createFolder:fileName.text autoUploadDirectory:NO];
  619. }];
  620. okAction.enabled = NO;
  621. [alertController addAction:cancelAction];
  622. [alertController addAction:okAction];
  623. [self presentViewController:alertController animated:YES completion:nil];
  624. }
  625. break;
  626. case k_returnCreateFotoVideoPlain: {
  627. _isPickerCriptate = false;
  628. [self openAssetsPickerController];
  629. }
  630. break;
  631. case k_returnCreateFilePlain: {
  632. _isPickerCriptate = false;
  633. [self openImportDocumentPicker];
  634. }
  635. break;
  636. /* ENCRYPTED */
  637. case k_returnCreateFolderEncrypted: {
  638. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  639. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  640. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  641. }];
  642. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  643. NSLog(@"Cancel action");
  644. }];
  645. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  646. UITextField *fileName = alertController.textFields.firstObject;
  647. [self createFolderEncrypted:fileName.text];
  648. }];
  649. okAction.enabled = NO;
  650. [alertController addAction:cancelAction];
  651. [alertController addAction:okAction];
  652. [self presentViewController:alertController animated:YES completion:nil];
  653. }
  654. break;
  655. case k_returnCreateFotoVideoEncrypted: {
  656. _isPickerCriptate = true;
  657. [self openAssetsPickerController];
  658. }
  659. break;
  660. case k_returnCreateFileEncrypted: {
  661. _isPickerCriptate = true;
  662. [self openImportDocumentPicker];
  663. }
  664. break;
  665. /* UTILITY */
  666. case k_returnNote:
  667. [self openModel:@"note" isNew:true];
  668. break;
  669. case k_returnAccountWeb:
  670. [self openModel:@"accountweb" isNew:true];
  671. break;
  672. /* BANK */
  673. case k_returnCartaDiCredito:
  674. [self openModel:@"cartadicredito" isNew:true];
  675. break;
  676. case k_returnBancomat:
  677. [self openModel:@"bancomat" isNew:true];
  678. break;
  679. case k_returnContoCorrente:
  680. [self openModel:@"contocorrente" isNew:true];
  681. break;
  682. /* DOCUMENT */
  683. case k_returnPatenteGuida:
  684. [self openModel:@"patenteguida" isNew:true];
  685. break;
  686. case k_returnCartaIdentita:
  687. [self openModel:@"cartaidentita" isNew:true];
  688. break;
  689. case k_returnPassaporto:
  690. [self openModel:@"passaporto" isNew:true];
  691. break;
  692. }
  693. }
  694. #pragma --------------------------------------------------------------------------------------------
  695. #pragma mark ===== Save selected File =====
  696. #pragma --------------------------------------------------------------------------------------------
  697. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  698. {
  699. if (error)
  700. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  701. else
  702. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  703. }
  704. - (void)saveSelectedFiles
  705. {
  706. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  707. return;
  708. NSLog(@"[LOG] Start download selected files ...");
  709. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  710. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  711. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  712. for (tableMetadata *metadata in metadatas) {
  713. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  714. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  715. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  716. }
  717. }
  718. [_hud hideHud];
  719. });
  720. [self tableViewSelect:NO];
  721. }
  722. #pragma --------------------------------------------------------------------------------------------
  723. #pragma mark ===== Change Password =====
  724. #pragma --------------------------------------------------------------------------------------------
  725. - (void) loginSuccess:(NSInteger)loginType
  726. {
  727. [self readFolder:_serverUrl];
  728. }
  729. - (void)changePasswordAccount
  730. {
  731. // Brand
  732. if ([NCBrandOptions sharedInstance].use_login_web) {
  733. _loginWeb = [CCLoginWeb new];
  734. _loginWeb.delegate = self;
  735. _loginWeb.loginType = loginModifyPasswordUser;
  736. dispatch_async(dispatch_get_main_queue(), ^ {
  737. [_loginWeb presentModalWithDefaultTheme:self];
  738. });
  739. } else {
  740. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  741. _loginVC.delegate = self;
  742. _loginVC.loginType = loginModifyPasswordUser;
  743. [self presentViewController:_loginVC animated:YES completion:nil];
  744. }
  745. }
  746. #pragma mark -
  747. #pragma --------------------------------------------------------------------------------------------
  748. #pragma mark ===== Peek & Pop =====
  749. #pragma --------------------------------------------------------------------------------------------
  750. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  751. {
  752. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  753. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  754. if (metadata.thumbnailExists && !metadata.cryptated) {
  755. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  756. if (cell) {
  757. previewingContext.sourceRect = cell.frame;
  758. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  759. vc.delegate = self;
  760. vc.metadata = metadata;
  761. return vc;
  762. }
  763. }
  764. return nil;
  765. }
  766. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  767. {
  768. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  769. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  770. }
  771. #pragma mark -
  772. #pragma --------------------------------------------------------------------------------------------
  773. #pragma mark ==== External Sites ====
  774. #pragma --------------------------------------------------------------------------------------------
  775. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  776. {
  777. [[NCManageDatabase sharedInstance] deleteExternalSites];
  778. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  779. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  780. }
  781. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  782. {
  783. NSLog(@"[LOG] No External Sites found");
  784. }
  785. #pragma --------------------------------------------------------------------------------------------
  786. #pragma mark ==== Activity ====
  787. #pragma --------------------------------------------------------------------------------------------
  788. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  789. {
  790. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  791. // Reload Activity Data Source
  792. [app.activeActivity reloadDatasource];
  793. }
  794. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  795. {
  796. NSLog(@"[LOG] No Activity found");
  797. }
  798. #pragma --------------------------------------------------------------------------------------------
  799. #pragma mark ==== Notification ====
  800. #pragma --------------------------------------------------------------------------------------------
  801. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  802. {
  803. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  804. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  805. // Order by date
  806. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  807. OCNotifications *notification1 = obj1, *notification2 = obj2;
  808. return [notification2.date compare: notification1.date];
  809. }];
  810. // verify if listOfNotifications is changed
  811. NSString *old = @"", *new = @"";
  812. for (OCNotifications *notification in listOfNotifications)
  813. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  814. for (OCNotifications *notification in appDelegate.listOfNotifications)
  815. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  816. if (![new isEqualToString:old]) {
  817. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  818. // reload Notification view
  819. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  820. }
  821. // Update NavigationBar
  822. if (!_isSelectedMode) {
  823. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  824. }
  825. });
  826. }
  827. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  828. {
  829. // Update NavigationBar
  830. if (!_isSelectedMode)
  831. [self setUINavigationBarDefault];
  832. }
  833. - (void)viewNotification
  834. {
  835. if ([app.listOfNotifications count] > 0) {
  836. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  837. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  838. [self presentViewController:notificationVC animated:YES completion:nil];
  839. }
  840. }
  841. #pragma --------------------------------------------------------------------------------------------
  842. #pragma mark ==== User Profile ====
  843. #pragma --------------------------------------------------------------------------------------------
  844. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  845. {
  846. if (errorCode == 401)
  847. [self changePasswordAccount];
  848. }
  849. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  850. {
  851. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  852. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  853. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  854. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  855. if (avatar)
  856. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  857. else
  858. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  859. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  860. });
  861. }
  862. #pragma --------------------------------------------------------------------------------------------
  863. #pragma mark ==== Capabilities ====
  864. #pragma --------------------------------------------------------------------------------------------
  865. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  866. {
  867. // Change Theming color
  868. [app settingThemingColorBrand];
  869. if (errorCode == 401)
  870. [self changePasswordAccount];
  871. }
  872. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  873. {
  874. // Update capabilities db
  875. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  876. // ------ THEMING -----------------------------------------------------------------------
  877. // Download Theming Background & Change Theming color
  878. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  879. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  880. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  881. if (themingBackground)
  882. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  883. else
  884. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  885. }
  886. dispatch_async(dispatch_get_main_queue(), ^{
  887. [app settingThemingColorBrand];
  888. });
  889. });
  890. // ------ SEARCH ------------------------------------------------------------------------
  891. // Search bar if change version
  892. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  893. [self cancelSearchBar];
  894. }
  895. // ------ GET SERVICE SERVER ------------------------------------------------------------
  896. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  897. // Read External Sites
  898. if (capabilities.isExternalSitesServerEnabled) {
  899. metadataNet.action = actionGetExternalSitesServer;
  900. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  901. }
  902. // Read Share
  903. if (capabilities.isFilesSharingAPIEnabled) {
  904. [app.sharesID removeAllObjects];
  905. metadataNet.action = actionReadShareServer;
  906. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  907. }
  908. // Read Notification
  909. metadataNet.action = actionGetNotificationServer;
  910. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  911. // Read User Profile
  912. metadataNet.action = actionGetUserProfile;
  913. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  914. // Read Activity
  915. metadataNet.action = actionGetActivityServer;
  916. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  917. }
  918. #pragma mark -
  919. #pragma --------------------------------------------------------------------------------------------
  920. #pragma mark ==== Request Server Information ====
  921. #pragma --------------------------------------------------------------------------------------------
  922. - (void)requestServerCapabilities
  923. {
  924. // test
  925. if (app.activeAccount.length == 0)
  926. return;
  927. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  928. metadataNet.action = actionGetCapabilities;
  929. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  930. }
  931. #pragma mark -
  932. #pragma --------------------------------------------------------------------------------------------
  933. #pragma mark ==== Middleware Ping ====
  934. #pragma --------------------------------------------------------------------------------------------
  935. - (void)middlewarePing
  936. {
  937. // test
  938. if (app.activeAccount.length == 0)
  939. return;
  940. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  941. metadataNet.action = actionMiddlewarePing;
  942. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  943. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  944. }
  945. #pragma mark -
  946. #pragma --------------------------------------------------------------------------------------------
  947. #pragma mark ==== Download Thumbnail Delegate ====
  948. #pragma --------------------------------------------------------------------------------------------
  949. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  950. {
  951. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  952. if ([self indexPathIsValid:indexPath]) {
  953. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  954. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  955. }
  956. }
  957. #pragma --------------------------------------------------------------------------------------------
  958. #pragma mark ==== Download ====
  959. #pragma --------------------------------------------------------------------------------------------
  960. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  961. {
  962. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  963. // File do not exists on server, remove in local
  964. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  965. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  966. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  967. if (metadata.directory && serverUrl) {
  968. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  969. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  970. }
  971. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  972. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  973. }
  974. if ([selector isEqualToString:selectorLoadViewImage]) {
  975. dispatch_async(dispatch_get_main_queue(), ^{
  976. // Updating Detail
  977. if (app.activeDetail)
  978. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  979. // Updating Photos
  980. if (app.activePhotos)
  981. [app.activePhotos downloadFileFailure:errorCode];
  982. });
  983. } else {
  984. if (errorCode != kCFURLErrorCancelled)
  985. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  986. }
  987. [self reloadDatasource:serverUrl];
  988. }
  989. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  990. {
  991. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  992. if (metadata == nil)
  993. return;
  994. // Download
  995. if ([selector isEqualToString:selectorDownloadFile]) {
  996. [self reloadDatasource:serverUrl];
  997. }
  998. // Synchronized
  999. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1000. [self reloadDatasource:serverUrl];
  1001. }
  1002. // add Favorite
  1003. if ([selector isEqualToString:selectorAddFavorite]) {
  1004. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1005. }
  1006. // encrypted file
  1007. if ([selector isEqualToString:selectorEncryptFile]) {
  1008. [self encryptedFile:metadata];
  1009. }
  1010. // decrypted file
  1011. if ([selector isEqualToString:selectorDecryptFile]) {
  1012. [self decryptedFile:metadata];
  1013. }
  1014. // open View File
  1015. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1016. [self reloadDatasource:serverUrl];
  1017. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1018. selector = selectorOpenIn;
  1019. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1020. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1021. selector = selectorOpenIn;
  1022. } else {
  1023. _metadata = metadata;
  1024. if ([self shouldPerformSegue])
  1025. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1026. }
  1027. }
  1028. // addLocal
  1029. if ([selector isEqualToString:selectorAddLocal]) {
  1030. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1031. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1032. [CCGraphics saveIcoWithEtag:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1033. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  1034. [self reloadDatasource:serverUrl];
  1035. }
  1036. // Open with...
  1037. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1038. [self reloadDatasource:serverUrl];
  1039. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1040. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1041. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1042. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1043. _docController.delegate = self;
  1044. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1045. }
  1046. // Save to Photo Album
  1047. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1048. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1049. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1050. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1051. if (image)
  1052. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1053. else
  1054. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1055. }
  1056. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1057. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1058. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1059. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1060. } else {
  1061. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1062. }
  1063. }
  1064. [self reloadDatasource:serverUrl];
  1065. }
  1066. // Copy File
  1067. if ([selector isEqualToString:selectorLoadCopy]) {
  1068. [self reloadDatasource:serverUrl];
  1069. [self copyFileToPasteboard:metadata];
  1070. }
  1071. // download and view a template
  1072. if ([selector isEqualToString:selectorLoadModelView]) {
  1073. // se è un template aggiorniamo anche nel FileSystem
  1074. if ([metadata.type isEqualToString: k_metadataType_template]) {
  1075. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadata.fileID date:metadata.date exifDate:nil exifLatitude:nil exifLongitude:nil fileName:nil fileNamePrint:metadata.fileNamePrint];
  1076. }
  1077. [self openModel:metadata.model isNew:false];
  1078. [self reloadDatasource:serverUrl];
  1079. }
  1080. //download file plist
  1081. if ([selector isEqualToString:selectorLoadPlist]) {
  1082. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1083. long countSelectorLoadPlist = 0;
  1084. for (NSOperation *operation in [app.netQueue operations]) {
  1085. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1086. countSelectorLoadPlist++;
  1087. }
  1088. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl]]) {
  1089. dispatch_async(dispatch_get_main_queue(), ^{
  1090. [self reloadDatasource:serverUrl];
  1091. });
  1092. }
  1093. });
  1094. }
  1095. //selectorLoadViewImage
  1096. if ([selector isEqualToString:selectorLoadViewImage]) {
  1097. // Detail
  1098. if (app.activeDetail)
  1099. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1100. // Photos
  1101. if (app.activePhotos)
  1102. [app.activePhotos downloadFileSuccess:metadata];
  1103. [self reloadDatasource:serverUrl];
  1104. }
  1105. // if exists postselector call self with selectorPost
  1106. if ([selectorPost length] > 0)
  1107. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1108. }
  1109. - (void)downloadSelectedFilesFolders
  1110. {
  1111. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1112. return;
  1113. NSLog(@"[LOG] Start download selected ...");
  1114. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1115. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1116. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1117. for (tableMetadata *metadata in selectedMetadatas) {
  1118. if ([metadata.type isEqualToString: k_metadataType_file]) {
  1119. if (metadata.directory) {
  1120. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1121. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1122. [[CCSynchronize sharedSynchronize] synchronizedFolder:serverUrl selector:selectorReadFolderWithDownload];
  1123. } else {
  1124. [[CCSynchronize sharedSynchronize] synchronizedFile:metadata selector:selectorReadFileWithDownload];
  1125. }
  1126. }
  1127. }
  1128. [_hud hideHud];
  1129. });
  1130. [self tableViewSelect:NO];
  1131. }
  1132. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1133. {
  1134. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", app.activeAccount, directoryID] sorted:nil ascending:NO];
  1135. for (tableMetadata *metadata in metadatas) {
  1136. if ([CCUtility isCryptoPlistString:metadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]] == NO && [metadata.session length] == 0) {
  1137. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1138. metadataNet.action = actionDownloadFile;
  1139. metadataNet.downloadData = NO;
  1140. metadataNet.downloadPlist = YES;
  1141. metadataNet.fileID = metadata.fileID;
  1142. metadataNet.selector = selectorLoadPlist;
  1143. metadataNet.serverUrl = serverUrl;
  1144. metadataNet.session = k_download_session_foreground;
  1145. metadataNet.taskStatus = k_taskStatusResume;
  1146. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1147. //[[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selectorLoadPlist selectorPost:nil session:k_download_session_foreground taskStatus:k_taskStatusResume delegate:self];
  1148. }
  1149. }
  1150. }
  1151. #pragma --------------------------------------------------------------------------------------------
  1152. #pragma mark ===== Upload new Photos/Videos =====
  1153. #pragma --------------------------------------------------------------------------------------------
  1154. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1155. {
  1156. // Auto Upload
  1157. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll]) {
  1158. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1159. // ONLY BACKGROUND
  1160. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1161. } else {
  1162. // ONLY FOREFROUND
  1163. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1164. }
  1165. }
  1166. // Read File test do not exists
  1167. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1168. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1169. // reUpload
  1170. if (metadata)
  1171. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1172. }
  1173. // Print error
  1174. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1175. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1176. }
  1177. [self reloadDatasource:serverUrl];
  1178. }
  1179. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1180. {
  1181. // Auto Upload
  1182. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll]) {
  1183. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1184. // ONLY BACKGROUND
  1185. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1186. } else {
  1187. // ONLY FOREFROUND
  1188. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1189. }
  1190. }
  1191. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1192. [self readFolder:serverUrl];
  1193. } else {
  1194. [self reloadDatasource:serverUrl];
  1195. }
  1196. }
  1197. //
  1198. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1199. //
  1200. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1201. {
  1202. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1203. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1204. });
  1205. }
  1206. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1207. {
  1208. NSArray *assets = [arguments objectAtIndex:0];
  1209. NSString *serverUrl = [arguments objectAtIndex:1];
  1210. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1211. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1212. NSString *session = [arguments objectAtIndex:4];
  1213. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1214. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1215. // Create the folder for Photos & if request the subfolders
  1216. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1217. return;
  1218. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1219. for (PHAsset *asset in assets) {
  1220. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1221. NSDate *assetDate = asset.creationDate;
  1222. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1223. // Create serverUrl if use sub folder
  1224. if (useSubFolder) {
  1225. [formatter setDateFormat:@"yyyy"];
  1226. NSString *yearString = [formatter stringFromDate:assetDate];
  1227. [formatter setDateFormat:@"MM"];
  1228. NSString *monthString = [formatter stringFromDate:assetDate];
  1229. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1230. }
  1231. // Check if is in upload
  1232. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1233. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1234. if ([isRecordInSessions count] > 0) {
  1235. // next upload
  1236. continue;
  1237. } else {
  1238. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1239. if (cryptated) {
  1240. metadataNet.action = actionUploadAsset;
  1241. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1242. metadataNet.cryptated = cryptated;
  1243. metadataNet.fileName = fileName;
  1244. metadataNet.session = session;
  1245. metadataNet.selector = selectorUploadFile;
  1246. metadataNet.selectorPost = nil;
  1247. metadataNet.serverUrl = serverUrl;
  1248. metadataNet.taskStatus = k_taskStatusResume;
  1249. } else {
  1250. metadataNet.action = actionReadFile;
  1251. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1252. metadataNet.cryptated = cryptated;
  1253. metadataNet.fileName = fileName;
  1254. metadataNet.session = session;
  1255. metadataNet.selector = selectorReadFileUploadFile;
  1256. metadataNet.serverUrl = serverUrl;
  1257. }
  1258. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1259. }
  1260. }
  1261. }
  1262. #pragma --------------------------------------------------------------------------------------------
  1263. #pragma mark ==== Read File ====
  1264. #pragma --------------------------------------------------------------------------------------------
  1265. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1266. {
  1267. // Read Folder
  1268. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1269. //[self readFolderWithForced:NO serverUrl:metadataNet.serverUrl];
  1270. }
  1271. // UploadFile
  1272. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1273. // File not exists
  1274. if (errorCode == 404) {
  1275. metadataNet.action = actionUploadAsset;
  1276. metadataNet.errorCode = 0;
  1277. metadataNet.selector = selectorUploadFile;
  1278. metadataNet.selectorPost = nil;
  1279. metadataNet.taskStatus = k_taskStatusResume;
  1280. if ([metadataNet.session containsString:@"wwan"])
  1281. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1282. else
  1283. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1284. } else {
  1285. // error ho many retry befor notification and go to on next asses
  1286. if (metadataNet.errorRetry < 3) {
  1287. // Retry read file
  1288. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1289. } else {
  1290. // STOP check file, view message error
  1291. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1292. }
  1293. }
  1294. }
  1295. }
  1296. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1297. {
  1298. // Read Folder
  1299. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1300. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1301. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1302. [self readFolder:metadataNet.serverUrl];
  1303. }
  1304. }
  1305. // UploadFile
  1306. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1307. metadataNet.action = actionUploadAsset;
  1308. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1309. metadataNet.selector = selectorUploadFile;
  1310. metadataNet.selectorPost = nil;
  1311. metadataNet.taskStatus = k_taskStatusResume;
  1312. if ([metadataNet.session containsString:@"wwan"])
  1313. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1314. else
  1315. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1316. }
  1317. }
  1318. - (void)readFileReloadFolder
  1319. {
  1320. if (!_serverUrl || !app.activeAccount || app.maintenanceMode)
  1321. return;
  1322. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1323. metadataNet.action = actionReadFile;
  1324. metadataNet.priority = NSOperationQueuePriorityHigh;
  1325. metadataNet.selector = selectorReadFileReloadFolder;
  1326. metadataNet.serverUrl = _serverUrl;
  1327. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1328. }
  1329. #pragma --------------------------------------------------------------------------------------------
  1330. #pragma mark ==== Read Folder ====
  1331. #pragma --------------------------------------------------------------------------------------------
  1332. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1333. {
  1334. // verify active user
  1335. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1336. _loadingFolder = NO;
  1337. [self tableViewReloadData];
  1338. [_refreshControl endRefreshing];
  1339. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1340. if (message && [record.account isEqualToString:metadataNet.account])
  1341. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1342. [self reloadDatasource:metadataNet.serverUrl];
  1343. if (errorCode == 401)
  1344. [self changePasswordAccount];
  1345. }
  1346. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1347. {
  1348. // verify active user
  1349. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1350. if (![record.account isEqualToString:metadataNet.account])
  1351. return;
  1352. // save father e update permission
  1353. if(!_isSearchMode && metadataFolder)
  1354. _fatherPermission = metadataFolder.permissions;
  1355. NSArray *recordsInSessions;
  1356. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1357. if (_isSearchMode) {
  1358. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1359. } else {
  1360. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag];
  1361. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1362. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1363. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1364. }
  1365. for (tableMetadata *metadata in metadatas) {
  1366. // type of file
  1367. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1368. // if crypto do not insert
  1369. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1370. // verify if the record encrypted has plist + crypto
  1371. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1372. BOOL isCryptoComplete = NO;
  1373. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1374. for (tableMetadata *completeMetadata in metadatas) {
  1375. if (completeMetadata.cryptated == NO) continue;
  1376. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1377. isCryptoComplete = YES;
  1378. break;
  1379. }
  1380. }
  1381. if (isCryptoComplete == NO) continue;
  1382. }
  1383. // verify if the record is in download/upload progress
  1384. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1385. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1386. // is in Download or Upload
  1387. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1388. continue;
  1389. }
  1390. }
  1391. // Insert in Array
  1392. [metadatasToInsertInDB addObject:metadata];
  1393. }
  1394. // insert in Database
  1395. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB activeUrl:app.activeUrl serverUrl:metadataNet.serverUrl];
  1396. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1397. // read plist
  1398. if (!_isSearchMode)
  1399. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1400. // File is changed ??
  1401. if (!_isSearchMode && metadatasToInsertInDB)
  1402. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1403. });
  1404. // Search Mode
  1405. if (_isSearchMode) {
  1406. // Fix managed -> Unmanaged _searchResultMetadatas
  1407. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1408. [self reloadDatasource:metadataNet.serverUrl];
  1409. }
  1410. // this is the same directory
  1411. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1412. // reload
  1413. [self reloadDatasource:metadataNet.serverUrl];
  1414. // stoprefresh
  1415. [_refreshControl endRefreshing];
  1416. // Enable change user
  1417. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1418. _loadingFolder = NO;
  1419. [self tableViewReloadData];
  1420. }
  1421. }
  1422. - (void)readFolder:(NSString *)serverUrl
  1423. {
  1424. // init control
  1425. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1426. [_refreshControl endRefreshing];
  1427. return;
  1428. }
  1429. // Search Mode
  1430. if (_isSearchMode) {
  1431. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1432. _searchFileName = @""; // forced reload searchg
  1433. [self updateSearchResultsForSearchController:self.searchController];
  1434. return;
  1435. }
  1436. _loadingFolder = YES;
  1437. [self tableViewReloadData];
  1438. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  1439. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1440. metadataNet.action = actionReadFolder;
  1441. metadataNet.date = [NSDate date];
  1442. metadataNet.directoryID = directory.directoryID;
  1443. metadataNet.priority = NSOperationQueuePriorityHigh;
  1444. metadataNet.selector = selectorReadFolder;
  1445. metadataNet.serverUrl = serverUrl;
  1446. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1447. }
  1448. #pragma mark -
  1449. #pragma --------------------------------------------------------------------------------------------
  1450. #pragma mark ===== Search =====
  1451. #pragma --------------------------------------------------------------------------------------------
  1452. -(void)searchStartTimer
  1453. {
  1454. NSString *home = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  1455. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:_depth date:nil selector:selectorSearch delegate:self];
  1456. _noFilesSearchTitle = @"";
  1457. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1458. [self.tableView reloadEmptyDataSet];
  1459. }
  1460. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1461. {
  1462. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
  1463. _isSearchMode = YES;
  1464. [self deleteRefreshControl];
  1465. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1466. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1467. _searchFileName = fileName;
  1468. // First : filter
  1469. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1470. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNamePrint CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1471. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1472. [_searchResultMetadatas removeAllObjects];
  1473. for (tableMetadata *record in records)
  1474. [_searchResultMetadatas addObject:record];
  1475. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1476. metadataNet.account = app.activeAccount;
  1477. metadataNet.directoryID = directoryID;
  1478. metadataNet.selector = selectorSearch;
  1479. metadataNet.serverUrl = _serverUrl;
  1480. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1481. // Version >= 12
  1482. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1483. [_timerWaitInput invalidate];
  1484. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1485. }
  1486. }
  1487. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1488. [self reloadDatasource];
  1489. }
  1490. }
  1491. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1492. {
  1493. [self cancelSearchBar];
  1494. [self readFolder:_serverUrl];
  1495. }
  1496. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1497. {
  1498. _searchFileName = @"";
  1499. if (message)
  1500. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1501. }
  1502. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1503. {
  1504. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1505. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1506. }
  1507. - (void)cancelSearchBar
  1508. {
  1509. if (self.searchController.active) {
  1510. [self.searchController setActive:NO];
  1511. [self createRefreshControl];
  1512. _isSearchMode = NO;
  1513. _searchFileName = @"";
  1514. _dateReadDataSource = nil;
  1515. _searchResultMetadatas = [NSMutableArray new];
  1516. [self reloadDatasource];
  1517. }
  1518. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
  1519. }
  1520. #pragma mark -
  1521. #pragma --------------------------------------------------------------------------------------------
  1522. #pragma mark ===== Delete File or Folder =====
  1523. #pragma --------------------------------------------------------------------------------------------
  1524. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1525. {
  1526. [self deleteFileOrFolderSuccess:metadataNet];
  1527. }
  1528. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1529. {
  1530. [_queueSelector removeObject:metadataNet.selector];
  1531. if ([_queueSelector count] == 0) {
  1532. [_hud hideHud];
  1533. // next
  1534. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1535. if ([_selectedFileIDsMetadatas count] > 0) {
  1536. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1537. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1538. } else {
  1539. // End Select Table View
  1540. [self tableViewSelect:NO];
  1541. // Reload
  1542. if (_isSearchMode)
  1543. [self readFolder:metadataNet.serverUrl];
  1544. else
  1545. [self reloadDatasource:metadataNet.serverUrl];
  1546. }
  1547. }
  1548. }
  1549. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1550. {
  1551. if (metadata.cryptated) {
  1552. [_queueSelector addObject:selectorDeleteCrypto];
  1553. [_queueSelector addObject:selectorDeletePlist];
  1554. } else {
  1555. [_queueSelector addObject:selectorDelete];
  1556. }
  1557. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1558. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1559. }
  1560. - (void)deleteFile
  1561. {
  1562. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1563. return;
  1564. [_queueSelector removeAllObjects];
  1565. if ([_selectedFileIDsMetadatas count] > 0) {
  1566. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1567. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1568. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1569. } else {
  1570. _numSelectedFileIDsMetadatas = 1;
  1571. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1572. }
  1573. }
  1574. #pragma --------------------------------------------------------------------------------------------
  1575. #pragma mark ===== Rename / Move =====
  1576. #pragma --------------------------------------------------------------------------------------------
  1577. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1578. {
  1579. [self readFolder:metadataNet.serverUrl];
  1580. }
  1581. - (void)renameFile:(NSArray *)arguments
  1582. {
  1583. tableMetadata* metadata = [arguments objectAtIndex:0];
  1584. NSString *fileName = [arguments objectAtIndex:1];
  1585. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1586. }
  1587. - (void)renameNote:(NSArray *)arguments
  1588. {
  1589. tableMetadata* metadata = [arguments objectAtIndex:0];
  1590. NSString *fileName = [arguments objectAtIndex:1];
  1591. CCTemplates *templates = [[CCTemplates alloc] init];
  1592. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1593. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1594. if (fileNameModel) {
  1595. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1596. metadataNet.action = actionUploadTemplate;
  1597. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1598. metadataNet.fileNamePrint = fileName;
  1599. metadataNet.etag = metadata.etag;
  1600. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1601. metadataNet.session = k_upload_session_foreground;
  1602. metadataNet.taskStatus = k_taskStatusResume;
  1603. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1604. }
  1605. }
  1606. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1607. {
  1608. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1609. [_hud hideHud];
  1610. if (message)
  1611. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1612. // End Select Table View
  1613. [self tableViewSelect:NO];
  1614. // reload Datasource
  1615. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1616. [self readFolder:metadataNet.serverUrl];
  1617. else
  1618. [self reloadDatasource];
  1619. }
  1620. }
  1621. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1622. {
  1623. [_queueSelector removeObject:metadataNet.selector];
  1624. if ([_queueSelector count] == 0) {
  1625. [_hud hideHud];
  1626. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1627. NSString *directoryID = metadataNet.directoryID;
  1628. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1629. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1630. // FILE -> Metadata
  1631. if (metadataNet.directory == NO)
  1632. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1633. // DIRECTORY -> Directory - CCMetadata
  1634. if (metadataNet.directory == YES) {
  1635. // delete all dir / subdir
  1636. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1637. // move metadata
  1638. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1639. // Add new directory
  1640. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1641. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1642. }
  1643. // next
  1644. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1645. if ([_selectedFileIDsMetadatas count] > 0) {
  1646. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1647. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1648. } else {
  1649. // End Select Table View
  1650. [self tableViewSelect:NO];
  1651. // reload Datasource
  1652. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1653. [self readFolder:metadataNet.serverUrl];
  1654. else
  1655. [self reloadDatasource];
  1656. }
  1657. }
  1658. }
  1659. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1660. {
  1661. tableMetadata *metadata = [arguments objectAtIndex:0];
  1662. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1663. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1664. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1665. // Plain
  1666. if (metadata.cryptated == NO) {
  1667. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1668. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1669. if(!error) {
  1670. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1671. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1672. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1673. }];
  1674. [alert addAction:ok];
  1675. [self presentViewController:alert animated:YES completion:nil];
  1676. });
  1677. // End Select Table View
  1678. [self tableViewSelect:NO];
  1679. // reload Datasource
  1680. [self readFileReloadFolder];
  1681. return;
  1682. }
  1683. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1684. metadataNet.action = actionMoveFileOrFolder;
  1685. metadataNet.directory = metadata.directory;
  1686. metadataNet.fileID = metadata.fileID;
  1687. metadataNet.directoryID = metadata.directoryID;
  1688. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1689. metadataNet.fileName = metadata.fileName;
  1690. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1691. metadataNet.fileNameTo = metadata.fileName;
  1692. metadataNet.etag = metadata.etag;
  1693. metadataNet.selector = selectorMove;
  1694. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1695. metadataNet.serverUrlTo = serverUrlTo;
  1696. [_queueSelector addObject:metadataNet.selector];
  1697. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1698. }
  1699. // cyptated
  1700. if (metadata.cryptated == YES) {
  1701. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1702. metadataNet.action = actionMoveFileOrFolder;
  1703. metadataNet.directory = metadata.directory;
  1704. metadataNet.fileID = metadata.fileID;
  1705. metadataNet.directoryID = metadata.directoryID;
  1706. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1707. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1708. metadataNet.etag = metadata.etag;
  1709. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1710. metadataNet.serverUrlTo = serverUrlTo;
  1711. // data
  1712. metadataNet.fileName = metadata.fileNameData;
  1713. metadataNet.fileNameTo = metadata.fileNameData;
  1714. metadataNet.selector = selectorMoveCrypto;
  1715. [_queueSelector addObject:metadataNet.selector];
  1716. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1717. // plist
  1718. metadataNet.fileName = metadata.fileName;
  1719. metadataNet.fileNameTo = metadata.fileName;
  1720. metadataNet.selector = selectorMovePlist;
  1721. [_queueSelector addObject:metadataNet.selector];
  1722. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1723. }
  1724. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1725. }
  1726. // DELEGATE : Move
  1727. - (void)dismissMove
  1728. {
  1729. [self reloadDatasource];
  1730. }
  1731. // DELEGATE : Move
  1732. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1733. {
  1734. [_queueSelector removeAllObjects];
  1735. if ([_selectedFileIDsMetadatas count] > 0) {
  1736. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1737. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1738. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1739. } else {
  1740. _numSelectedFileIDsMetadatas = 1;
  1741. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1742. }
  1743. }
  1744. - (void)moveOpenWindow:(NSArray *)indexPaths
  1745. {
  1746. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1747. return;
  1748. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1749. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1750. viewController.delegate = self;
  1751. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1752. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1753. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1754. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1755. viewController.networkingOperationQueue = app.netQueue;
  1756. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1757. [self presentViewController:navigationController animated:YES completion:nil];
  1758. }
  1759. #pragma --------------------------------------------------------------------------------------------
  1760. #pragma mark ===== Create folder =====
  1761. #pragma --------------------------------------------------------------------------------------------
  1762. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1763. {
  1764. if (metadataNet.cryptated == NO) {
  1765. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1766. [self reloadDatasource];
  1767. // We are in directory fail ?
  1768. CCMain *vc = [app.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1769. if (vc)
  1770. [vc.navigationController popViewControllerAnimated:YES];
  1771. }
  1772. if (message)
  1773. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1774. }
  1775. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1776. {
  1777. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1778. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1779. if (metadataNet.cryptated == NO) {
  1780. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1781. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1782. metadata.fileID = metadataNet.fileID;
  1783. metadata.date = metadataNet.date;
  1784. metadata.permissions = @"RDNVCK";
  1785. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata activeUrl:app.activeUrl serverUrl:_serverUrl];
  1786. [self reloadDatasource];
  1787. }
  1788. }
  1789. - (void)createFolder:(NSString *)fileNameFolder autoUploadDirectory:(BOOL)autoUploadDirectory
  1790. {
  1791. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1792. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1793. if (![fileNameFolder length]) return;
  1794. if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1795. else metadataNet.serverUrl = _serverUrl;
  1796. metadataNet.action = actionCreateFolder;
  1797. metadataNet.directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1798. if (autoUploadDirectory)
  1799. metadataNet.options = @"folderAutoUpload";
  1800. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1801. metadataNet.fileName = fileNameFolder;
  1802. metadataNet.selector = selectorCreateFolder;
  1803. metadataNet.serverUrl = _serverUrl;
  1804. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1805. // Create Directory on metadata
  1806. tableMetadata *metadata = [CCUtility createMetadataWithAccount:app.activeAccount date:[NSDate date] directory:YES fileID:metadataNet.fileID directoryID:metadataNet.directoryID fileName:metadataNet.fileName etag:@"" size:0 status:k_metadataStatusNormal];
  1807. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata activeUrl:app.activeUrl serverUrl:_serverUrl];
  1808. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1809. [self reloadDatasource];
  1810. }
  1811. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1812. {
  1813. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1814. NSString *fileNamePlist;
  1815. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1816. if (![fileNameFolder length]) return;
  1817. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1818. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1819. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1820. // Create folder
  1821. metadataNet.action = actionCreateFolder;
  1822. metadataNet.cryptated = YES;
  1823. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1824. metadataNet.fileName = fileNamePlist;
  1825. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1826. metadataNet.selector = selectorCreateFolder;
  1827. metadataNet.serverUrl = _serverUrl;
  1828. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1829. // upload plist file
  1830. metadataNet.action = actionUploadOnlyPlist;
  1831. metadataNet.cryptated = YES;
  1832. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1833. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1834. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1835. metadataNet.selectorPost = selectorReadFolderForced;
  1836. metadataNet.serverUrl = _serverUrl;
  1837. metadataNet.session = k_upload_session_foreground;
  1838. metadataNet.taskStatus = k_taskStatusResume;
  1839. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1840. }
  1841. #pragma --------------------------------------------------------------------------------------------
  1842. #pragma mark ===== Encrypted / Decrypted Folder =====
  1843. #pragma --------------------------------------------------------------------------------------------
  1844. - (void)encyptedDecryptedFolder
  1845. {
  1846. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1847. if (_metadata.cryptated) {
  1848. // DECRYPTED
  1849. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1850. //-------------------------- RENAME -------------------------------------------//
  1851. metadataNet.action = actionMoveFileOrFolder;
  1852. metadataNet.fileID = _metadata.fileID;
  1853. metadataNet.fileName = _metadata.fileNameData;
  1854. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1855. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1856. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1857. metadataNet.selector = selectorRename;
  1858. metadataNet.serverUrl = serverUrl;
  1859. metadataNet.serverUrlTo = serverUrl;
  1860. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1861. //-------------------------- DELETE -------------------------------------------//
  1862. metadataNet.action = actionDeleteFileDirectory;
  1863. metadataNet.fileID = _metadata.fileID;
  1864. metadataNet.fileName = _metadata.fileName;
  1865. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1866. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1867. metadataNet.selector = selectorDeletePlist;
  1868. metadataNet.selectorPost = selectorReadFolderForced;
  1869. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1870. } else {
  1871. // ENCRYPTED
  1872. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1873. // Create File Plist
  1874. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1875. //-------------------------- RENAME -------------------------------------------//
  1876. metadataNet.action = actionMoveFileOrFolder;
  1877. metadataNet.fileID = _metadata.fileID;
  1878. metadataNet.fileName = _metadata.fileName;
  1879. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1880. metadataNet.fileNameTo = fileNameCrypto;
  1881. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1882. metadataNet.selector = selectorRename;
  1883. metadataNet.serverUrl = serverUrl;
  1884. metadataNet.serverUrlTo = serverUrl;
  1885. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1886. //-------------------------- UPLOAD -------------------------------------------//
  1887. metadataNet.action = actionUploadOnlyPlist;
  1888. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1889. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1890. metadataNet.selectorPost = selectorReadFolderForced;
  1891. metadataNet.serverUrl = serverUrl;
  1892. metadataNet.session = k_upload_session_foreground;
  1893. metadataNet.taskStatus = k_taskStatusResume;
  1894. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1895. }
  1896. }
  1897. #pragma --------------------------------------------------------------------------------------------
  1898. #pragma mark ===== Encrypted/Decrypted File =====
  1899. #pragma --------------------------------------------------------------------------------------------
  1900. - (void)encryptedSelectedFiles
  1901. {
  1902. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1903. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1904. for (tableMetadata *metadata in selectedMetadatas) {
  1905. if (metadata.cryptated == NO && metadata.directory == NO)
  1906. [metadatas addObject:metadata];
  1907. }
  1908. if ([metadatas count] > 0) {
  1909. NSLog(@"[LOG] Start encrypted selected files ...");
  1910. for (tableMetadata* metadata in metadatas) {
  1911. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1912. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1913. }
  1914. }
  1915. [self tableViewSelect:NO];
  1916. }
  1917. - (void)decryptedSelectedFiles
  1918. {
  1919. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1920. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1921. for (tableMetadata *metadata in selectedMetadatas) {
  1922. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1923. [metadatas addObject:metadata];
  1924. }
  1925. if ([metadatas count] > 0) {
  1926. NSLog(@"[LOG] Start decrypted selected files ...");
  1927. for (tableMetadata* metadata in metadatas) {
  1928. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1929. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1930. }
  1931. }
  1932. [self tableViewSelect:NO];
  1933. }
  1934. - (void)cmdEncryptedDecryptedFile
  1935. {
  1936. NSString *selector;
  1937. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1938. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1939. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1940. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1941. }
  1942. - (void)encryptedFile:(tableMetadata *)metadata
  1943. {
  1944. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1945. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1946. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1947. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1948. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1949. dispatch_async(dispatch_get_main_queue(), ^{
  1950. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1951. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1952. });
  1953. } else {
  1954. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1955. }
  1956. }
  1957. - (void)decryptedFile:(tableMetadata *)metadata
  1958. {
  1959. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1960. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1961. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1962. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1963. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1964. dispatch_async(dispatch_get_main_queue(), ^{
  1965. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1966. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1967. });
  1968. } else {
  1969. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1970. }
  1971. }
  1972. #pragma --------------------------------------------------------------------------------------------
  1973. #pragma mark ===== Progress & Task Button =====
  1974. #pragma --------------------------------------------------------------------------------------------
  1975. - (void)triggerProgressTask:(NSNotification *)notification
  1976. {
  1977. NSDictionary *dict = notification.userInfo;
  1978. NSString *fileID = [dict valueForKey:@"fileID"];
  1979. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1980. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1981. float progress = [[dict valueForKey:@"progress"] floatValue];
  1982. // CCProgress
  1983. if (progress == 0)
  1984. [self.navigationController cancelCCProgress];
  1985. else
  1986. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1987. // Check
  1988. if (!fileID)
  1989. return;
  1990. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1991. if (![serverUrl isEqualToString:_serverUrl])
  1992. return;
  1993. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1994. if ([self indexPathIsValid:indexPath]) {
  1995. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1996. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  1997. else cell.progressView.progressTintColor = [UIColor blackColor];
  1998. cell.progressView.hidden = NO;
  1999. [cell.progressView setProgress:progress];
  2000. }
  2001. }
  2002. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  2003. {
  2004. UITouch * touch = [[event allTouches] anyObject];
  2005. CGPoint location = [touch locationInView:self.tableView];
  2006. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2007. if ([self indexPathIsValid:indexPath]) {
  2008. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2009. if (metadata)
  2010. [self reloadTaskButton:metadata];
  2011. }
  2012. }
  2013. - (void)reloadTaskButton:(tableMetadata *)metadata
  2014. {
  2015. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2016. __block NSURLSessionTask *findTask;
  2017. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2018. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2019. NSString *fileID = metadata.fileID;
  2020. // DOWNLOAD
  2021. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2022. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2023. for (NSURLSessionUploadTask *task in downloadTasks)
  2024. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2025. findTask = task;
  2026. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2027. [task cancel];
  2028. }
  2029. if (!findTask) {
  2030. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2031. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2032. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2033. }
  2034. }];
  2035. }
  2036. // UPLOAD
  2037. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2038. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2039. for (NSURLSessionUploadTask *task in uploadTasks)
  2040. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2041. findTask = task;
  2042. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2043. [task cancel];
  2044. }
  2045. if (!findTask) {
  2046. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2047. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2048. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2049. }
  2050. }];
  2051. }
  2052. }
  2053. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2054. {
  2055. UITouch * touch = [[event allTouches] anyObject];
  2056. CGPoint location = [touch locationInView:self.tableView];
  2057. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2058. if ([self indexPathIsValid:indexPath]) {
  2059. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2060. if (metadata)
  2061. [self cancelTaskButton:metadata reloadTable:YES];
  2062. }
  2063. }
  2064. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2065. {
  2066. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2067. __block NSURLSessionTask *findTask;
  2068. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2069. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2070. NSString *fileID = metadata.fileID;
  2071. // DOWNLOAD
  2072. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2073. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2074. for (NSURLSessionTask *task in downloadTasks)
  2075. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2076. findTask = task;
  2077. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2078. [task cancel];
  2079. }
  2080. if (!findTask) {
  2081. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2082. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2083. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2084. }
  2085. }];
  2086. }
  2087. // UPLOAD
  2088. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2089. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2090. for (NSURLSessionUploadTask *task in uploadTasks)
  2091. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2092. findTask = task;
  2093. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2094. [task cancel];
  2095. }
  2096. if (!findTask) {
  2097. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2098. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2099. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2100. }
  2101. }];
  2102. }
  2103. }
  2104. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2105. {
  2106. UITouch * touch = [[event allTouches] anyObject];
  2107. CGPoint location = [touch locationInView:self.tableView];
  2108. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2109. if ([self indexPathIsValid:indexPath]) {
  2110. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2111. if (metadata)
  2112. [self stopTaskButton:metadata];
  2113. }
  2114. }
  2115. - (void)stopTaskButton:(tableMetadata *)metadata
  2116. {
  2117. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2118. __block NSURLSessionTask *findTask;
  2119. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2120. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2121. NSString *fileID = metadata.fileID;
  2122. // UPLOAD
  2123. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2124. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2125. for (NSURLSessionUploadTask *task in uploadTasks)
  2126. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2127. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2128. findTask = task;
  2129. [task cancel];
  2130. }
  2131. if (!findTask) {
  2132. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2133. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2134. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2135. }
  2136. }];
  2137. }
  2138. }
  2139. #pragma --------------------------------------------------------------------------------------------
  2140. #pragma mark ===== Shared =====
  2141. #pragma --------------------------------------------------------------------------------------------
  2142. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2143. {
  2144. [_hud hideHud];
  2145. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2146. // change account ?
  2147. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2148. if([record.account isEqualToString:metadataNet.account] == NO)
  2149. return;
  2150. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2151. if (result) {
  2152. appDelegate.sharesLink = result[0];
  2153. appDelegate.sharesUserAndGroup = result[1];
  2154. }
  2155. // Notify Shares View
  2156. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  2157. if (openWindow) {
  2158. if (_shareOC) {
  2159. [_shareOC reloadData];
  2160. } else {
  2161. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2162. // Apriamo la view
  2163. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2164. _shareOC.delegate = self;
  2165. _shareOC.metadata = metadata;
  2166. _shareOC.serverUrl = metadataNet.serverUrl;
  2167. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2168. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2169. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2170. [self presentViewController:_shareOC animated:YES completion:nil];
  2171. }
  2172. }
  2173. [self tableViewReloadData];
  2174. }
  2175. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2176. {
  2177. [_hud hideHud];
  2178. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2179. if (_shareOC)
  2180. [_shareOC reloadData];
  2181. [self tableViewReloadData];
  2182. if (errorCode == 401)
  2183. [self changePasswordAccount];
  2184. }
  2185. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2186. {
  2187. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2188. metadataNet.action = actionShare;
  2189. metadataNet.fileID = metadata.fileID;
  2190. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2191. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2192. metadataNet.password = password;
  2193. metadataNet.selector = selectorShare;
  2194. metadataNet.serverUrl = serverUrl;
  2195. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2196. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2197. }
  2198. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2199. {
  2200. [_hud hideHud];
  2201. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2202. // rimuoviamo la condivisione da db
  2203. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2204. if (result) {
  2205. appDelegate.sharesLink = result[0];
  2206. appDelegate.sharesUserAndGroup = result[1];
  2207. }
  2208. if (_shareOC)
  2209. [_shareOC reloadData];
  2210. [self tableViewReloadData];
  2211. }
  2212. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2213. {
  2214. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2215. metadataNet.action = actionUnShare;
  2216. metadataNet.fileID = metadata.fileID;
  2217. metadataNet.fileName = metadata.fileName;
  2218. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2219. metadataNet.selector = selectorUnshare;
  2220. metadataNet.serverUrl = serverUrl;
  2221. metadataNet.share = share;
  2222. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2223. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2224. }
  2225. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2226. {
  2227. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2228. metadataNet.action = actionUpdateShare;
  2229. metadataNet.fileID = metadata.fileID;
  2230. metadataNet.expirationTime = expirationTime;
  2231. metadataNet.password = password;
  2232. metadataNet.selector = selectorUpdateShare;
  2233. metadataNet.serverUrl = serverUrl;
  2234. metadataNet.share = share;
  2235. metadataNet.sharePermission = permission;
  2236. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2237. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2238. }
  2239. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2240. {
  2241. [_hud hideHud];
  2242. if (_shareOC)
  2243. [_shareOC reloadUserAndGroup:items];
  2244. }
  2245. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2246. {
  2247. [_hud hideHud];
  2248. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2249. }
  2250. - (void)getUserAndGroup:(NSString *)find
  2251. {
  2252. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2253. metadataNet.action = actionGetUserAndGroup;
  2254. metadataNet.options = find;
  2255. metadataNet.selector = selectorGetUserAndGroup;
  2256. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2257. [_hud visibleIndeterminateHud];
  2258. }
  2259. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2260. {
  2261. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2262. metadataNet.action = actionShareWith;
  2263. metadataNet.fileID = metadata.fileID;
  2264. metadataNet.directoryID = directoryID;
  2265. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2266. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2267. metadataNet.serverUrl = serverUrl;
  2268. metadataNet.selector = selectorShare;
  2269. metadataNet.share = user;
  2270. metadataNet.shareeType = shareeType;
  2271. metadataNet.sharePermission = permission;
  2272. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2273. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2274. }
  2275. - (void)openWindowShare:(tableMetadata *)metadata
  2276. {
  2277. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2278. metadataNet.action = actionReadShareServer;
  2279. metadataNet.fileID = metadata.fileID;
  2280. metadataNet.fileName = metadata.fileName;
  2281. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2282. metadataNet.selector = selectorOpenWindowShare;
  2283. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2284. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2285. [_hud visibleIndeterminateHud];
  2286. }
  2287. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2288. {
  2289. CGPoint location = [tapGesture locationInView:self.tableView];
  2290. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2291. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2292. if (metadata)
  2293. [self openWindowShare:metadata];
  2294. }
  2295. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2296. {
  2297. CGPoint location = [tapGesture locationInView:self.tableView];
  2298. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2299. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2300. if (metadata) {
  2301. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2302. vc.metadata = metadata;
  2303. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2304. [self presentViewController:vc animated:YES completion:nil];
  2305. }
  2306. }
  2307. #pragma --------------------------------------------------------------------------------------------
  2308. #pragma mark ===== Favorite =====
  2309. #pragma --------------------------------------------------------------------------------------------
  2310. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2311. {
  2312. _dateReadDataSource = nil;
  2313. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2314. if (_isSearchMode)
  2315. [self readFolder:metadataNet.serverUrl];
  2316. else
  2317. [self reloadDatasource:metadataNet.serverUrl];
  2318. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2319. if (metadata.directory && metadata.favorite) {
  2320. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2321. [app.activeFavorites addFavoriteFolder:dir];
  2322. }
  2323. }
  2324. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2325. {
  2326. }
  2327. - (void)addFavorite:(tableMetadata *)metadata
  2328. {
  2329. if (metadata.directory) {
  2330. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2331. } else {
  2332. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2333. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2334. }
  2335. }
  2336. - (void)removeFavorite:(tableMetadata *)metadata
  2337. {
  2338. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2339. }
  2340. #pragma --------------------------------------------------------------------------------------------
  2341. #pragma mark ===== Local =====
  2342. #pragma --------------------------------------------------------------------------------------------
  2343. - (void)addLocal:(tableMetadata *)metadata
  2344. {
  2345. if (metadata.errorPasscode || !metadata.uuid) return;
  2346. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2347. if ([metadata.type isEqualToString: k_metadataType_file])
  2348. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2349. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2350. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2351. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2352. }
  2353. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2354. if ([self indexPathIsValid:indexPath])
  2355. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2356. }
  2357. #pragma --------------------------------------------------------------------------------------------
  2358. #pragma mark ===== Open in... =====
  2359. #pragma --------------------------------------------------------------------------------------------
  2360. - (void)openIn:(tableMetadata *)metadata
  2361. {
  2362. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2363. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2364. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2365. if ([self indexPathIsValid:indexPath])
  2366. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2367. }
  2368. #pragma --------------------------------------------------------------------------------------------
  2369. #pragma mark ===== Remove Local File =====
  2370. #pragma --------------------------------------------------------------------------------------------
  2371. - (void)removeLocalFile:(tableMetadata *)metadata
  2372. {
  2373. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2374. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2375. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2376. [self reloadDatasource:serverUrl];
  2377. }
  2378. #pragma --------------------------------------------------------------------------------------------
  2379. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2380. #pragma --------------------------------------------------------------------------------------------
  2381. - (void)orderTable:(NSString *)order
  2382. {
  2383. [CCUtility setOrderSettings:order];
  2384. // Clear data-read of DataSource
  2385. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2386. }
  2387. - (void)ascendingTable:(BOOL)ascending
  2388. {
  2389. [CCUtility setAscendingSettings:ascending];
  2390. // Clear data-read of DataSource
  2391. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2392. }
  2393. - (void)directoryOnTop:(BOOL)directoryOnTop
  2394. {
  2395. [CCUtility setDirectoryOnTop:directoryOnTop];
  2396. // Clear data-read of DataSource
  2397. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2398. }
  2399. - (void)tableGroupBy:(NSString *)groupBy
  2400. {
  2401. [CCUtility setGroupBySettings:groupBy];
  2402. // Clear data-read of DataSource
  2403. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2404. }
  2405. #pragma --------------------------------------------------------------------------------------------
  2406. #pragma mark ==== Menu LOGO ====
  2407. #pragma --------------------------------------------------------------------------------------------
  2408. - (void)menuLogo
  2409. {
  2410. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2411. return;
  2412. // Brand
  2413. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2414. return;
  2415. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [[NCManageDatabase sharedInstance] countAutoUploadWithSession:nil] > 0) {
  2416. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2417. return;
  2418. }
  2419. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2420. NSMutableArray *menuArray = [NSMutableArray new];
  2421. for (NSString *account in listAccount) {
  2422. if ([account isEqualToString:app.activeAccount]) continue;
  2423. CCMenuItem *item = [[CCMenuItem alloc] init];
  2424. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2425. item.argument = account;
  2426. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2427. item.target = self;
  2428. item.action = @selector(changeDefaultAccount:);
  2429. [menuArray addObject:item];
  2430. }
  2431. if ([menuArray count] == 0)
  2432. return;
  2433. OptionalConfiguration options;
  2434. Color textColor, backgroundColor;
  2435. textColor.R = 0;
  2436. textColor.G = 0;
  2437. textColor.B = 0;
  2438. backgroundColor.R = 1;
  2439. backgroundColor.G = 1;
  2440. backgroundColor.B = 1;
  2441. NSInteger originY = 60;
  2442. options.arrowSize = 9;
  2443. options.marginXSpacing = 7;
  2444. options.marginYSpacing = 10;
  2445. options.intervalSpacing = 20;
  2446. options.menuCornerRadius = 6.5;
  2447. options.maskToBackground = NO;
  2448. options.shadowOfMenu = YES;
  2449. options.hasSeperatorLine = YES;
  2450. options.seperatorLineHasInsets = YES;
  2451. options.textColor = textColor;
  2452. options.menuBackgroundColor = backgroundColor;
  2453. CGRect rect = self.view.frame;
  2454. rect.origin.y = rect.origin.y + originY;
  2455. rect.size.height = rect.size.height - originY;
  2456. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2457. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2458. }
  2459. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2460. {
  2461. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2462. // STOP, erase all in queue networking
  2463. [app cancelAllOperations];
  2464. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2465. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2466. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2467. if (tableAccount)
  2468. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2469. // go to home sweet home
  2470. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2471. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2472. });
  2473. }
  2474. #pragma --------------------------------------------------------------------------------------------
  2475. #pragma mark ==== ReMenu ====
  2476. #pragma --------------------------------------------------------------------------------------------
  2477. - (void)createReMenuBackgroundView:(REMenu *)menu
  2478. {
  2479. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2480. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2481. [UIView animateWithDuration:0.2 animations:^{
  2482. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2483. if (height < self.tabBarController.tabBar.frame.size.height)
  2484. height = self.tabBarController.tabBar.frame.size.height;
  2485. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2486. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2487. }];
  2488. }
  2489. - (void)createReMainMenu
  2490. {
  2491. NSString *ordinamento;
  2492. NSString *groupBy = _directoryGroupBy;
  2493. __block NSString *nuovoOrdinamento;
  2494. NSString *titoloNuovo, *titoloAttuale;
  2495. BOOL ascendente;
  2496. __block BOOL nuovoAscendente;
  2497. UIImage *image;
  2498. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2499. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2500. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2501. [self tableViewSelect:YES];
  2502. }
  2503. }];
  2504. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2505. ordinamento = _directoryOrder;
  2506. if ([ordinamento isEqualToString:@"fileName"]) {
  2507. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2508. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2509. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2510. nuovoOrdinamento = @"date";
  2511. }
  2512. if ([ordinamento isEqualToString:@"date"]) {
  2513. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2514. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2515. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2516. nuovoOrdinamento = @"fileName";
  2517. }
  2518. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2519. [self orderTable:nuovoOrdinamento];
  2520. }];
  2521. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2522. ascendente = [CCUtility getAscendingSettings];
  2523. if (ascendente) {
  2524. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2525. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2526. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2527. nuovoAscendente = false;
  2528. }
  2529. if (!ascendente) {
  2530. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2531. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2532. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2533. nuovoAscendente = true;
  2534. }
  2535. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2536. [self ascendingTable:nuovoAscendente];
  2537. }];
  2538. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2539. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2540. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2541. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2542. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2543. else [self tableGroupBy:@"alphabetic"];
  2544. }];
  2545. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2546. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2547. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2548. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2549. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2550. else [self tableGroupBy:@"typefile"];
  2551. }];
  2552. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2553. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2554. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2555. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2556. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2557. else [self tableGroupBy:@"date"];
  2558. }];
  2559. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2560. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2561. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2562. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2563. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2564. else [self directoryOnTop:YES];
  2565. }];
  2566. // REMENU --------------------------------------------------------------------------------------------------------------
  2567. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2568. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2569. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2570. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2571. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2572. app.reMainMenu.separatorHeight = 0.5;
  2573. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2574. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2575. app.reMainMenu.textColor = [UIColor blackColor];
  2576. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2577. app.reMainMenu.textShadowColor = nil;
  2578. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2579. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2580. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2581. app.reMainMenu.highlightedSeparatorColor = nil;
  2582. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2583. app.reMainMenu.highlightedTextShadowColor = nil;
  2584. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2585. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2586. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2587. app.reMainMenu.subtitleTextShadowColor = nil;
  2588. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2589. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2590. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2591. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2592. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2593. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2594. app.reMainMenu.borderWidth = 0.3;
  2595. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2596. app.reMainMenu.animationDuration = 0.2;
  2597. app.reMainMenu.closeAnimationDuration = 0.2;
  2598. app.reMainMenu.bounce = NO;
  2599. [app.reMainMenu setClosePreparationBlock:^{
  2600. // Backgroun reMenu (Gesture)
  2601. [_reMenuBackgroundView removeFromSuperview];
  2602. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2603. }];
  2604. }
  2605. - (void)toggleReMainMenu
  2606. {
  2607. if (app.reMainMenu.isOpen) {
  2608. [app.reMainMenu close];
  2609. } else {
  2610. [self createReMainMenu];
  2611. [app.reMainMenu showFromNavigationController:self.navigationController];
  2612. // Backgroun reMenu & (Gesture)
  2613. [self createReMenuBackgroundView:app.reMainMenu];
  2614. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2615. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2616. }
  2617. }
  2618. - (void)createReSelectMenu
  2619. {
  2620. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2621. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2622. [self deleteFile];
  2623. }];
  2624. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2625. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2626. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2627. }];
  2628. if (app.isCryptoCloudMode) {
  2629. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2630. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2631. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2632. }];
  2633. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2634. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2635. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2636. }];
  2637. }
  2638. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2639. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2640. [self downloadSelectedFilesFolders];
  2641. }];
  2642. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2643. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2644. [self saveSelectedFiles];
  2645. }];
  2646. // REMENU --------------------------------------------------------------------------------------------------------------
  2647. if (app.isCryptoCloudMode) {
  2648. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2649. } else {
  2650. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2651. }
  2652. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2653. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2654. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2655. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2656. app.reSelectMenu.separatorHeight = 0.5;
  2657. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2658. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2659. app.reSelectMenu.textColor = [UIColor blackColor];
  2660. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2661. app.reSelectMenu.textShadowColor = nil;
  2662. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2663. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2664. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2665. app.reSelectMenu.highlightedSeparatorColor = nil;
  2666. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2667. app.reSelectMenu.highlightedTextShadowColor = nil;
  2668. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2669. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2670. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2671. app.reSelectMenu.subtitleTextShadowColor = nil;
  2672. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2673. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2674. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2675. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2676. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2677. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2678. app.reSelectMenu.borderWidth = 0.3;
  2679. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2680. app.reSelectMenu.closeAnimationDuration = 0.2;
  2681. app.reSelectMenu.animationDuration = 0.2;
  2682. app.reSelectMenu.bounce = NO;
  2683. [app.reSelectMenu setClosePreparationBlock:^{
  2684. // Backgroun reMenu (Gesture)
  2685. [_reMenuBackgroundView removeFromSuperview];
  2686. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2687. }];
  2688. }
  2689. - (void)toggleReSelectMenu
  2690. {
  2691. if (app.reSelectMenu.isOpen) {
  2692. [app.reSelectMenu close];
  2693. } else {
  2694. [self createReSelectMenu];
  2695. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2696. // Backgroun reMenu & (Gesture)
  2697. [self createReMenuBackgroundView:app.reSelectMenu];
  2698. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2699. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2700. }
  2701. }
  2702. #pragma --------------------------------------------------------------------------------------------
  2703. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2704. #pragma --------------------------------------------------------------------------------------------
  2705. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2706. {
  2707. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2708. UITableView *tableView = (UITableView*)self.view;
  2709. CGPoint touchPoint = [recognizer locationInView:self.view];
  2710. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2711. if ([self indexPathIsValid:indexPath])
  2712. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2713. else
  2714. _metadata = nil;
  2715. [self becomeFirstResponder];
  2716. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2717. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2718. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2719. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2720. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2721. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2722. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2723. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2724. if (app.isCryptoCloudMode)
  2725. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2726. else
  2727. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2728. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2729. [menuController setMenuVisible:YES animated:YES];
  2730. }
  2731. }
  2732. - (BOOL)canBecomeFirstResponder
  2733. {
  2734. return YES;
  2735. }
  2736. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2737. {
  2738. // For copy file, copy files, Open in ... :
  2739. //
  2740. // NO Directory
  2741. // NO Error Passcode
  2742. // NO In Session mode (download/upload)
  2743. // NO Template
  2744. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2745. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2746. // NO Cryptated with Title lenght = 0
  2747. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2748. return YES;
  2749. }
  2750. return NO;
  2751. }
  2752. if (@selector(copyFiles:) == action) {
  2753. if (_isSelectedMode) {
  2754. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2755. for (tableMetadata *metadata in selectedMetadatas) {
  2756. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2757. // NO Cryptated with Title lenght = 0
  2758. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2759. return YES;
  2760. }
  2761. }
  2762. }
  2763. return NO;
  2764. }
  2765. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2766. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2767. NSArray *items = [pasteboard items];
  2768. if ([items count] == 1) {
  2769. // Value : (NSData) fileID
  2770. NSDictionary *dic = [items objectAtIndex:0];
  2771. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2772. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2773. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2774. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2775. if (directoryUser) {
  2776. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2777. return YES;
  2778. }
  2779. return NO;
  2780. } else return NO;
  2781. }
  2782. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2783. BOOL isValid = NO;
  2784. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2785. NSArray *items = [pasteboard items];
  2786. if ([items count] <= 1) return NO;
  2787. for (NSDictionary *dic in items) {
  2788. // Value : (NSData) fileID
  2789. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2790. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2791. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2792. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2793. if (directoryUser) {
  2794. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2795. isValid = YES;
  2796. }
  2797. }
  2798. return isValid;
  2799. }
  2800. return NO;
  2801. }
  2802. /************************************ COPY ************************************/
  2803. - (void)copyFile:(id)sender
  2804. {
  2805. // Remove all item
  2806. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2807. pasteboard.items = [[NSArray alloc] init];
  2808. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2809. [self copyFileToPasteboard:_metadata];
  2810. } else {
  2811. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2812. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2813. }
  2814. }
  2815. - (void)copyFiles:(id)sender
  2816. {
  2817. // Remove all item
  2818. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2819. pasteboard.items = [[NSArray alloc] init];
  2820. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2821. for (tableMetadata *metadata in selectedMetadatas) {
  2822. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2823. [self copyFileToPasteboard:metadata];
  2824. } else {
  2825. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2826. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2827. }
  2828. }
  2829. [self tableViewSelect:NO];
  2830. }
  2831. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2832. {
  2833. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2834. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2835. // Value : (NSData) fileID
  2836. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2837. [items addObject:item];
  2838. [pasteboard setItems:items];
  2839. }
  2840. /************************************ OPEN IN ... ************************************/
  2841. - (void)openinFile:(id)sender
  2842. {
  2843. [self openIn:_metadata];
  2844. }
  2845. /************************************ PASTE ************************************/
  2846. - (void)pasteFile:(id)sender
  2847. {
  2848. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2849. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2850. }
  2851. - (void)pasteFileEncrypted:(id)sender
  2852. {
  2853. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2854. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2855. }
  2856. - (void)pasteFiles:(id)sender
  2857. {
  2858. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2859. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2860. }
  2861. - (void)pasteFilesEncrypted:(id)sender
  2862. {
  2863. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2864. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2865. }
  2866. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2867. {
  2868. for (NSDictionary *dic in items) {
  2869. // Value : (NSData) fileID
  2870. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2871. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2872. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2873. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2874. if (!metadata || !account) return;
  2875. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2876. if (directoryUser) {
  2877. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2878. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2879. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2880. }
  2881. }
  2882. }
  2883. }
  2884. #pragma --------------------------------------------------------------------------------------------
  2885. #pragma mark ===== Lock Passcode =====
  2886. #pragma --------------------------------------------------------------------------------------------
  2887. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2888. {
  2889. return _failedAttempts;
  2890. }
  2891. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2892. {
  2893. return _lockUntilDate;
  2894. }
  2895. - (void)passcodeViewCloseButtonPressed:(id)sender
  2896. {
  2897. [self dismissViewControllerAnimated:YES completion:nil];
  2898. }
  2899. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2900. {
  2901. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2902. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2903. _lockUntilDate = nil;
  2904. _failedAttempts = 0;
  2905. aResultHandler(YES);
  2906. } else aResultHandler(NO);
  2907. } else aResultHandler(YES);
  2908. }
  2909. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2910. {
  2911. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2912. switch (aViewController.type) {
  2913. case BKPasscodeViewControllerCheckPasscodeType: {
  2914. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2915. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2916. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2917. // scriviamo il passcode
  2918. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2919. [self readFolder:_serverUrl];
  2920. } else {
  2921. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2922. [alertView show];
  2923. }
  2924. }
  2925. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2926. // possiamo procedere alla prossima directory
  2927. [self performSegueDirectoryWithControlPasscode:false];
  2928. // avviamo la sessione Passcode Lock con now
  2929. app.sessionePasscodeLock = [NSDate date];
  2930. }
  2931. // disattivazione lock cartella
  2932. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2933. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2934. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2935. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2936. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2937. }
  2938. [self tableViewReloadData];
  2939. }
  2940. }
  2941. break;
  2942. default:
  2943. break;
  2944. }
  2945. }
  2946. - (void)comandoLockPassword
  2947. {
  2948. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2949. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2950. // se non è abilitato il Lock Passcode esci
  2951. if ([[CCUtility getBlockCode] length] == 0) {
  2952. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2953. [alertView show];
  2954. return;
  2955. }
  2956. // se è richiesta la disattivazione si chiede la password
  2957. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2958. if (directory.lock) {
  2959. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2960. viewController.delegate = self;
  2961. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2962. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2963. viewController.inputViewTitlePassword = YES;
  2964. if ([CCUtility getSimplyBlockCode]) {
  2965. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2966. viewController.passcodeInputView.maximumLength = 6;
  2967. } else {
  2968. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2969. viewController.passcodeInputView.maximumLength = 64;
  2970. }
  2971. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2972. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2973. viewController.touchIDManager = touchIDManager;
  2974. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2975. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2976. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2977. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2978. [self presentViewController:navigationController animated:YES completion:nil];
  2979. return;
  2980. }
  2981. // ---------------- ACTIVATE PASSWORD
  2982. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2983. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2984. if ([self indexPathIsValid:indexPath])
  2985. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2986. } else {
  2987. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2988. }
  2989. }
  2990. #pragma mark -
  2991. #pragma --------------------------------------------------------------------------------------------
  2992. #pragma mark ===== Swipe Tablet -> menu =====
  2993. #pragma --------------------------------------------------------------------------------------------
  2994. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2995. {
  2996. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2997. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2998. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2999. return NO;
  3000. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier != k_taskIdentifierDone || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3001. return NO;
  3002. else
  3003. return YES;
  3004. }
  3005. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  3006. {
  3007. //
  3008. }
  3009. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  3010. {
  3011. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3012. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3013. if (direction == MGSwipeDirectionRightToLeft) {
  3014. // Delete
  3015. if (index == 0)
  3016. [self swipeDelete:indexPath];
  3017. // More
  3018. if (index == 1) {
  3019. [cell hideSwipeAnimated:NO];
  3020. [self performSelector:@selector(swipeMore:) withObject:indexPath afterDelay:0.1];
  3021. }
  3022. }
  3023. if (direction == MGSwipeDirectionLeftToRight) {
  3024. if (_metadata.favorite)
  3025. [self removeFavorite:_metadata];
  3026. else
  3027. [self addFavorite:_metadata];
  3028. }
  3029. return YES;
  3030. }
  3031. - (void)swipeDelete:(NSIndexPath *)indexPath
  3032. {
  3033. // Directory locked ?
  3034. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileNameData];
  3035. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3036. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) {
  3037. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3038. return;
  3039. }
  3040. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3041. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  3042. [self performSelector:@selector(deleteFile) withObject:nil];
  3043. }]];
  3044. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3045. [alertController dismissViewControllerAnimated:YES completion:nil];
  3046. }]];
  3047. alertController.popoverPresentationController.sourceView = self.view;
  3048. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3049. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3050. [alertController.view layoutIfNeeded];
  3051. [self presentViewController:alertController animated:YES completion:nil];
  3052. }
  3053. - (void)swipeMore:(NSIndexPath *)indexPath
  3054. {
  3055. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3056. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  3057. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  3058. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3059. if (_metadata.favorite) {
  3060. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3061. } else {
  3062. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3063. }
  3064. if (_metadata.directory) {
  3065. // calcolo lockServerUrl
  3066. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3067. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3068. if (directory.lock)
  3069. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3070. else
  3071. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3072. }
  3073. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  3074. // ******************************************* AHKActionSheet *******************************************
  3075. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3076. actionSheet.animationDuration = 0.2;
  3077. actionSheet.blurRadius = 0.0f;
  3078. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3079. actionSheet.buttonHeight = 50.0;
  3080. actionSheet.cancelButtonHeight = 50.0f;
  3081. actionSheet.separatorHeight = 5.0f;
  3082. actionSheet.automaticallyTintButtonImages = @(NO);
  3083. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3084. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3085. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3086. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3087. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3088. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3089. // ******************************************* DIRECTORY *******************************************
  3090. if (_metadata.directory) {
  3091. BOOL lockDirectory = NO;
  3092. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3093. // Directory bloccata ?
  3094. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, dirServerUrl]];
  3095. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3096. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3097. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3098. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3099. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3100. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3101. height: 50.0
  3102. type: AHKActionSheetButtonTypeDisabled
  3103. handler: nil
  3104. ];
  3105. if (_metadata.cryptated == NO && !lockDirectory) {
  3106. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3107. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3108. backgroundColor:[UIColor whiteColor]
  3109. height: 50.0
  3110. type:AHKActionSheetButtonTypeDefault
  3111. handler:^(AHKActionSheet *as) {
  3112. [self openWindowShare:_metadata];
  3113. }];
  3114. }
  3115. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3116. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3117. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3118. backgroundColor:[UIColor whiteColor]
  3119. height: 50.0
  3120. type:AHKActionSheetButtonTypeDefault
  3121. handler:^(AHKActionSheet *as) {
  3122. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3123. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3124. textField.text = _metadata.fileNamePrint;
  3125. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  3126. //textField.delegate = self;
  3127. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3128. }];
  3129. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3130. NSLog(@"Cancel action");
  3131. }];
  3132. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3133. UITextField *fileName = alertController.textFields.firstObject;
  3134. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3135. }];
  3136. okAction.enabled = NO;
  3137. [alertController addAction:cancelAction];
  3138. [alertController addAction:okAction];
  3139. [self presentViewController:alertController animated:YES completion:nil];
  3140. }];
  3141. }
  3142. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3143. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3144. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3145. backgroundColor:[UIColor whiteColor]
  3146. height: 50.0
  3147. type:AHKActionSheetButtonTypeDefault
  3148. handler:^(AHKActionSheet *as) {
  3149. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3150. }];
  3151. }
  3152. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && _metadata.cryptated == NO) {
  3153. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3154. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3155. backgroundColor:[UIColor whiteColor]
  3156. height: 50.0
  3157. type:AHKActionSheetButtonTypeDefault
  3158. handler:^(AHKActionSheet *as) {
  3159. // Settings new folder Automatatic upload
  3160. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3161. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  3162. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  3163. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  3164. if (app.activeAccount.length > 0 && app.activePhotos)
  3165. [app.activePhotos reloadDatasourceForced];
  3166. [self readFolder:serverUrl];
  3167. NSLog(@"[LOG] Update Folder Photo");
  3168. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  3169. if ([autoUploadPath length] > 0)
  3170. [[CCSynchronize sharedSynchronize] synchronizedFolder:autoUploadPath selector:selectorReadFolder];
  3171. }];
  3172. }
  3173. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  3174. [actionSheet addButtonWithTitle:titoloLock
  3175. image:[UIImage imageNamed:@"actionSheetLock"]
  3176. backgroundColor:[UIColor whiteColor]
  3177. height: 50.0
  3178. type:AHKActionSheetButtonTypeEncrypted
  3179. handler:^(AHKActionSheet *as) {
  3180. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3181. }];
  3182. }
  3183. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3184. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3185. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3186. backgroundColor:[UIColor whiteColor]
  3187. height: 50.0
  3188. type:AHKActionSheetButtonTypeEncrypted
  3189. handler:^(AHKActionSheet *as) {
  3190. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3191. }];
  3192. }
  3193. [actionSheet show];
  3194. }
  3195. // ******************************************* FILE *******************************************
  3196. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3197. UIImage *iconHeader;
  3198. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3199. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3200. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3201. else
  3202. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3203. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3204. image: iconHeader
  3205. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3206. height: 50.0
  3207. type: AHKActionSheetButtonTypeDisabled
  3208. handler: nil
  3209. ];
  3210. if (_metadata.cryptated == NO) {
  3211. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3212. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3213. backgroundColor:[UIColor whiteColor]
  3214. height: 50.0
  3215. type:AHKActionSheetButtonTypeDefault
  3216. handler:^(AHKActionSheet *as) {
  3217. [self openWindowShare:_metadata];
  3218. }];
  3219. }
  3220. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3221. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3222. backgroundColor:[UIColor whiteColor]
  3223. height: 50.0
  3224. type:AHKActionSheetButtonTypeDefault
  3225. handler:^(AHKActionSheet *as) {
  3226. [self performSelector:@selector(openIn:) withObject:_metadata];
  3227. }];
  3228. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3229. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3230. backgroundColor:[UIColor whiteColor]
  3231. height: 50.0
  3232. type:AHKActionSheetButtonTypeDefault
  3233. handler:^(AHKActionSheet *as) {
  3234. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3235. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3236. //textField.placeholder = _metadata.fileNamePrint;
  3237. textField.text = _metadata.fileNamePrint;
  3238. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3239. }];
  3240. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3241. NSLog(@"Cancel action");
  3242. }];
  3243. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3244. UITextField *fileName = alertController.textFields.firstObject;
  3245. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3246. }];
  3247. okAction.enabled = NO;
  3248. [alertController addAction:cancelAction];
  3249. [alertController addAction:okAction];
  3250. [self presentViewController:alertController animated:YES completion:nil];
  3251. }];
  3252. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3253. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3254. backgroundColor:[UIColor whiteColor]
  3255. height: 50.0
  3256. type:AHKActionSheetButtonTypeDefault
  3257. handler:^(AHKActionSheet *as) {
  3258. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3259. }];
  3260. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3261. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3262. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3263. backgroundColor:[UIColor whiteColor]
  3264. height: 50.0
  3265. type:AHKActionSheetButtonTypeDefault
  3266. handler:^(AHKActionSheet *as) {
  3267. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3268. }];
  3269. }
  3270. if (app.isCryptoCloudMode) {
  3271. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3272. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3273. backgroundColor:[UIColor whiteColor]
  3274. height: 50.0
  3275. type:AHKActionSheetButtonTypeEncrypted
  3276. handler:^(AHKActionSheet *as) {
  3277. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3278. }];
  3279. }
  3280. #ifdef DEBUG
  3281. /*
  3282. [actionSheet addButtonWithTitle:@"Hide file"
  3283. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"admin"] color:[NCBrandColor sharedInstance].brand]
  3284. backgroundColor:[UIColor whiteColor]
  3285. height: 50.0
  3286. type:AHKActionSheetButtonTypeDefault
  3287. handler:^(AHKActionSheet *as) {
  3288. [[NCManageDatabase sharedInstance] setMetadataStatusWithFileID:_metadata.fileID status:k_metadataStatusHide];
  3289. [self reloadDatasource];
  3290. }];
  3291. */
  3292. #endif
  3293. [actionSheet show];
  3294. }
  3295. // ******************************************* TEMPLATE *******************************************
  3296. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3297. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3298. image: [UIImage imageNamed:_metadata.iconName]
  3299. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3300. height: 50.0
  3301. type: AHKActionSheetButtonTypeDisabled
  3302. handler: nil
  3303. ];
  3304. if ([_metadata.model isEqualToString:@"note"]) {
  3305. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3306. image:[UIImage imageNamed:@"actionSheetRename"]
  3307. backgroundColor:[UIColor whiteColor]
  3308. height: 50.0
  3309. type:AHKActionSheetButtonTypeDefault
  3310. handler:^(AHKActionSheet *as) {
  3311. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3312. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3313. textField.placeholder = _metadata.fileNamePrint;
  3314. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3315. }];
  3316. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3317. NSLog(@"Cancel action");
  3318. }];
  3319. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3320. UITextField *fileName = alertController.textFields.firstObject;
  3321. [self performSelectorOnMainThread:@selector(renameNote:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3322. }];
  3323. okAction.enabled = NO;
  3324. [alertController addAction:cancelAction];
  3325. [alertController addAction:okAction];
  3326. [self presentViewController:alertController animated:YES completion:nil];
  3327. }];
  3328. }
  3329. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3330. image:[UIImage imageNamed:@"actionSheetMove"]
  3331. backgroundColor:[UIColor whiteColor]
  3332. height: 50.0
  3333. type:AHKActionSheetButtonTypeDefault
  3334. handler:^(AHKActionSheet *as) {
  3335. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3336. }];
  3337. [actionSheet show];
  3338. }
  3339. }
  3340. #pragma --------------------------------------------------------------------------------------------
  3341. #pragma mark - ==== Datasource ====
  3342. #pragma --------------------------------------------------------------------------------------------
  3343. - (void)clearDateReadDataSource:(NSNotification *)notification
  3344. {
  3345. _dateReadDataSource = Nil;
  3346. [self reloadDatasource];
  3347. }
  3348. - (void)reloadDatasource
  3349. {
  3350. [self reloadDatasource:_serverUrl];
  3351. }
  3352. - (void)reloadDatasource:(NSString *)serverUrl
  3353. {
  3354. // test
  3355. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3356. return;
  3357. // Search Mode
  3358. if(_isSearchMode) {
  3359. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3360. [self tableViewReloadData];
  3361. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3362. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3363. _noFilesSearchDescription = @"";
  3364. }
  3365. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3366. _noFilesSearchTitle = @"";
  3367. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3368. }
  3369. [self.tableView reloadEmptyDataSet];
  3370. return;
  3371. }
  3372. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3373. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3374. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3375. if (main) {
  3376. [main reloadDatasource];
  3377. } else {
  3378. [self tableViewReloadData];
  3379. [app.activeTransfers reloadDatasource];
  3380. }
  3381. return;
  3382. }
  3383. [app.activeTransfers reloadDatasource];
  3384. // Settaggio variabili per le ottimizzazioni
  3385. _directoryGroupBy = [CCUtility getGroupBySettings];
  3386. _directoryOrder = [CCUtility getOrderSettings];
  3387. // Controllo data lettura Data Source
  3388. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  3389. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3390. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3391. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3392. _dateReadDataSource = [NSDate date];
  3393. // Data Source
  3394. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", app.activeAccount, [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl], k_metadataStatusNormal] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3395. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3396. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3397. } else {
  3398. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3399. }
  3400. [self tableViewReloadData];
  3401. }
  3402. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3403. {
  3404. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3405. if (selectedRows.count > 0) {
  3406. for (NSIndexPath *selectionIndex in selectedRows) {
  3407. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3408. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3409. [metadatas addObject:metadata];
  3410. }
  3411. }
  3412. return metadatas;
  3413. }
  3414. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3415. {
  3416. NSInteger section = indexPath.section + 1;
  3417. NSInteger row = indexPath.row + 1;
  3418. NSInteger totSections = [_sectionDataSource.sections count] ;
  3419. if ((totSections < section) || (section > totSections)) {
  3420. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3421. return nil;
  3422. }
  3423. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3424. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3425. if (fileIDs) {
  3426. NSInteger totRows =[fileIDs count] ;
  3427. if ((totRows < row) || (row > totRows)) {
  3428. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3429. return nil;
  3430. }
  3431. } else {
  3432. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3433. return nil;
  3434. }
  3435. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3436. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3437. return metadata;
  3438. }
  3439. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3440. {
  3441. NSInteger totSections =[_sectionDataSource.sections count] ;
  3442. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3443. #if DEBUG
  3444. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3445. [alertView show];
  3446. #endif
  3447. return nil;
  3448. }
  3449. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3450. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3451. }
  3452. #pragma --------------------------------------------------------------------------------------------
  3453. #pragma mark - ==== Table ====
  3454. #pragma --------------------------------------------------------------------------------------------
  3455. - (void)tableViewSelect:(BOOL)edit
  3456. {
  3457. // chiudiamo eventuali swipe aperti
  3458. if (edit)
  3459. [self.tableView setEditing:NO animated:NO];
  3460. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3461. [self.tableView setEditing:edit animated:YES];
  3462. _isSelectedMode = edit;
  3463. if (edit)
  3464. [self setUINavigationBarSelected];
  3465. else
  3466. [self setUINavigationBarDefault];
  3467. [_selectedFileIDsMetadatas removeAllObjects];
  3468. [self setTitle];
  3469. }
  3470. - (void)tableViewReloadData
  3471. {
  3472. // store selected cells before relod
  3473. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3474. //store swipeOffset before relod
  3475. [_statusSwipeCell removeAllObjects];
  3476. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3477. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3478. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3479. }
  3480. // reload table view
  3481. [self.tableView reloadData];
  3482. // selected cells stored
  3483. for (NSIndexPath *path in indexPaths)
  3484. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3485. [self setTableViewFooter];
  3486. if (self.tableView.editing)
  3487. [self setTitle];
  3488. }
  3489. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3490. {
  3491. if (tableView.editing == 1) {
  3492. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3493. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3494. return NO;
  3495. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier != k_taskIdentifierDone || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3496. return NO;
  3497. else
  3498. return YES;
  3499. } else {
  3500. [_selectedFileIDsMetadatas removeAllObjects];
  3501. }
  3502. return YES;
  3503. }
  3504. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3505. {
  3506. return 60;
  3507. }
  3508. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3509. {
  3510. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3511. }
  3512. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3513. {
  3514. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3515. }
  3516. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3517. {
  3518. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3519. NSString *sectionTitle = [sections objectAtIndex:section];
  3520. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3521. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3522. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3523. return 20.f;
  3524. }
  3525. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3526. {
  3527. float shift;
  3528. UIVisualEffectView *visualEffectView;
  3529. NSString *titleSection;
  3530. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3531. return nil;
  3532. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3533. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3534. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3535. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3536. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3537. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3538. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3539. else titleSection = NSLocalizedString(titleSection,nil);
  3540. // Format title
  3541. NSString *currentDevice = [CCUtility currentDevice];
  3542. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3543. visualEffectView = [[UIVisualEffectView alloc] init];
  3544. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3545. } else {
  3546. UIVisualEffect *blurEffect;
  3547. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3548. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3549. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3550. }
  3551. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3552. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3553. shift = - 35;
  3554. else
  3555. shift = - 20;
  3556. } else shift = - 10;
  3557. // Title
  3558. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3559. titleLabel.backgroundColor = [UIColor clearColor];
  3560. titleLabel.textColor = [UIColor blackColor];
  3561. titleLabel.font = [UIFont systemFontOfSize:12];
  3562. titleLabel.textAlignment = NSTextAlignmentLeft;
  3563. titleLabel.text = titleSection;
  3564. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3565. [visualEffectView addSubview:titleLabel];
  3566. // Elements
  3567. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3568. elementLabel.backgroundColor = [UIColor clearColor];
  3569. elementLabel.textColor = [UIColor blackColor];;
  3570. elementLabel.font = [UIFont systemFontOfSize:12];
  3571. elementLabel.textAlignment = NSTextAlignmentRight;
  3572. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3573. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3574. NSUInteger rowsCount = [metadatas count];
  3575. if (rowsCount == 0) return nil;
  3576. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3577. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3578. [visualEffectView addSubview:elementLabel];
  3579. return visualEffectView;
  3580. }
  3581. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3582. {
  3583. return [_sectionDataSource.sections indexOfObject:title];
  3584. }
  3585. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3586. {
  3587. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3588. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3589. else
  3590. return nil;
  3591. }
  3592. /*
  3593. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3594. {
  3595. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3596. }
  3597. }
  3598. */
  3599. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3600. {
  3601. NSString *typeCell;
  3602. NSString *dataFile;
  3603. NSString *lunghezzaFile;
  3604. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3605. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  3606. return [tableView dequeueReusableCellWithIdentifier:@"CellMainTransfer"];
  3607. }
  3608. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3609. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3610. else typeCell = @"CellMainTransfer";
  3611. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3612. // variable base
  3613. cell.delegate = self;
  3614. cell.indexPath = indexPath;
  3615. // separator
  3616. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3617. // change color selection
  3618. UIView *selectionColor = [[UIView alloc] init];
  3619. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3620. cell.selectedBackgroundView = selectionColor;
  3621. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3622. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3623. // ----------------------------------------------------------------------------------------------------------
  3624. // DEFAULT
  3625. // ----------------------------------------------------------------------------------------------------------
  3626. cell.file.image = nil;
  3627. cell.status.image = nil;
  3628. cell.favorite.image = nil;
  3629. cell.shared.image = nil;
  3630. cell.local.image = nil;
  3631. cell.labelTitle.enabled = YES;
  3632. cell.labelTitle.text = @"";
  3633. cell.labelInfoFile.enabled = YES;
  3634. cell.labelInfoFile.text = @"";
  3635. cell.progressView.progress = 0.0;
  3636. cell.progressView.hidden = YES;
  3637. cell.cancelTaskButton.hidden = YES;
  3638. cell.reloadTaskButton.hidden = YES;
  3639. cell.stopTaskButton.hidden = YES;
  3640. // Encrypted color
  3641. if (metadata.cryptated) {
  3642. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3643. } else {
  3644. cell.labelTitle.textColor = [UIColor blackColor];
  3645. }
  3646. // ----------------------------------------------------------------------------------------------------------
  3647. // File Name & Folder
  3648. // ----------------------------------------------------------------------------------------------------------
  3649. // nome del file
  3650. cell.labelTitle.text = metadata.fileNamePrint;
  3651. // è una directory
  3652. if (metadata.directory) {
  3653. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3654. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3655. lunghezzaFile = @" ";
  3656. // ----------------------------------------------------------------------------------------------------------
  3657. // Favorite Folder
  3658. // ----------------------------------------------------------------------------------------------------------
  3659. if (metadata.favorite) {
  3660. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3661. }
  3662. } else {
  3663. // File
  3664. dataFile = [CCUtility dateDiff:metadata.date];
  3665. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3666. // Plist ancora da scaricare
  3667. if (metadata.cryptated && [metadata.title length] == 0) {
  3668. dataFile = @" ";
  3669. lunghezzaFile = @" ";
  3670. }
  3671. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3672. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3673. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3674. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3675. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3676. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3677. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3678. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3679. cell.local.image = [UIImage imageNamed:@"local"];
  3680. else
  3681. cell.local.image = nil;
  3682. //cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3683. //cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3684. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3685. }
  3686. // Plist ancora da scaricare
  3687. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3688. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3689. cell.accessoryType = UITableViewCellAccessoryNone;
  3690. }
  3691. // ----------------------------------------------------------------------------------------------------------
  3692. // File Image View
  3693. // ----------------------------------------------------------------------------------------------------------
  3694. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3695. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3696. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3697. } else {
  3698. if (metadata.directory)
  3699. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3700. else
  3701. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3702. if (metadata.thumbnailExists)
  3703. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3704. }
  3705. // ----------------------------------------------------------------------------------------------------------
  3706. // Image Status cyptated & Lock Passcode
  3707. // ----------------------------------------------------------------------------------------------------------
  3708. // File Cyptated
  3709. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3710. cell.status.image = [UIImage imageNamed:@"lock"];
  3711. }
  3712. // Directory con passcode lock attivato
  3713. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3714. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3715. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3716. cell.status.image = [UIImage imageNamed:@"passcode"];
  3717. // ----------------------------------------------------------------------------------------------------------
  3718. // Favorite
  3719. // ----------------------------------------------------------------------------------------------------------
  3720. if (metadata.favorite) {
  3721. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3722. }
  3723. // ----------------------------------------------------------------------------------------------------------
  3724. // Share
  3725. // ----------------------------------------------------------------------------------------------------------
  3726. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3727. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3728. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3729. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3730. // Aggiungiamo il Tap per le shared
  3731. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3732. if (isShare) {
  3733. if (metadata.directory) {
  3734. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3735. cell.shared.userInteractionEnabled = NO;
  3736. } else {
  3737. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3738. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3739. [tap setNumberOfTapsRequired:1];
  3740. cell.shared.userInteractionEnabled = YES;
  3741. [cell.shared addGestureRecognizer:tap];
  3742. }
  3743. }
  3744. if (isMounted) {
  3745. if (metadata.directory) {
  3746. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3747. cell.shared.userInteractionEnabled = NO;
  3748. } else {
  3749. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3750. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3751. [tap setNumberOfTapsRequired:1];
  3752. cell.shared.userInteractionEnabled = YES;
  3753. [cell.shared addGestureRecognizer:tap];
  3754. }
  3755. }
  3756. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3757. if (metadata.directory) {
  3758. if ([shareLink length] > 0)
  3759. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3760. if ([shareUserAndGroup length] > 0)
  3761. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3762. cell.shared.userInteractionEnabled = NO;
  3763. } else {
  3764. if ([shareLink length] > 0)
  3765. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3766. if ([shareUserAndGroup length] > 0)
  3767. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3768. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3769. [tap setNumberOfTapsRequired:1];
  3770. cell.shared.userInteractionEnabled = YES;
  3771. [cell.shared addGestureRecognizer:tap];
  3772. }
  3773. }
  3774. } else {
  3775. cell.shared.userInteractionEnabled = NO;
  3776. }
  3777. // ----------------------------------------------------------------------------------------------------------
  3778. // downloadFile
  3779. // ----------------------------------------------------------------------------------------------------------
  3780. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3781. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3782. else cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3783. // sessionTaskIdentifier : RELOAD + STOP
  3784. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3785. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3786. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3787. cell.cancelTaskButton.hidden = NO;
  3788. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3789. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3790. cell.reloadTaskButton.hidden = NO;
  3791. }
  3792. // sessionTaskIdentifierPlist : RELOAD
  3793. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3794. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3795. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3796. cell.reloadTaskButton.hidden = NO;
  3797. }
  3798. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3799. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3800. if (progress > 0) {
  3801. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3802. else cell.progressView.progressTintColor = [UIColor blackColor];
  3803. cell.progressView.progress = progress;
  3804. cell.progressView.hidden = NO;
  3805. }
  3806. // ----------------------------------------------------------------------------------------------------------
  3807. // downloadFile Error
  3808. // ----------------------------------------------------------------------------------------------------------
  3809. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3810. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3811. if ([metadata.sessionError length] == 0)
  3812. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3813. else
  3814. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3815. }
  3816. }
  3817. // ----------------------------------------------------------------------------------------------------------
  3818. // uploadFile
  3819. // ----------------------------------------------------------------------------------------------------------
  3820. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3821. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3822. else cell.status.image = [UIImage imageNamed:@"statusupload"];
  3823. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3824. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3825. cell.cancelTaskButton.hidden = NO;
  3826. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3827. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3828. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3829. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusstopcrypto"];
  3830. else cell.status.image = [UIImage imageNamed:@"statusstop"];
  3831. cell.reloadTaskButton.hidden = NO;
  3832. cell.stopTaskButton.hidden = YES;
  3833. } else {
  3834. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3835. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3836. cell.stopTaskButton.hidden = NO;
  3837. cell.reloadTaskButton.hidden = YES;
  3838. }
  3839. // se non c'è una preview in bianconero metti l'immagine di default
  3840. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3841. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3842. cell.labelTitle.enabled = NO;
  3843. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3844. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3845. if (progress > 0) {
  3846. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3847. else cell.progressView.progressTintColor = [UIColor blackColor];
  3848. cell.progressView.progress = progress;
  3849. cell.progressView.hidden = NO;
  3850. }
  3851. // ----------------------------------------------------------------------------------------------------------
  3852. // uploadFileError
  3853. // ----------------------------------------------------------------------------------------------------------
  3854. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3855. cell.labelTitle.enabled = NO;
  3856. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3857. if ([metadata.sessionError length] == 0)
  3858. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3859. else
  3860. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3861. }
  3862. }
  3863. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3864. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3865. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3866. // ======== MGSwipe ========
  3867. //Left only plain
  3868. if (metadata.cryptated == NO) {
  3869. if (metadata.favorite)
  3870. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_unfavorite_", nil)] icon:[UIImage imageNamed:@"swipeUnfavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3871. else
  3872. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_favorite_", nil)] icon:[UIImage imageNamed:@"swipeFavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3873. cell.leftExpansion.buttonIndex = 0;
  3874. cell.leftExpansion.fillOnTrigger = NO;
  3875. //centerIconOverText
  3876. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3877. [favoriteButton centerIconOverText];
  3878. } else {
  3879. cell.leftButtons = [NSArray new];
  3880. }
  3881. //Right
  3882. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_delete_", nil)] icon:[UIImage imageNamed:@"swipeDelete"] backgroundColor:[UIColor redColor]], [MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_more_", nil)] icon:[UIImage imageNamed:@"swipeMore"] backgroundColor:[UIColor lightGrayColor]]];
  3883. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3884. //centerIconOverText
  3885. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3886. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3887. [deleteButton centerIconOverText];
  3888. [moreButton centerIconOverText];
  3889. //restore swipeOffset after relod
  3890. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3891. if (swipeOffset < 0) {
  3892. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3893. } else if (swipeOffset > 0) {
  3894. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3895. }
  3896. return cell;
  3897. }
  3898. - (void)setTableViewFooter
  3899. {
  3900. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3901. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3902. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3903. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3904. UIFont *appFont = [UIFont systemFontOfSize:12];
  3905. footerLabel.font = appFont;
  3906. footerLabel.textColor = [UIColor grayColor];
  3907. footerLabel.backgroundColor = [UIColor clearColor];
  3908. footerLabel.textAlignment = NSTextAlignmentCenter;
  3909. NSString *folders;
  3910. NSString *files;
  3911. NSString *footerText;
  3912. if (_sectionDataSource.directories > 1) {
  3913. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3914. } else if (_sectionDataSource.directories == 1){
  3915. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3916. } else {
  3917. folders = @"";
  3918. }
  3919. if (_sectionDataSource.files > 1) {
  3920. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3921. } else if (_sectionDataSource.files == 1){
  3922. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3923. } else {
  3924. files = @"";
  3925. }
  3926. if ([folders isEqualToString:@""]) {
  3927. footerText = files;
  3928. } else if ([files isEqualToString:@""]) {
  3929. footerText = folders;
  3930. } else {
  3931. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3932. }
  3933. footerLabel.text = footerText;
  3934. [footerView addSubview:footerLabel];
  3935. [self.tableView setTableFooterView:footerView];
  3936. }
  3937. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3938. {
  3939. NSString *textMessage;
  3940. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3941. // settiamo il record file.
  3942. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3943. // se non può essere selezionata deseleziona
  3944. if ([cell isEditing] == NO)
  3945. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3946. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3947. if (self.tableView.editing) {
  3948. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3949. [self setTitle];
  3950. return;
  3951. }
  3952. // test crash
  3953. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3954. if (indexPath.row >= [metadatas count]) return;
  3955. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3956. // se è in corso una sessione
  3957. if ([_metadata.session length] > 0) return;
  3958. if (_metadata.errorPasscode) {
  3959. // se UUID è nil lo sta ancora caricando quindi esci
  3960. if (!_metadata.uuid) return;
  3961. // esiste un hint ??
  3962. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3963. // qui !! la richiesta della nuova passcode
  3964. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3965. // stesso UUID ... la password è stata modificata !!!!!!
  3966. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3967. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3968. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3969. [alertView show];
  3970. } else {
  3971. // UUID diverso.
  3972. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3973. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3974. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3975. [alertView show];
  3976. }
  3977. // chiediamo la passcode e ricarichiamo tutto.
  3978. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3979. viewController.delegate = self;
  3980. viewController.fromType = CCBKPasscodeFromPasscode;
  3981. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3982. viewController.passcodeInputView.maximumLength = 64;
  3983. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3984. viewController.inputViewTitlePassword = NO;
  3985. viewController.title = [NCBrandOptions sharedInstance].brand;
  3986. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3987. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3988. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3989. [self presentViewController:navigationController animated:YES completion:nil];
  3990. }
  3991. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3992. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3993. NSString* selector;
  3994. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3995. else selector = selectorLoadPlist;
  3996. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3997. return;
  3998. }
  3999. // se il plist è caricato ed è un modello aprilo
  4000. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  4001. // file
  4002. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  4003. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  4004. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  4005. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  4006. } else {
  4007. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  4008. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  4009. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  4010. }
  4011. }
  4012. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  4013. }
  4014. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  4015. {
  4016. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  4017. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  4018. [self setTitle];
  4019. }
  4020. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  4021. {
  4022. if (!indexPath)
  4023. return NO;
  4024. NSInteger section = indexPath.section;
  4025. NSInteger row = indexPath.row;
  4026. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  4027. //Make sure the specified section exists
  4028. if (section > lastSectionIndex)
  4029. return NO;
  4030. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  4031. return row <= rowCount;
  4032. }
  4033. #pragma --------------------------------------------------------------------------------------------
  4034. #pragma mark ===== Navigation ====
  4035. #pragma --------------------------------------------------------------------------------------------
  4036. - (BOOL)shouldPerformSegue
  4037. {
  4038. // if background return
  4039. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4040. if (self.view.window == NO)
  4041. return NO;
  4042. // Collapsed ma siamo già in detail esci
  4043. if (self.splitViewController.isCollapsed)
  4044. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4045. // Video in esecuzione esci
  4046. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4047. return YES;
  4048. }
  4049. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4050. {
  4051. id viewController = segue.destinationViewController;
  4052. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4053. tableMetadata *metadata;
  4054. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4055. UINavigationController *nav = viewController;
  4056. _detailViewController = (CCDetail *)nav.topViewController;
  4057. } else {
  4058. _detailViewController = segue.destinationViewController;
  4059. }
  4060. if ([sender isKindOfClass:[tableMetadata class]]) {
  4061. metadata = sender;
  4062. [allRecordsDataSourceImagesVideos addObject:sender];
  4063. } else {
  4064. metadata = _metadata;
  4065. for (NSString *fileID in _sectionDataSource.allEtag) {
  4066. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4067. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4068. [allRecordsDataSourceImagesVideos addObject:metadata];
  4069. }
  4070. }
  4071. _detailViewController.metadataDetail = metadata;
  4072. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4073. _detailViewController.dateFilterQuery = nil;
  4074. [_detailViewController setTitle:metadata.fileNamePrint];
  4075. }
  4076. // can i go to next viewcontroller
  4077. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4078. {
  4079. NSString *nomeDir;
  4080. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4081. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  4082. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4083. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  4084. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4085. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4086. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4087. viewController.delegate = self;
  4088. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4089. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4090. viewController.inputViewTitlePassword = YES;
  4091. if ([CCUtility getSimplyBlockCode]) {
  4092. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4093. viewController.passcodeInputView.maximumLength = 6;
  4094. } else {
  4095. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4096. viewController.passcodeInputView.maximumLength = 64;
  4097. }
  4098. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4099. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4100. viewController.touchIDManager = touchIDManager;
  4101. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4102. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4103. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4104. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4105. [self presentViewController:navController animated:YES completion:nil];
  4106. return;
  4107. }
  4108. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4109. else nomeDir = _metadata.fileName;
  4110. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4111. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4112. if (viewController.isViewLoaded == false || viewController == nil) {
  4113. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4114. viewController.isFolderEncrypted = _metadata.cryptated;
  4115. viewController.serverUrl = serverUrlPush;
  4116. viewController.titleMain = _metadata.fileNamePrint;
  4117. viewController.textBackButton = _titleMain;
  4118. // save self
  4119. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4120. }
  4121. // OFF SearchBar
  4122. [viewController cancelSearchBar];
  4123. [self.navigationController pushViewController:viewController animated:YES];
  4124. }
  4125. }
  4126. @end